Validating unique email using DynamicFormWidget - Yii2

邮差的信 提交于 2019-12-24 00:34:20

问题


I am using DynamicFormWidget for multiple input fields like: first_name, last_name, email & mobile_no. And, I don't want user to type the existing email. Means, email should be unique. It is working when I am not using DynamicFormWidget. Actually, I don't know how to validate unique email in multiple input forms using Yii2.

addmembers.php (View)

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
?>

<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.container-items',
'widgetItem' => '.house-item',
'limit' => 10,
'min' => 1,
'insertButton' => '.add-house',
'deleteButton' => '.remove-house',
'model' => $modelsTeamMembers[0],
'formId' => 'dynamic-form',
'formFields' => ['description',],
]); ?>

<table class="table table-bordered table-striped">
<thead>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email</th>
    <th>Mobile Number</th>
  </tr>
</thead>
<tbody class="container-items">
<?php foreach ($modelsTeamMembers as $indexMember => $modelTeamMembers): ?>
    <tr class="house-item">
      <td class="vcenter">
        <?php
        if (! $modelTeamMembers->isNewRecord) {
          echo Html::activeHiddenInput($modelTeamMembers, "[{$indexMember}]id");
        }
        ?>
        <?= $form->field($modelTeamMembers, "[{$indexMember}]first_name")->label(false) ?>
      </td>
      <td>
        <?= $form->field($modelTeamMembers, "[{$indexMember}]last_name")->label(false) ?>
      </td>
      <td>
        <?= $form->field($modelTeamMembers, "[{$indexMember}]email",['enableAjaxValidation' => true])->label(false) ?>
      </td>
      <td>
        <?= $form->field($modelTeamMembers, "[{$indexMember}]mobile_no",['inputOptions' => ['class' => 'form-control', 'maxlength'=>"10"]])->label(false) ?>
      </td>
    </tr>
 <?php endforeach; ?>

UsersController.php (Controller)

<?php
namespace app\modules\users\controllers;

use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;

class UsersController extends CommonController 
{
    public function actionAddmembers() {

        if(Yii::$app->request->isAjax && $modelUser->load(Yii::$app->request->post())) {
          Yii::$app->response->format = Response::FORMAT_JSON;
          return ActiveForm::validate($modelUser);
        } 
        elseif ($modelUser->load(Yii::$app->request->post())) {
            .
            .
        }

    }
}

Users.php (Model)

namespace app\modules\users\models;

use Yii;
use app\models\MyActiveRecord;
use yii\web\IdentityInterface;

class Users extends MyActiveRecord implements IdentityInterface
{

  public $rememberMe;
  public $confirm_password;
  public $verify_code;
  public $_user = false;

  public static function tableName() {
    return 'users';
  }

  public function rules() {
    return [

      .
            .
      //Email ID
      'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
      'emailRequired' => ['email', 'required','message'=>'* required field'],
      'emailPattern' => ['email', 'email'],
      'emailUnique' => ['email', 'unique','message'=>'Email already exists!'],
        ];
  }
  .
  .
  .
}

I Also Tried :

UsersController.php (Controller)

public function actionAddmembers() {

  $modelUser = new Users();
  $modelCompanyUser = new CompanyUsers();
  $modelCompany = new Company();
  $modelsTeamMembers = [new Users]; 

  $modelUserDetails = MyActiveRecord::createMultiple(Users::classname());
  MyActiveRecord::loadMultiple($modelUserDetails, Yii::$app->request->post());

    if (Yii::$app->request->isAjax) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      return ArrayHelper::merge(ActiveForm::validateMultiple($modelUserDetails));
    } elseif($modelUser->load(Yii::$app->request->post())){
        .
        .
    }
}

I am following yii2-dynamicform

Any help/hint/suggestion would be appreciable.


回答1:


Yes. I got it. If anyone having the same problem, use this code. Please Change $modelUserDetails variable wherever it is needed.

I'm using DynamicFormWidget.

And, I wanted to check email exist on email field. So,

addmembers.php (view)

Use use yii\widgets\ActiveForm; in top of the page. And, put 'enableAjaxValidation' => true in the field where you want user to restrict to enter duplicate value.

use yii\widgets\ActiveForm; // This is mandatory.
.
.
<?= $form->field($modelTeamMembers, "[{$indexMember}]email",['enableAjaxValidation' => true]);?>
.
.

UsersController.php (controller)

<?
// These two lines are mandatory. 
use yii\web\Response;
use yii\widgets\ActiveForm;

..

public function actionAddMembers() {

   .
   .
   $modelUserDetails = MyActiveRecord::createMultiple(Users::classname());
   MyActiveRecord::loadMultiple($modelUserDetails, Yii::$app->request->post());

   // ajax validation
   if (Yii::$app->request->isAjax) {

     Yii::$app->response->format = Response::FORMAT_JSON;
     return ActiveForm::validateMultiple($modelUserDetails);

   } elseif ($modelUser->load(Yii::$app->request->post())) {
        // Business Logic
   }
}

Users.php (model)

class Users extends MyActiveRecord implements IdentityInterface
{
    .
    .
    .

    public function rules() {
    return [
            .
            .
            ['email', 'unique','message'=>'Email already exists!'],
        ];
  }

}

It will surely help.



来源:https://stackoverflow.com/questions/36605856/validating-unique-email-using-dynamicformwidget-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!