User Registration: setting id

Ok, so I am new to Yii.

I have a user registration form that works great when I manually set the user id value within the controller action.

My question is: what is the best practice for getting the id value to insert with the new User?

I am basically just going to write the SQL select statement that returns the max id value from the User table. Then make the new Users ID equal to the max + 1.

The above "code" should be part of the beforeSave method correct?

Thanks in advance for you advice.

(sorry for such a basic question but it is uncovered in the Book, as well as any of the tutorials.)

Best solution to this is to use an autoincrement field…

Thanks for the prompt reply. The User class inserts properly into the table now with the auto-increment property. However, I need to assign a role to the user when they register.

Where is the best place to put

$auth->assign('renter', $this->id);

In the assign call, is $this->id the proper reference use the auto-incremented id value from the insert.

You can place after the save, the id will be filled with the generated one.

Ok so:

here is the main part of my controller action:



				$user->user_type_id= 1;//unneeded field now that I am using the CDBAuthManager

        		// validates user input and redirect to previous page if validated


        		//$valid=$name->validate() && $valid;







here is my afterSave() on the User Model:

public function afterSave()


		$auth = Yii::app()->authManager;

		$auth->assign('renter', $this->id);


please double check my afterSave method.

Now the main problem is: when the form tries to validate, "ID cannot be blank" is the error received.

Manually setting the id in the controller to 0 will insert the user just fine(auto-incremented), but fails the assign call because the id value does not overwrite the 0 value with the auto-incremented value.

Any advice?

Better to call parent implementation:

public function afterSave()


                $auth = Yii::app()->authManager;

                $auth->assign('renter', $this->id);

                return parent::afterSave();


I don’t remember why, but is better to do so…

I fixed the validation error by modifying the rules() on the User model, removing the id from the required fields array.

Topic can be seen as closed.

Thanks to mdomba and zaccaria.