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

How to save a record if I dont want all fields saved?

I have an user table: id, username, password. Password is md5 encoded. So lets say I want to modify the username. I findFirst(id) the record, make the modification, and save. The md5 encoding run in "beforeSave". If I do it like that, it will always reencode the password. If I set 'null' for password, it will fail with "password is required" as it cant be null.



85.5k

you have to remove your pass encoding from beforeSave, just do it when you are creating a user


$record = new \MyApp\Models\User();
$record->name  = $name;
$recod->pass = md5($pass);

//if it is possible stop using md5, in controller : $this->security->hash($password); ... more information you can see here https://php.net/manual/en/function.password-hash.php



28.2k

it would be too easy like that, and in addition new record can be created by 1000 places, and its easy to miss the md5 encoding

you have to remove your pass encoding from beforeSave, just do it when you are creating a user


$record = new \MyApp\Models\User();
$record->name  = $name;
$recod->pass = md5($pass);

//if it is possible stop using md5, in controller : $this->security->hash($password); ... more information you can see here https://php.net/manual/en/function.password-hash.php



85.5k

class users {

    public static function createUser($data, $pass){

        $user = new \MyApp\Models\Users($data);

        $user->password = md5($pass);

        if ($user->save() === false){
            return $user->getMessages();
        }

        return true;
    }
}

$check = users::createUser(['name' => 'koko', 'age' => 16], 'mypass');

if ($check !== true){
    foreach ($check AS $message){
        // display error messages
    }
}

or you can move the messages logic inside the function, depens of how do you structure your app



85.5k

mmm nope, got it


function beforeSave(){
    if ($this->id == null){
        $tthis->password = md5($passowrd);
    }
}

or use beforeCreate

https://docs.phalcon.io/en/latest/reference/models.html



17.5k

As an aside... md5 is easily cracked. Why are you not using the security password hashing built into Phalcon?

The best way to prevent the problem when you have blank password ow you wish it updated only when its set


class Users extends Model
{

    public function setPassword($password = null)
    {
        if (!$password) {
            $this->skipAttributes(array('password'));
        } else {
            $this->password = $password;
        }
    }

    public function beforeSave()
    {
        $this->password = sha1($this->password);
    }

}

in this case when form sets password as blank, becouse it's not changed model set it to be skipped ;) or you can add this skip in initialize and when it's set remove it from skip