我有一个型号Booking,其字段为shipping_address和billing_address,两个型号的地址。 我现在想要将它们打印到基本上运行良好的相同形式,问题是两个模型的字段具有相同的ID。例如,字段" zip"在shipping_address中有id" zip"和" zip"在billing_address中也有" zip"作为它的身份。
如果我现在填写表格,它会同时验证两个字段,而其中只有一个字段确实为真。
我已经将字段名称更改为Shippping_Address [&#39; zip&#39;]和Billing_Address [&#39; zip&#39;]因此控制器能够识别这两种模型。< / p>
以下是字段的打印方式:
<?= $form->field($billing_address, 'address_line_1')->textInput(['maxlength' => 45, 'name'=> 'Billing_Address[address_line1]']); ?>
<?= $form->field($billing_address, 'address_line_2')->textInput(['maxlength' => 45, 'name'=> 'Billing_Address[address_line2]']) ?>
<?= $form->field($billing_address, 'zip')->textInput(['maxlength' => 11, 'name'=> 'Billing_Address[zip]']) ?>
<?= $form->field($billing_address, 'city')->textInput(['maxlength' => 45, 'name'=> 'Billing_Address[city]']) ?>
<?= $form->field($billing_address, 'country')->textInput(['maxlength' => 45, 'name'=> 'Billing_Address[country]']) ?>
<?= $form->field($shipping_address, 'address_line_1')->textInput(['maxlength' => 45, 'name'=> 'Shipping_Address[address_line1]']); ?>
<?= $form->field($shipping_address, 'address_line_2')->textInput(['maxlength' => 45, 'name'=> 'Shipping_Address[address_line2]']) ?>
<?= $form->field($shipping_address, 'zip')->textInput(['maxlength' => 11, 'name'=> 'Shipping_Address[zip]']) ?>
<?= $form->field($shipping_address, 'city')->textInput(['maxlength' => 45, 'name'=> 'Shipping_Address[city]']) ?>
<?= $form->field($shipping_address, 'country')->textInput(['maxlength' => 45, 'name'=> 'Shipping_Address[country]']) ?>
编辑:在实现了tony的答案之后:
<?= $form->field(
$shipping_address,
'address_line_1',
[
'selectors' => [
'input' => '#shipping-address_line_1',
'container' => '.shipping-address_line_1'
],
'options' =>
['class' => 'shipping-address_line_1']
])->textInput([
'maxlength' => 45,
'name'=> 'Shipping_Address[address_line1]',
'id'=>'shipping-address_line_1',
]); ?>
我还更改了容器类,因为它与其他字段的容器类相同。现在第二个字段(代码如上所示)运行正常。问题是,第一个字段(代码未更改)不再验证。
怎么能解决这个问题?
答案 0 :(得分:4)
因为您使用一个模型类在一个页面上生成两组输入,所以yii2为它们生成相同的 clientValidation 规则。要单独验证,您需要为每个需要手动验证每个集合的输入设置 id 属性。对于您的zip输入字段,解决方案将是(根据最新评论编辑):
//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']);
如您所见,我们在 textInput 选项中添加了自定义 id 属性,并在 field 选项中为js验证设置了相应的选择器。 Read about selectors property