Skip to content

Instantly share code, notes, and snippets.

@monbang
Created June 16, 2020 06:37
Show Gist options
  • Save monbang/b73882fc29976c5ef0874a6a61d2f712 to your computer and use it in GitHub Desktop.
Save monbang/b73882fc29976c5ef0874a6a61d2f712 to your computer and use it in GitHub Desktop.
yii validation 2
<?php
namespace app\models;
// proper update unique validation solution:-- https://stackoverflow.com/a/44473290
use Yii;
use yii\base\Model;
class UserUpdateForm extends Model
{
public $id;
public $name;
public $username;
public $password;
public $password_confirm;
public $role;
public $is_active;
protected $model;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'username'], 'required'],
['username', 'filter', 'filter' => 'trim'],
[['is_active'], 'boolean'],
['role', 'in', 'range' => Role::getConstantsByName()],
[['name', 'username'], 'string', 'max' => 200],
[
'username', 'unique',
'targetAttribute' => 'username',
'targetClass' => User::class,
'targetAttribute' => 'username',
'filter' => function($query) {
$query->andWhere(['not', ['id' => $this->id]]);
}
],
[['password', 'password_confirm'], 'string', 'min' => 5, 'max' => 255],
['password', 'match', 'pattern' => '/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', 'message' => 'Password must contain letters and numbers'],
['password', 'compare', 'compareAttribute' => 'password_confirm'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'username' => 'Username',
'password' => 'Password',
'password_confirm' => 'Confirm Password',
'is_active' => 'Status',
'role' => 'Role',
];
}
public function updateAccount()
{
$model = User::findOne(['id' => $this->id]);
if (is_null($model)) {
return null;
}
if (!$this->validate()) {
return null;
}
$model->name = $this->name;
$model->username = $this->username;
$model->is_active = $this->is_active;
$model->role = $this->role;
if ($model->getOldAttribute('pass_hash') !== $model->setPassword($this->password)) {
$model->setPassword($this->password);
}
return $model->save() ? $model : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment