2

In my code I have a field (e.g. field name is exampleField[]) in which I implemented add more functionality through JS. Now, I want to implement Yii2 required Validator on each field. I already use each validator but it's not working. My yii2 version is 2.0.6.

Here is my javascript code:

var max_fields = 4; //maximum input boxes allowed
        var wrapper = $(".addAmount"); //Fields wrapper
        var add_button = $(".add_field_button"); //Add button ID
        var html = '';

        var x = <?php echo $count ?>; //initlal text box count

        $(add_button).click(function (e) { //on add input button click

            html = '<div id="multipleRow' + x + '"><div class="fullwidth">';
            html += '<div class="span4"><div class="control-group">';
            html += '<label for="plandetail-planduration" class="control-label">Duration <span class="required">*</span></label>';
            html += '<div class="controls"><div class="form-group field-plandetail-planduration required">';
            html += '<input type="text" name="PlanDetail[planDuration][]" class="form-control" id="plandetail-planduration">';
            html += '<div class="error"></div></div></div></div>';
            html += '</div>';
            html += '<div class="span4"><div class="control-group">';
            html += '<label for="plandetail-plandurationtype" class="control-label">Duration Period<span class="required">*</span></label>';
            html += '<div class="controls"><div class="form-group field-plandetail-plandurationtype">';
            html += '<select name="PlanDetail[planDurationType][]" class="form-control" id="plandetail-plandurationtype">';
            html += '<option value=""></option>';
            html += '<option value="month">Month</option>';
            html += '<option value="year">Year</option>';
            html += '</select>';
            html += '<div class="help-block"></div>';
            html += '</div></div></div></div></div>';
            html += '<div class="fullwidth">';
            html += '<div class="span4"><div class="control-group">';
            html += '<label for="plandetail-planamount" class="control-label">Amount <span class="required">*</span></label>';
            html += '<div class="controls"><div class="form-group field-plandetail-planamount required">';
            html += '<input type="text" name="PlanDetail[planAmount][]" class="form-control" id="plandetail-planamount">';
            html += '<div class="error"></div>';
            html += '</div></div>';
            html += '</div></div>';
            html += '<div class="span4"><div class="control-group">';
            html += '<label for="plandetail-plandiscountamount" class="control-label">Discount Amount <span class="required">*</span></label>';
            html += '<div class="controls"><div class="form-group field-plandetail-plandiscountamount required">';
            html += '<input type="text" name="PlanDetail[planDiscountAmount][]" class="form-control" id="plandetail-plandiscountamount">';
            html += '<div class="error"></div>';
            html += '</div></div>';
            html += '</div></div>';
            html += '<div class="span4"><div class="control-group">';
            html += '<label for="plandetail-plancurrency" class="control-label">Currency <span class="required">*</span></label>';
            html += '<div class="controls"><div class="form-group field-plandetail-plancurrency required">';
            html += '<select name="PlanDetail[planCurrency][]" class="form-control" id="plandetail-plancurrency">';
            html += '<option value=""></option><option value="USD">USD</option><option value="EUR">EUR</option>';
            html += '</select>';
            html += '<div class="help-block"></div>';
            html += '</div></div>';
            html += '</div></div>';
            html += '</div>';
            html += '<div class="col-lg-4"><a href="javascript:void(0)" class="remove_field" id="' + x + '">Remove</a></div>';
            html += '</div></div>';
            e.preventDefault();
            if (x < max_fields) { //max input box allowed
                x++; //text box increment
                $(wrapper).append(html); //add input box
            }else{alert('You Can not add more than 4 Amount')}

        });
        $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
            e.preventDefault();
//            alert(this.id);
            $("#multipleRow" + this.id).remove();
            x--;
        });
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
SAR
  • 57
  • 8
  • EachValidator should work. I guess there is probably something wrong with your javascript that is generating these fields. Update your question with the relevant code so people can help more. So far, we can only guess what's happening. – Clyff Jul 29 '16 at 19:05
  • please put your codes – Jalali Jul 29 '16 at 19:41
  • @Clyff i updated my code – SAR Aug 01 '16 at 08:37

1 Answers1

0

You are only adding the html of your inputs and missing the js that makes the validation. You must add all the dynamic fields with yiiActiveForm. Here is a example with the contact form that comes with basic template:

First, remove the field email from the form, so we can add it latter with js:

<?php // $form->field($model, 'email') ?>

Make sure you are using ajax validation in your form:

<?php $form = ActiveForm::begin(['id' => 'contact-form', 'enableAjaxValidation' => true]); ?>

Now, in the end of the view add this code:

<?php
$js = <<<JS
$( document ).ready(function() {
    var input = '<div class="form-group field-contactform-email required">' +
        '<label class="control-label" for="contactform-email">Email</label>' +
        '<input type="text" id="contactform-email" class="form-control" name="ContactForm[email]">' +
        '<p class="help-block help-block-error"></p>' +
    '</div>';

    $('#contact-form').append(input); // add the html in the form

    $('#contact-form').yiiActiveForm('add', { // add the js rules to the form
        'id': 'contactform-email',
        'name': 'email',
        'container': '.field-contactform-email',
        'input': '#contactform-email',
        'enableAjaxValidation':true
    });
});
JS;

$this->registerJs($js); // insert javascript

Finally, we just need to make the ajax validation in the controller, something like:

use yii\web\Response;
use yii\widgets\ActiveForm;

class SiteController extends Controller
{
    ...

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post())) { // load the post
            if (Yii::$app->request->isAjax) { // verify is ajax
                Yii::$app->response->format = Response::FORMAT_JSON; // change the response to json format
                return ActiveForm::validate($model); // return the validation as json
            } elseif ($model->contact(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('contactFormSubmitted');

                return $this->refresh();
            }
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }
}
Clyff
  • 4,046
  • 2
  • 17
  • 32