We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Double execution of a model setter

Hi everyone. I'm struggling with a problem with setter on my model.

Lets say I have a model User

class User extends \Phalcon\Mvc\Model
{
    public function setPassword()
    {
        $this->password = md5($password);
    }
}

when I'm trying to set a password from controller to a new user


    public function newAction()
    {
        $user = new User();
        $user->setPassword($password);
        $user->save();
    }

setPassword gets called twice. In effect saved password is a hash of a hash of password string.

Is this a known issue?

Sometimes I might need to assign a value to the field without setter (although setter exists). $user->password seem to call setPassword anyway.

edited May '16

Try create hash with the method "beforeSave"

public function beforeCreate(){
    $this->password = md5($this->password);
}


11.6k
edited May '16

I think it's because the ->save() method implicitely call the setter too. Maybe you have just to assign the password then save:

<?php

    public function newAction()
    {
        $user = new User();
        $user->password = $mypassword;
        $user->save();
    }

It's silly, setter is for setting something....

I think it's because the ->save() method implicitely call the setter too. Maybe you have just to assign the password then save:

<?php

  public function newAction()
   {
       $user = new User();
       $user->password = $mypassword;
       $user->save();
   }