i have a problem. I have a required field "password". I want to ignore the last field when i clicked on "update" button. Thank you for your attention.
My rules:
public function rules()
{
return [
[['username', 'role_id', 'surname', 'name', 'patronymic', 'email', 'password', 'department_id'], 'required'],
[['role_id', 'department_id'], 'integer'],
[['date_of_birth'], 'safe'],
[['password'], 'string', 'min' => 8],
[['username', 'surname', 'name', 'patronymic', 'email', 'telephone', 'skype', 'avatar', 'password'], 'string', 'max' => 255],
[['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']],
[['department_id'], 'exist', 'skipOnError' => true, 'targetClass' => Department::className(), 'targetAttribute' => ['department_id' => 'id']],
[['file'], 'file', 'extensions' => 'png, jpg'],
['email', 'email'],
[['email', 'username'], 'unique'],
];`
Also in my User models i used BeforeSave function (to hash my password, when i created a new record).
public function beforeSave($insert)
{
if (isset($this->password)) {
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
}
return parent::beforeSave($insert);
}
My controller update action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$imageName = uniqid();
$model->file = UploadedFile::getInstance($model, 'file');
if (!empty($model->file)){
$model->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );
$model->avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
You can use scenarios to do this: docs, but u shouldn't hash password in beforeSave()
. Like in advanced template, create setter for password
OR create custom filter in rules + add scenario like 'on' => 'createUser'
or 'except' => 'updateUser'
.