[英]Multiple model in one model Yii2
I want to create multiple model in one form. 我想以一种形式创建多个模型。
This is my controller: 这是我的控制器:
public function actionWorkRoom() {
$model = [new Moshtari()];
$model[0] = new Moshtari();
$model[1] = new Moshtari();
if (Model::loadMultiple($model, Yii::$app->request->post()) && Model::validateMultiple($model)) {
foreach ($model as $m) {
$m->save(false);
}
}
return $this->render('_form_work_room', ['model' => $model]);
}
Model: 模型:
class Moshtari extends \yii\db\ActiveRecord {
public function rules() {
return [
[['CodeKargah'], 'number'],
]
}
public function attributeLabels() {
return [
'CodeKargah' => Yii::t('app', 'Code Kargah'),
];
}
}
And this is my form in view: 这是我的表格:
foreach ($model as $index => $m) {
echo $form->field($m, "[$index]CodeKargah");
}
but this is throwing this error: 但这会引发此错误:
Call to a member function getActiveValidators() on a non-object 在非对象上调用成员函数getActiveValidators()
I solved, this is new code: 我解决了,这是新代码:
Controller: 控制器:
public function actionWorkRoom($member = 1) {
$model[] = new Moshtari(['scenario' => 'work_room_kargah']);
for ($i = 0; $i < $member; $i++) {
$model[] = new Moshtari(['scenario' => 'work_room']);
}
if (Model::loadMultiple($model, Yii::$app->request->post()) && Model::validateMultiple($model)) {
foreach ($model as $m) {
$m->time = Yii::$app->jdate->date('Y/m/d') . ' ' . date('H:i:s');
$m->CodeKargah = $model[0]->CodeKargah;
$m->save(false);
}
return $this->redirect('index');
}
return $this->render('_form_work_room', ['models' => $model]);
}
View 视图
foreach ($models as $index => $model) {
//print_r($model->getErrors());
if ($index >= 1) {
<?=
$form->field($model, "[$index]name", [
'template' => '<div class="row nomargin"><div class="col-md-4 form_label">{label}</div><div class="col-md-7">{input}{error}</div></div>']
)->textInput(['maxlength' => true])
?>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.