简体   繁体   English

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

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

I'm using one model file for 2 forms. 我正在为2个表单使用一个模型文件。 One for SIGNUP & Other for A dding members . 一个用于SIGNUP和其他用于一个dding成员

I didn't set any scenario for SIGNUP form. 我没有为SIGNUP表单设置任何场景。 But, scenario for Adding members form is set. 但是,设置了添加成员表单的方案。

Model 模型

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.'],

  ];
}

View 视图

Here, I set scenario like $modelTeamMembers->scenario = 'addteammembersidebar'; 在这里,我设置了类似$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; ?>

All validation error message working except for email field. email字段外,所有验证错误消息均有效 If, I remove 'enableAjaxValidation' => true from field, it works. 如果,我从字段中删除'enableAjaxValidation' => true ,它可以工作。 But, for me 'enableAjaxValidation' => true is required. 但是,对我来说'enableAjaxValidation' => true是必需的。

Image 图片

在此输入图像描述

As in image, it is clearly visible that error message coming " Please enter your email address. " Which should be " Please enter email address. ". 与图像一样,可以清楚地看到错误消息“ 请输入您的电子邮件地址。 ”应该是“ 请输入电子邮件地址。 ”。 Only email field validation error message not coming correct. 只有email字段验证错误消息不正确。 Except all are fine. 除了一切都很好。

How to set validation message for email field for scenarios? 如何为场景的email字段设置验证消息? Any help/hint/suggestions are appreciable. 任何帮助/提示/建议都很明显。

May I know why exactly do you need to use email validation with AjaxValidation in here? 我可以知道您为什么需要在这里使用AjaxValidation进行电子邮件验证? For this type it is enough to write without it since AjaxValidation is more suitable when you want to search and retrieve data from database or other models, not model itself. 对于这种类型,只需要在没有它的情况下编写它就足够了,因为当您想要从数据库或其他模型中搜索和检索数据时, AjaxValidation更适合,而不是模型本身。

However, if you feel you need AjaxValidation , you must set up a few different things since you're current code won't work. 但是,如果您认为需要AjaxValidation ,则必须设置一些不同的东西,因为您当前的代码将无法正常工作。


Setting up AjaxValidation in View : View中设置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);

Why this needed? 为什么需要这个? You have set AjaxValidation to be active, but you haven't set URL that this Ajax will work on. 您已将AjaxValidation设置为活动状态,但您尚未设置此Ajax将处理的URL。 It is set in ActiveForm::begin() in most cases. 在大多数情况下,它在ActiveForm::begin()中设置。


Setting up AjaxValidation in Controller (required): Controller中设置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);
    }
}

Why this needed? 为什么需要这个? Ajax will send a request but request without any actions will do nothing. Ajax将发送请求,但没有任何操作的请求将不会执行任何操作。 This will "create new" object with same rules and attributes and will attempt to validate with new set of data. 这将“创建具有相同规则和属性的新对象”,并将尝试使用新的数据集进行验证。 For rendering method, $obj->scenario must also be set because otherwise it would use default scenario. 对于渲染方法,还必须设置$obj->scenario ,否则它将使用默认场景。


There are no changes to Model . 模型没有变化。 Everything should remain the same as in your example. 一切都应该保持与你的例子相同。

In case you want to make it unique email, you have to make changes to Model as well: 如果您想要使其成为唯一的电子邮件,您还必须对模型进行更改:

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()],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM