跟进:Yii2: Validation in form with two instances of same model
我有一个型号Booking,其字段为shipping_address和billing_address,两个型号的地址。我现在想要将它们打印到基本上工作得很好的相同形式。验证适用于使用数据填充字段,但在提交表单时失败。
在控制器中,帐单地址使用现有地址模型的字段设置,并且发货地址使用新的地址模型设置:
public function actionCreate()
{
$model = new Donation();
if (!empty($_POST['Address'])) {
//TODO: Save models
return $this->redirect(['view', 'id' => $model->id]);
} else {
$user = User::find(Yii::$app->user->identity->id)->one();
$billing_address = $user->getBillingAddress()->one();
return $this->render('create', [
'model' => $model,
'billing_address' => $billing_address,
'shipping_address' => new Address()
]);
}
}
以下代码显示了字段的打印方式。
比林兹字段:
<?= $form->field(
$billing_address,
'address_line_1',
[
'selectors' => [
'input' => '#billing-address_line_1',
'error' => '#billing-address_line_1',
'container' => '.billing-address_line_1'
],
'options' =>
['class' => 'billing-address_line_1']
])->textInput([
'maxlength' => 45,
'name'=> 'Billing_Address[address_line1]',
'id'=>'billing-address_line_1',
]); ?>
优惠字段:
<?= $form->field(
$shipping_address,
'address_line_1',
[
'selectors' => [
'input' => '#shipping-address_line_1',
'error' => '#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 :(得分:0)
我会这样做,我不会直接在渲染函数中创建第二个地址,而是创建第一个模型,然后传递给函数。
} else {
$user = User::find(Yii::$app->user->identity->id)->one();
$billing_address = $user->getBillingAddress()->one();
$shipping_address = new Address();
return $this->render('create', [
'model' => $model,
'billing_address' => $billing_address,
'shipping_address' => $shipping_address,
]);
}