4

I'm using one model file for 2 forms. One for SIGNUP & Other for Adding members.

I didn't set any scenario for SIGNUP form. 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';.

<?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. If, I remove 'enableAjaxValidation' => true from field, it works. But, for me 'enableAjaxValidation' => true is required.

Image

enter image description here

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. Except all are fine.

How to set validation message for email field for scenarios? Any help/hint/suggestions are appreciable.

Nana Partykar
  • 10,556
  • 10
  • 48
  • 77

1 Answers1

12

May I know why exactly do you need to use email validation with AjaxValidation in here? 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.

However, if you feel you need AjaxValidation, you must set up a few different things since you're current code won't work.


Setting up AjaxValidation in View:

// 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. It is set in ActiveForm::begin() in most cases.


Setting up AjaxValidation in Controller (required):

// 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. 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.


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()],
}
Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72
Gynteniuxas
  • 7,035
  • 18
  • 38
  • 54
  • 1
    Hi Thanks for answering. Actually for email field unique validation rule I am checking for. Existing email not allowing. That's why I'm keeping Ajax validation. Any new way to do or this code will work for email unique validation. – Nana Partykar Jul 31 '16 at 00:14
  • @NanaPartykar I have edited the code a little bit. Changed only that part of **Model** since it's the only thing you need to change. This will make your `email` attribute unique. – Gynteniuxas Jul 31 '16 at 06:55
  • Actually, I didn't went office. Tomorrow first task will be to check this answer. I hope, by seeing the quality answer of yours will solve my problem. *Thanks* – Nana Partykar Jul 31 '16 at 18:09
  • I see. Well, of course, before posting this, I tested it myself and it works for me, so if something is not quite right, you're still missing something (I didn't include `use`s). I hope my answer will help you a lot (maybe mark as accepted since I'm the only one who wrote here D:). – Gynteniuxas Jul 31 '16 at 18:12
  • Don't worry brother. I am genuine user of stack overflow. I will do. That's for sure. Ur efforts will get counted. – Nana Partykar Jul 31 '16 at 18:17
  • Yea, I see your reputation and how long you have been have. I'm used to reply to new users. – Gynteniuxas Jul 31 '16 at 18:19
  • Hi. Now it's taking *Please enter your email*. But, not checking email validation. In this line, `['email', 'unique', 'message' => 'Email must be unique', 'targetClass' => User2::className()],` User2 is another class name or same class. – Nana Partykar Aug 01 '16 at 07:33
  • Now, only `unique` email validation not working. and everything working. Please suggest something for unique email validation @Edvin – Nana Partykar Aug 01 '16 at 07:35
  • Sorry. Since, That Task Was Very Important. And, I was Not able To do in hurry. So, I Created one different model for addmembers.php. But, your solution is very efficient. May be I'm missed somewhere. I will try your code in my free time. *Thanks For Your Effort.* – Nana Partykar Aug 01 '16 at 14:15
  • @NanaPartykar No no, that's totally fine. I asked exactly for the same reason why you couldn't answer - it was very important (in case you couldn't get it, I may help you solving this faster). – Gynteniuxas Aug 01 '16 at 15:34