title: Yii2 Adding rules in models if the record is already exists in database
body: <p>My problem is validating the records if already exists in database. So i created a Officials Form using Gii Generator in yii2. It contains name_id,position,fname,mname,lname. If the admin wants to create a new data, and that data is already exists it will show a pop-up message "This data already exists".
  How can i achieve that? Any ideas?</p>
  
  <p>This is my model:</p>
  
  <pre><code>class Name extends \yii\db\ActiveRecord
  {
  public static function tableName()
  {
      return 'name';
  }
  public function rules()
  {
      return [
          [['position', 'fname', 'lname'], 'required'],
          [['position', 'fname', 'mname', 'lname'], 'string', 'max' =&gt; 50],
  
  
      ];
  }
  public function attributeLabels()
  {
      return [
          'name_id' =&gt; 'Name ID',
          'position' =&gt; 'Position',
          'fname' =&gt; 'First Name',
          'mname' =&gt; 'Middle Name',
          'lname' =&gt; 'Last Name',
      ];
  }
  }
  </code></pre>
  
  <p>This is my controller:</p>
  
  <pre><code>   public function actionCreate()
  {
      $model = new Name();
  
      if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;save()) {
          return $this-&gt;redirect(['report/create', 'id' =&gt; $model-&gt;name_id]);
      } else {
          return $this-&gt;renderAjax('create', [
              'model' =&gt; $model,
          ]);
      }
  }
  </code></pre>
  
  <p>And this is my _form:</p>
  
  <pre><code>&lt;div class="name-form"&gt;
  &lt;?php yii\widgets\Pjax::begin(['id' =&gt; 'sign-up']) ?&gt;
  &lt;?php $form = ActiveForm::begin(['id' =&gt; 'form-signup', 'options' =&gt; ['data-pjax' =&gt; true]]); ?&gt;
  
  &lt;?= $form-&gt;field($model, 'position')-&gt;textInput(['maxlength' =&gt; true,'style'=&gt;'width:500px','placeholder' =&gt; 'Enter a Position....']) ?&gt;
  
  &lt;?= $form-&gt;field($model, 'fname')-&gt;textInput(['maxlength' =&gt; true,'style'=&gt;'width:500px','placeholder' =&gt; 'Enter a First Name....']) ?&gt;
  
  &lt;?= $form-&gt;field($model, 'mname')-&gt;textInput(['maxlength' =&gt; true,'style'=&gt;'width:500px','placeholder' =&gt; 'Enter a Middle Name....']) ?&gt;
  
  &lt;?= $form-&gt;field($model, 'lname')-&gt;textInput(['maxlength' =&gt; true,'style'=&gt;'width:500px','placeholder' =&gt; 'Enter a Last Name....'    ]) ?&gt;
  
      &lt;div class="form-group"&gt;
        &lt;?= Html::submitButton($model-&gt;isNewRecord ? 'Create' : 'Update', ['class' =&gt; $model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-success','style' =&gt; 'padding:10px 60px; width:100%;']) ?&gt;
      &lt;/div&gt;
  
  
  &lt;?php ActiveForm::end(); ?&gt;
  &lt;?php yii\widgets\Pjax::end() ?&gt;
  </code></pre>
  
  <p></p>