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() ?>