1

I'm doing user editing facility for my admin panel. I want to ignore empty password on update, but not on create.

I have following validation rules for User model:

public static $rules = array(
    'login'                 => 'required|max:255|alpha_dash|unique',
    'displayname'           => 'required|max:255|unique',
    'email'                 => 'required|email|max:255|unique',
    'password'              => 'required|confirmed',
    'password_confirmation' => 'required',
);

But it doesn't let me update user model when I don't pass password to it. It just complains about not having a password.

How to make it work?

Cysioland
  • 1,126
  • 1
  • 9
  • 21

3 Answers3

3

You can do something like this in your controller:

if ($user->exists)
{
    $user::$rules['password'] = (Input::get('password')) ? 'required|confirmed' : '';
    $user::$rules['password_confirmation'] = (Input::get('password')) ? 'required' : '';
}

$user->save();
1

That's something people are still thinking about. But usually create rules and update rules will be different.

public static $create_rules = array(
    'login'                 => 'required|max:255|alpha_dash|unique',
    'displayname'           => 'required|max:255|unique',
    'email'                 => 'required|email|max:255|unique',
    'password'              => 'required|confirmed',
    'password_confirmation' => 'required',
);

public static $update_rules = array(
    'login'                 => 'required|max:255|alpha_dash|unique',
    'displayname'           => 'required|max:255|unique',
    'email'                 => 'required|email|max:255|unique',
);

Then in your validation code, you can

if ( ! $this->exists || Input::get('password'))
{
   $validation_rules = static::$create_rules;
}
else
{
   $validation_rules = static::$update_rules;
}
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • But when I somehow want to change the password, it doesn't need confirmation then. It is undesirable. – Cysioland Jan 08 '14 at 18:23
  • The code was just to gave you some thoughts about it. You can check if there's a password filled in the input, then you can just use the create rules again. It all depends on how you'll change your user password. Mine is a form with 2 inputs only. No other user data involved. Edited. – Antonio Carlos Ribeiro Jan 08 '14 at 18:33
1

If you want to consolidate this behavior to the model itself (so it doesn't matter where it's being created/saved from) you can utilize Ardent's beforeValidate function to change the rules before validating:

public function beforeValidate() { if(isset($this->id)) { self::$rules['password'] = 'confirmed'; self::$rules['password_confirmation'] = ''; } }

You would just add code like that anywhere in the model in question.

Beau
  • 1,771
  • 1
  • 15
  • 20