我的模型有2个字段Product.php:
[['ID_PRODUCT'], 'integer'],
[['NAME_PRODUCT'], 'string'],
我的Controller ProductController.php:
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->ID_PRODUCT]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
我希望在ActiveForm中插入多次相同的表:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'ID_PRODUCT')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'NAME_PRODUCT')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ID_PRODUCT')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'NAME_PRODUCT')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
但是当我保存信息时,字段会被覆盖,只插入最后一条记录
答案 0 :(得分:12)
您要做的是收集,验证和保存表格数据。它不起作用的原因是,在表单中,Yii根据字段名称和模型生成名称标签,例如, name="[Product]["ID_PRODUCT"]
。将表单发送到服务器时,第一个字段将被最后一个字段覆盖,因为它们具有相同的名称。在表单中收集表格输入的正确方法是在名称的末尾添加括号,如下所示; name="[1][Product]["ID_PRODUCT"]
。使用这种方法,Yii提供了加载和验证多个模型的方法。
修改您的控制器代码以使用多个模型;
<?php
namespace app\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Product;
class ProductController extends Controller
{
public function actionCreate(){
//Find out how many products have been submitted by the form
$count = count(Yii::$app->request->post('Product', []));
//Send at least one model to the form
$products = [new Product()];
//Create an array of the products submitted
for($i = 1; $i < $count; $i++) {
$products[] = new Product();
}
//Load and validate the multiple models
if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {
foreach ($products as $product) {
//Try to save the models. Validation is not needed as it's already been done.
$product->save(false);
}
return $this->redirect('view');
}
return $this->render('create', ['products' => $products]);
}
}
现在您拥有填充表单所需的所有数据,包括为您product
模型的各个实例生成的任何错误消息。需要像这样更改表单的视图文件,以使用多个模型;
foreach ($products as $index => $product) {
echo $form->field($product, "[$index]ID_PRODUCT")->label($product->ID_PRODUCT);
echo $form->field($product, "[$index]NAME_PRODUCT")->label($product->NAME_PRODUCT);
}
所有这些都包含在Yii2 documentation
中