The active record cannot be updated because it is new

I tried to call saveAttributes() to insert to my model and I got this exception - "The active record cannot be updated because it is new".

$message=new Message;

$message->saveAttributes(array(‘user’=>$uid));

"The active record cannot be updated because it is new".

You should use the method "save".

"saveAttributes" can only be used to update existing models. Check the documentation.

As the documentation for it says - "this method only saves the specified attributes of an existing row dataset"… so it can be used only for existing records (UPDATE)

where we include the condition to update??

i dnt understand how saveAttributes works??

If you do

$message = new Message;

you are creating a new record… so it’s not UPDATING but INSERTING and you cannot use saveAttributes()

ok…ok…i undestood… is it is only using after ‘aftersave()’ ?? right?

afterSave() ???

it can be used only with existing record… for example




//.. get an existing record

$postRecord=Post::model()->findByPk($postID);

//.. assign new value to the attribute "name"

$postRecord->name='new name';

//.. save only that one attribute... not the complete record

$postRecord->saveAttributes(array('name'));



so need to write code like

$message = new Message;

$message->id = ‘…’;

$message->uid = ‘$user’;

$message-save();

[where id is the primary key] … is it correct??

Yes…

NOTE: if the primary key is an “autoincrement” than you don’t assign anything to it…

ok thank u very much mdomba …

the primary key is autoincrement…

so… ok…

$message = new Message;

$message->uid = ‘$user’;

$message-save();

this is not working… why??

How is not working?

Do you get any error?

NOTE: What are you assigning here is the text ‘$user’ not the value of the variable user…

NOTE2: when posting code use the code button ( <> - on the editor toolbar) so that the code is more readable

no nothig… no error after all… not inserting any value table…

Do you have DEBUG enabled?

what is the type of the UID field… is it a number?

as I wrote you above you are assigning to it a text value… that could be the reason for not saving…

mdomba, now its working … its the problem with my rules()…

the save() checks the rules()!!

i have one more field in the model… that is also under required!!!

thank u… thank u…

Very nice to see that mdomba helped you and it is working now.

Please don’t forget to vote for him since he helped you.

sure mentel …

Thanks for this post I really got useful. BTW It was not for me but the way your post that worked for me thanks much.