我的规则:
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'],
];`
同样在我的用户模型中,我使用了BeforeSave功能(当我创建新记录时,哈希我的密码)。
public function beforeSave($insert)
{
if (isset($this->password)) {
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
}
return parent::beforeSave($insert);
}
我的控制器更新操作:
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,
]);
}
}
答案 0 :(得分:0)
您可以使用方案执行此操作:docs,但您不应在beforeSave()
中哈希密码。与高级模板一样,为password
创建setter或在规则中创建自定义过滤器+添加'on' => 'createUser'
或'except' => 'updateUser'
等场景。