T
T
teodor7teodor72016-07-22 16:51:05
Yii
teodor7teodor7, 2016-07-22 16:51:05

How to check only the newest entry for uniqueness in Yii2?

Tell me you need to edit the available data, but filter it so that there are unique data or those that are there. Suggest a more elegant version.

public function rules() {
    return [
      // username and password are both required
      [['login', 'email'], 'required', 'message' => 'Необходимо заполнить поле.'],
      ['email', 'email'],
      ['login', 'match', 'pattern' => '/^[a-z]\w*$/i', 'message' => 'Только латинский шрифт, цифры и подчеркивыние.'],
      [['password', 'confirmPassword'], 'validationPassword'],
      [['id', 'login', 'email'], 'validationLoginEmail'],
    ];
  }

  public function validationLoginEmail($attribute, $params) {
    
    (int) $this->id;
 
    $patern_user = User::findByLogin($this->login);
    
    if ($patern_user != null and $this->id != $patern_user->id  ) {
      $this->addError('login', 'Такой логин уже существует.');
       
    }
    
    $patern_user = User::findByEmail($this->email);
 
    if (  $patern_user != null and $this->id != $patern_user->id) {
      $this->addError('email', 'Такой e-mail уже существует.');
    }  
  
    
    }

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2016-07-23
@webinar

Please note that yii has update and create scripts, they can be created and used in rules, for example:
There is also $model->isNewRecord returning true or false

A
Andrew, 2016-07-22
@mhthnz

\app\models\Users and users.id replace with your model with user table

[['email', 'login'], 'unique', 'targetClass' => \app\models\Users::className(), 'filter' => 'users.id != '.$this->id]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question