Dedikisme's Blog

Ngeblog biar dibilang eksis

Yii2 Building a Single Form With Multiple Models

Sebenernya simple sih, prosesnya sama kayka melakukan single form dengan single model tapi perbedaanya terletak pada validasinya saja. Misal saya punya 2 model, User dan Customer, pada controllernya sebagai berikut

ihikController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
...
   public function actionUhuk() {
        $modelCustomer = new Customer();
        $modelUser = new User(['scenario' => 'register']);

        $postData = Yii::$app->request->post();
    if ($modelUser->load($postData) && $modelCustomer->load($postData) && Model::validateMultiple([$modelUser, $modelCustomer])) {
          // terserah, sekarang mau diapain

        return $this->redirect(['auuhh']);
        } else {
        return $this->render('uhuk', ['model' => $modelCustomer, 'modelUser' => $modelUser]);
        }
    }
...
?>

dan pada viewnya

uhuk.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
...
 <?php $form = ActiveForm::begin(); ?>
  <h3>Your Personal Details</h3>

  <?= $form->field($model, 'name')->textInput(['maxlength' => 45]) ?>

  <?= $form->field($model, 'phone')->textInput(['maxlength' => 20]) ?>

  <?= $form->field($modelUser, 'email')->textInput(['maxlength' => 45]) ?>

  <h3>Your Account</h3>
  <?= $form->field($modelUser, 'username')->textInput(['maxlength' => 45]) ?>

  <?= $form->field($modelUser, 'password')->passwordInput() ?>

  <?= $form->field($modelUser, 'password_repeat')->passwordInput() ?>

  <h3>Your Address</h3>

  <?= $form->field($model, 'province')->dropDownList(Province::getOptions(), ['id' => 'cat-id']);
  ?>


  <?=
  $form->field($model, 'city')->widget(DepDrop::classname(), [
      'options' => ['id' => 'subcat-id'],
      'pluginOptions' => [
          'depends' => ['cat-id'],
          'placeholder' => 'Select...',
          'url' => Url::to(['/checkout/subcat']),
      ]
  ]);
  ?>

  <?= $form->field($model, 'address')->textarea(['maxlength' => 45]) ?>

  <?= $form->field($model, 'zipcode')->textInput(['maxlength' => 45]) ?>


<?php ActiveForm::end(); ?>
...
?>

Comments