phpyii2yii2-advanced-appyii2-modeldynamicform

How to show form fields while updating a record in Yii2


I am using wbraganca / yii2-dynamicform. I am able to create a new record. There are two models that I am using to create records. The data is saved into both of the tables.

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


<div class="row">
    <div class="panel panel-default">
        <div class="panel-heading"><h4><i class="glyphicon glyphicon-flash"></i> Tariff Slabs</h4></div>
        <div class="panel-body">
            <?php DynamicFormWidget::begin([
                'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
                'widgetBody' => '.container-items', // required: css class selector
                'widgetItem' => '.item', // required: css class
                'limit' => 10, // the maximum times, an element can be cloned (default 999)
                'min' => 1, // 0 or 1 (default 1)
                'insertButton' => '.js-add-filter', // css class
                'deleteButton' => '.js-remove-filter', // css class
                'model' =>  $modelsTariffSlabs[0],
                'formId' => 'dynamic-form',
                 'formFields' => [
                    'slab_name',
                    'slab_start',
                    'slab_end',
                    'rate'
                ],
            ]); ?>

            <div class="container-items"><!-- widgetContainer -->
                <?php foreach ($modelsTariffSlabs as $i => $modelTariffSlabs): ?>
                    <div class="item panel panel-default"><!-- widgetBody -->
                        <div class="panel-heading">
                            <h3 class="panel-title pull-left">Slab</h3>
                            <div class="pull-right">
                                <button type="button" id="addBtn" class="js-add-filter btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                                <button type="button" id="remBtn" class="js-remove-filter btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
                            </div>
                            <div class="clearfix"></div>
                        </div>
                        <div class="panel-body">
                            <?php
                            // necessary for update action.
                            if (! $modelTariffSlabs->isNewRecord) {
                                echo Html::activeHiddenInput($modelTariffSlabs, "[{$i}]id");
                            }
                            ?>
                            <div class="row">
                                <div class="col-sm-3">
                                    <?= $form->field($modelTariffSlabs, "[{$i}]slab_name")->textInput(['maxlength' => 10,"class"=>"form-control js-slab-name"]) ?>
                                </div>
                                <div class="col-sm-3">
                                    <?= $form->field($modelTariffSlabs, "[{$i}]slab_start")->textInput(['maxlength' => 10,"class"=>"form-control js-slab-start"]) ?>
                                </div>
                                <div class="col-sm-3">
                                        <?= $form->field($modelTariffSlabs, "[{$i}]slab_end")->textInput(['maxlength' => 10,"class"=>"form-control js-slab-end"]) ?>
                                    </div>
                                <div class="col-sm-3">
                                    <?= $form->field($modelTariffSlabs, "[{$i}]rate")->textInput(['maxlength' => 10]) ?>
                                </div>
                            </div><!-- .row -->

                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php DynamicFormWidget::end(); ?>
        </div>
     </div>
</div>

Now when I try to update it I am not data of the second model.

enter image description here

Update.php

<div class="mdc-tariff-update">
<?= $this->render('_form', [
    'model' => $model,
    'modelsTariffSlabs' => $modelsTariffSlabs
]) ?>

</div>

Update controller

 public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $modelsTariffSlabs = [new MdcTariffSlabs()];


    if ($model->load(Yii::$app->request->post()) && $model->save()) {

        $oldIDs = ArrayHelper::map($modelsTariffSlabs, 'id', 'id');
        $modelsTariffSlabs = CustomtariffModel::createMultiple(MdcTariffSlabs::classname(), $modelsTariffSlabs);
        CustomtariffModel::loadMultiple($modelsTariffSlabs, Yii::$app->request->post());
        $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsTariffSlabs, 'id', 'id')));

        // validate all models
        $valid = $model->validate();
        $valid = CustomtariffModel::validateMultiple($modelsTariffSlabs) && $valid;

        if ($valid) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($flag = $model->save(false)) {
                    if (! empty($deletedIDs)) {
                        MdcTariffSlabs::deleteAll(['id' => $deletedIDs]);
                    }
                    foreach ($modelsTariffSlabs as $modelTariffSlabs) {
                        $modelTariffSlabs->t_id = $model->id;
                        if (! ($flag = $modelTariffSlabs->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                }
                if ($flag) {
                    $transaction->commit();
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }


        return $this->redirect(['view', 'id' => $model->id]);
    }

    return $this->render('update', [
        'model' => $model,
        'modelsTariffSlabs' => (empty($modelsTariffSlabs)) ? [new MdcTariffSlabs()] : $modelsTariffSlabs
    ]);
}

How can I show the values of all fields in my update form ?

Any help would be highly appreaciated.


Solution

  • I assume that the issue is in this line

    $modelsTariffSlabs = [new MdcTariffSlabs()];

    It always create an empty model. You have to get all the records that are saved. Below code should work

    Assuming that $modelTariffSlabs->t_id = $model->id; // t_id is id of your main table

    protected function findModelSlabs($id)
    {
    
        if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])->all()) !== null) {
    
            return $model;
        }
    
        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
    

    And then change

    $modelsTariffSlabs = [new MdcTariffSlabs()];
    

    TO

    $modelsTariffSlabs = $this->findModelSlabs($model->id);
    

    I hope this will help