Thanks to elbek and imehesz that suggested to look in this page. I solved this by using scenarios. I added my new code at the end of the post.
Hi all, I am a bit new in Yii, but have a lot of experience in PHP and other languages.
I have a quick question. I have a model for my Users table, and it has these rules (passoword required, password = password2, etc):
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('..., password, ...', 'required'),
...
array('password', 'length', 'max'=>32, 'min'=>6),
array('password2','length', 'max'=>32, 'min'=>6),
// compare password to repeated password
array('password', 'compare', 'compareAttribute'=>'password2'),
...
);
}
It works fine when I create the user, but when I update I have a issue.
I don’t have the password field in the update form (cause that field will be updated on a different screen). The problem is that when goes to actionUpdate() it tries to save ( in if($model->save()) ). It fails because ‘Password cannot be blank’.
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
if($model->save())
$this->redirect(array('index'));
}
$this->render('update',array(
'model'=>$model,
));
}
So I would like to know how can I tell the framework to omit the required validation for the password field (I will still like the other validations to run).
Thanks a lot
My new code is:
On the User model, the rules look like this:
public function rules()
{
return array(
array('..., ..., ...', 'required'),
array('password', 'required', 'on'=>'insert, updatePassword'),
...
// compare password to repeated password
array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'insert, updatePassword'),
...
);
}
On the UserControler, I did not have to change the actionCreate and actionUpdate. I added an actionUpdatePassword that looks like this:
public function actionUpdatePassword($id) {
$model=$this->loadModel($id);
if(isset($_POST['User']))
{
$model->setScenario('updatePassword'); // *** THIS activates the validations for the passwords ***
$model->attributes=$_POST['User'];
if($model->save()) {
$this->redirect(array('update', 'id' => $id));
}
}
$this->render('updatePassword',array(
'model'=>$model,
));
}