如何在 Yii2 中更新记录时显示表单字段

How to show form fields while updating a record in Yii2

我正在使用 wbraganca / yii2-动态形式。我能够创造一个新记录。我使用两种模型来创建记录。数据被保存到两个表中。

<?= $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>

现在我尝试更新时,我不是第二个模型的数据。

Update.php

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

</div>

更新控制器

 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
    ]);
}

如何在我的更新表单中显示所有字段的值?

如有任何帮助,我们将不胜感激。

我认为问题出在这一行

$modelsTariffSlabs = [new MdcTariffSlabs()];

它总是创建一个空模型。您必须获取所有已保存的记录。下面的代码应该可以工作

假设 $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.'));
}

然后改变

$modelsTariffSlabs = [new MdcTariffSlabs()];

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

希望对您有所帮助

或者你可以这样调用关系(当你处于更新模式时):

$modelsTariffSlabs = $model->mdcTariffSlabs

如果 mdcTariffSlabs 是关系名称 - 如果是相关模型,它是 returns 数组。 或者如果你没有关系,你可以在主模型中创建它:

 public function getMdcTariffSlabs()
{
    return $this->hasMany(MdcTariffSlabs::className(), ['t_id' => 'id']);
}