Save() doesnt set id

I am saving a new record using the standard yii mechanism but I have the id column which is the PK as a control on the form so I can load a previous instance. The code that does stuff after the save() relies on $model->id. Prior to adding the dropdownlist that is linked to id this worked fine. Now I find that although save() does actually save the new entity, and in the log I can see an insert statement, the id property which is the PK is not set so I run into trouble further on.

Any ideas why the id would not be set when the insert has successfully happened and save returned true?

is the id field set to auto increment?

are the ids set in the table?

Yes and Yes. The same model works fine in another controller and used to work in this one until I added the code to reload older entities - this seems to have thrown it. The changes are to add a drop down list with all entities and then when this is selected to load an older one into the form.

On the form I added

    	<label for="transTo">Choose recipient:</label>


          echo CHtml::activeDropDownList($model,'id',        CHtml::listData(Recipient::model()->findAllByAttributes(array('customer_id'=>yii::app()->user->getState('c_id',-1))), 'id', 'NameAndCountry'),

          array('empty'=>array(0=>'Resend to a previous recipient'),





The in the controller I load the model if no buttons were pressed and ID is passed in. Problem is that now when there is no ID (I have tried 0 or ‘’ in the id property prior to save) save() works fine but when I trace immediately after save() I dont see a value in the id property.

if($model->save()) {

  yii::trace($model->id.':'.$model->Surname,'**************************************after save');

but there is a new row in the db and I see in the log that an insert happpened.

I have now solved this - I am not sure it isnt a bug. I have to set the PK to null before save.

            if ($model->id==0) {





                // form inputs are valid, do something here

                if($model->save()) {

Indeed I’ve witnessed the same problem. I think it could be because the id in the form is set to empty string (has to be null like suggested). The id is set in the database properly.

I had the same issue and forcing $model->id = null; before save fixed it.

In my context, i used the same form for create and update so my posted data returned id=0 when i’m creating a new row.

I affect $model->attributes = $_POST[‘mydata’] and $model->id = 0 <_<

did not work for me.


resulted in error



had no effect

this didn’t work either


That’s a pretty old bug, here you can find the issue and a dirty fix:

I had the same issue. To resolve your problem, do not bind your primary key attribute in your partial view. For example when I add this line to my partial view:

<?php echo $form->hiddenField($model,'id'); ?>

then after


, my primary key is empty.