如何在场景中为具有 ajax 验证的字段设置验证消息? - Yii2

How to set validation message for field having ajax validation in scenarios? - Yii2

我正在为 2 个表单使用一个模型文件。一份用于 SIGNUP & 另一份用于 A 添加成员.

我没有为 SIGNUP 表单设置任何方案。但是,添加成员 表单的方案已设置。

型号

public function rules() {
  return [

    //Add Members
    ['first_name', 'required','message'=>'Please enter first name.','on'=>'addteammembersidebar'],
    ['email', 'required','message'=>'Please enter email address.','on'=>'addteammembersidebar'],
    ['mobile','required','message'=>'Please enter mobile number.','on'=>'addteammembersidebar'],

    //Common
    ['first_name', 'required','message'=>'Please enter your first name.'],
    ['email', 'required','message'=>'Please enter your email address.'],
    ['mobile','required','message'=>'Please enter your mobile number.'],

  ];
}

查看

在这里,我设置了$modelTeamMembers->scenario = 'addteammembersidebar';这样的场景。

<?php foreach ($modelsTeamMembers as $indexMember => $modelTeamMembers): 
  $modelTeamMembers->scenario = 'addteammembersidebar';
  ?>
  <tr class="house-item">
    <td class="vcenter">
      <?php
      // necessary for update action.
      if (! $modelTeamMembers->isNewRecord) {
        echo Html::activeHiddenInput($modelTeamMembers, "[{$indexMember}]id");
      }
      ?>

      <?php 
      $modelTeamMembers->first_name = $first_name;
      echo $form->field($modelTeamMembers, "[{$indexMember}]first_name")->label(false); 
      ?>
    </td>
    <td>
      <?php
      $modelTeamMembers->last_name = $last_name;
      echo $form->field($modelTeamMembers, "[{$indexMember}]last_name")->label(false); 
      ?>
    </td>
    <td>
      <?php
      $modelTeamMembers->email = $email;
      echo $form->field($modelTeamMembers, "[{$indexMember}]email",['enableAjaxValidation' => true])->label(false); 
      ?>
    </td>
    <td>
      <?php
      $modelTeamMembers->mobile = $mobile_number;
      echo $form->field($modelTeamMembers, "[{$indexMember}]mobile",
          ['inputOptions' => ['class' => 'form-control', 'maxlength'=>"10"]])->label(false);
      ?>
    </td>
  </tr>

<?php endforeach; ?>

email 字段外,所有验证错误消息均有效。如果我从字段中删除 'enableAjaxValidation' => true,它就可以工作。但是,对我来说 'enableAjaxValidation' => true 是必需的。

图片

如图所示,可以清楚地看到错误消息“请输入您的电子邮件地址。”应该是“请输入电子邮件地址。”。只有 email 字段验证错误消息不正确。除了一切都很好

如何为场景的 email 字段设置验证消息?任何 help/hint/suggestions 都是可观的。

我可以知道为什么您需要在这里使用 AjaxValidation 的电子邮件验证吗?对于这种类型,没有它就足够了,因为当您想从数据库或其他模型而不是模型本身搜索和检索数据时,AjaxValidation 更适合。

但是,如果您觉得需要 AjaxValidation,则必须进行一些不同的设置,因为您当前的代码无法正常工作。


视图中设置AjaxValidation

// Set to: index.php?r=profile/email-validation
$form = ActiveForm::begin(['validationUrl' => ['profile/email-validation']]);

// This is set correctly (no changes are needed comparing to your attempt)
echo $form->field($modelTeamMembers, "[{$indexMember}]email", ['enableAjaxValidation' => true])->label(false);

为什么需要这个?您已将 AjaxValidation 设置为活动状态,但尚未设置此 Ajax 将起作用的 URL。大多数情况下设置在ActiveForm::begin()


控制器中设置AjaxValidation(必需):

// Method that renders your view file
public function actionSomethingThatRendersView()
{
    // Code here
    $user->scenario = 'addteammembersidebar';                 // Custom scenario name
    return $this->render(/* the remaining code goes here */);
}

// This is the method that Ajax will send request to ($_POST[])
public function actionEmailValidation()
{
    $post = Yii::$app->request->post();
    if (!empty($post))
    {
        Yii::$app->response->format = Response::FORMAT_JSON;  // Must be in JSON format
        $profile = new User();                                // Edit your class name in here
        // Custom scenario (must be the same as above otherwise you might get unexpected response)
        $profile->scenario = 'addteammembersidebar';
        $profile->load($post);

        return ActiveForm::validate($profile);
    }
}

为什么需要这个? Ajax 将发送一个请求,但没有任何操作的请求将不执行任何操作。这将 "create new" 具有相同规则和属性的对象,并将尝试使用新数据集进行验证。对于渲染方法,还必须设置$obj->scenario,否则将使用默认场景。


型号没有变化。一切都应该与您的示例中的一样。

如果你想让它成为唯一的电子邮件,你还必须对 Model 进行更改:

public function rules()
{
    // ...
    ['email', 'unique', 'message' => 'Email must be unique'],
    // If your attribute is not in the same table as defined in class, then:
    ['email', 'unique', 'message' => 'Email must be unique', 'targetClass' => User2::className()],
}