Yii2: Validation in form with two instances of same model

后端 未结 1 508
后悔当初
后悔当初 2021-01-21 19:03

I have a model Booking with the fields shipping_address and billing_address, both of the model Address. I now want to print them to the same form which basically works pretty we

相关标签:
1条回答
  • 2021-01-21 19:31

    Because you use one model class for generating two sets of inputs at one page, yii2 generates identical clientValidation rules for both of them. To separate validation you need to set id attribute for each input that required validation in each of this sets manually. For your zip input field the solution will be next (edited according to latest comments):

    //Billing
    $form->field($billing_address, 'zip', 
    [
        'selectors' => [
            'input' => '#billing-zip',
            'container' => '#billing-container',
        ],
        'options' => ['id' => 'billing-container'],
    ])->textInput(['maxlength' => 11, 
                   'name'=> 'Billing_Address[zip]', 
                   'id'=>'billing-zip']); 
    
    //Shipping
    $form->field($shipping_address, 'zip', 
    [
        'selectors' => [
            'input' => '#shipping-zip',
            'container' => '#shipping-container',
        ],
        'options' => ['id' => 'shipping-container'],
    ])->textInput(['maxlength' => 11, 
                   'name'=> 'Shipping_Address[zip]', 
                   'id'=>'shipping-zip']);
    

    As you can see we added custom id attribute in textInput options, and set corresponding selector for js validation in field options. Read about selectors property

    0 讨论(0)
提交回复
热议问题