Generating API_KEY for each new User

I need to automatically generate API_KEY for each new User.

So I hook afterSave (because I need to know record ‘id’). From within afterSave() I generate and set ‘api_key’ property and call $this->save() - at which point it blows up with “Duplicate entry ‘6’ for key ‘PRIMARY’”.

When I try $this-update() instead - it blows up with "The active record cannot be updated because it is new". So how can I update/save record from within afterSave() ?

At the afterSave point the record still has the scenario ‘insert’ and so will always run an insert. You can either setScenario( ‘update’ ) and then call save. Or you can use updateAttributes(), iirc.

Added: setScenario(‘update’) with the same results:

Subsequent $this->save() blows with “Duplicate entry … for key ‘PRIMARY’”

Subsequent $this->update() blows with "The active record cannot be updated because it is new"

Gleb

Ok, here’s how it will work:


    //-----------------------------------------------------------------------

    public function afterSave ()

    {

        parent::afterSave();


        $is_new_record = $this->getIsNewRecord ();

        $this->setIsNewRecord (false);

        // Set necessary attributes:

        // $this->api_key = md5(microtime());

        $this->update();

        $this->setIsNewRecord ($is_new_record);

    }

    //-----------------------------------------------------------------------



Fixed.

Gleb