3

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?

This is my model:

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' => 50],


    ];
}
public function attributeLabels()
{
    return [
        'name_id' => 'Name ID',
        'position' => 'Position',
        'fname' => 'First Name',
        'mname' => 'Middle Name',
        'lname' => 'Last Name',
    ];
}
}

This is my controller:

   public function actionCreate()
{
    $model = new Name();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['report/create', 'id' => $model->name_id]);
    } else {
        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }
}

And this is my _form:

<div class="name-form">
<?php yii\widgets\Pjax::begin(['id' => 'sign-up']) ?>
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['data-pjax' => true]]); ?>

<?= $form->field($model, 'position')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a Position....']) ?>

<?= $form->field($model, 'fname')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a First Name....']) ?>

<?= $form->field($model, 'mname')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a Middle Name....']) ?>

<?= $form->field($model, 'lname')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a Last Name....'    ]) ?>

    <div class="form-group">
      <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success','style' => 'padding:10px 60px; width:100%;']) ?>
    </div>


<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>

2 Answers2

2

So i assume you want a unique validator, you can try this in your model :

public function rules()
{
    return [
        [['position', 'fname', 'lname'], 'required'],
        [['position', 'fname', 'mname', 'lname'], 'string', 'max' => 50],
        [['fname','lname'], 'unique', 'targetAttribute' => ['fname', 'lname'], 'message' => 'This data already exists']
    ];
}

The above rules will make the combination of fname and lname attributes to be unique, you can modify what attribute or combination of attributes you want to be unique by adding or removing the field name / attributes to the validation rules.

Nue
  • 181
  • 3
  • 9
  • Thank you. But what if the admin want to type the same first name but different last name. For example the data in the database are testposition, testfirstname,testlastname. The admin wants to type the same position and firstname but different lastname. I've tried you're code but it seems it validates fname and lname. –  May 29 '17 at 02:38
  • So you want `position` to be validated too? as i mentioned before you can just add `position` to the attributes validation, something like `[['position','fname','lname'],'unique']` . – Nue May 29 '17 at 04:14
  • Nope, just fname and lname only. –  May 29 '17 at 05:21
1

You can create your custom validation , Take any attribute name and define rule :

 public function rules()
    {   
      return [
          [['position', 'fname', 'lname'], 'required'],
          [['position', 'fname', 'mname', 'lname'], 'string', 'max' => 50],
          [['position', 'fname', 'lname'], 'checkUniq'], //add this line
      ];
    }

-> custom function in model :

public function checkUniq($attribute, $params)
{
    $user = self::find()->where(['fname'=>$this->fname,'lname'=>$this->lname,'position'=>$this->position])->one();
    if (isset($user) && $user!=null)
        $this->addError($attribute, 'User already added.');
}
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53