Isnewrecord Returning True On Model Instantiated By Findbypk()

I seem to be getting all the weird errors recently.

I finally got my save() issue to work – briefly. (And I’m not sure what finally did it.) But now I have another problem: when I run save() on a model which I’ve loaded via findByPk, it gives me a duplicate primary key error on an INSERT statement. When I switch it over to use update(), I get:

The active record cannot be updated because it is new.

I put this into my code, just to test things out:

        // Find the existing record.

        $story_id = (int)$_POST['Story']['story_id'];

        echo "<p>Finding story by primary key.</p>";

        $story = Story::model()->findByPk( $story_id );

        echo "<p>isNewRecord: "; new dBug($story->isNewRecord); echo "<p>";

And that outputs this:

Finding story by primary key.

isNewRecord: TRUE

This seems completely nonsensical to me. The model is there, with all its data correctly loaded; it just doesn’t seem to reflect the fact that, yes, it’s come from an existing record in the database. Do I need to add an afterFind() method just to get my model to realize that it’s not new?

This should not happen. I advise you to post your framework version and try to debug through the findByPk method call to see where it should set the isNewRecord flag and why it doesn’t.

Are you using a __construct method in the model that is receiving the data? If so make sure it is receiving the default scenario param as that is what determines whether or not its a new record.

I would include a code snippet but apparently I’m subject to a spam filter :S

You saved me so much time with this tip. Thank you.

Saved me too ! 6 years after…