prawee / yii2-dependform-widgets
如何在单个表单中使用关系模型
dev-master
2020-06-25 03:38 UTC
Requires
- yiisoft/yii2: ~2.0.14
- yiisoft/yii2-bootstrap4: ~2.0.8
This package is auto-updated.
Last update: 2024-09-25 13:39:09 UTC
README
用例示例
有2个表格需要同时保存,并且取决于你选择的团队成员数量
team - id - name - member person - id - team_id - name - position - experience
用法
视图
use prawee\widgets\DependWidget; ... $form = ActiveForm::begin(['id' => 'depend-form']); echo $form->field($team, 'name', ['options' => ['class' => 'col-md-8']])->textInput(['autofocus' => true]); echo $form->field($team, 'member', ['options' =>['class' => 'col-md-4']])->dropDownList([ 1 => 1, 2 => 2, 3 => 3, 5 => 5, 8 => 8, 10 => 10, ],['prompt' => 'select']); echo DependWidget::widget([ 'form' => $form, 'model' => $person, 'attributes' => [ 'name', 'position', 'experience' => [ 'type' => 'select', 'list' =>[1 => '1-2', 2 => '3-5', 3 => '5 >', 4 => '10 >'] ], ], 'attributeOptions' => ['class' => 'col-md-4'], 'depends' => [Html::getInputId($team, 'member')] ]); ?> <div class="form-group col-md-12"> <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?> </div> <?php ActiveForm::end(); ?>
控制器
... public function actionCreate() { $team = new Team(); $person = new Person(); $post = \Yii::$app->request->post(); if (Model::loadMultiple([$person], $post) && Model::validateMultiple([$person])) { $team->load($post['Team']); foreach($post['Person'] as $person): $person->load($person); $person->team_id = $team->id; $person->save(); endforeach; $team->save(); return $this->redirect(['index']); } return $this->render('create', [ 'team' => $team, 'person' => $person ]); } ...