Yii2:嵌套动态表单wbraganca添加了更多字段

时间:2018-09-16 13:35:39

标签: php yii2 yii2-basic-app dynamic-forms

我正在为yii2使用wbragnaca动态表格,添加和删除按钮在创建时可以正常使用,完美无缺。但是,当我在Instrument上更新嵌套项时,即为该项目的嵌套形式是,当我单击添加按钮时,它会添加3个字段,而不仅仅是一个字段。

这是我单击“项目-报表”按钮之前的表格:

Instrument Form before

在这里,我单击了项目上的添加按钮之后:

Instrument Form after

这是我的数据库设计:

DATABASE

这是我的代码,

_form.php

    <?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;

/* @var $this yii\web\View */
/* @var $model app\models\Instrument */
/* @var $form yii\widgets\ActiveForm */
?>


    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>

<div>
       <?= $form->field($modelInstrument, 'name')->textInput(['maxlength' => true,'style'=>'width: 50%', 'placeholder'=>'Name'])->label(false) ?>

       <?= $form->field($modelInstrument, 'description')->textArea(['rows' => '6', 'placeholder'=>'Description'])->label(false) ?>

</div>

<div class="padding-v-md">
   <div class="line line-dashed"></div>
</div>
<br/>
<?php DynamicFormWidget::begin([
   'widgetContainer' => 'dynamicform_wrapper',
   'widgetBody' => '.container-items',
   'widgetItem' => '.section-item',
   'min' => 1,
   'insertButton' => '.add-section',
   'deleteButton' => '.remove-section',
   'model' => $modelsSection[0],
   'formId' => 'dynamic-form',
   'formFields' => [
       'name',
       'description',
   ],
]); ?>
<table class="table table-bordered table-striped">
   <thead>
       <tr>
           <th >Sections</th>
           <th style="width: 650px; height: 30px;">Items</th>
           <th class="text-center" style="width: 30px; height: 30px;">
               <button type="button" class="add-section btn btn-success btn-xs"><span class="glyphicon glyphicon-plus" style="font-size: 10px"></span></button>
           </th>
       </tr>
   </thead>
   <tbody class="container-items">
   <?php foreach ($modelsSection as $indexSection => $modelSection): ?>
       <tr class="section-item">
           <td class="vcenter">
               <?php
                   // necessary for update action.
                   if (! $modelSection->isNewRecord) {
                       echo Html::activeHiddenInput($modelSection, "[{$indexSection}]id");
                   }
               ?>
               <?= $form->field($modelSection, "[{$indexSection}]name")->label(false)->textInput(['placeholder'=>"Name"]) ?>
               <?= $form->field($modelSection, "[{$indexSection}]description")->label(false)->textArea(['rows' => '6', 'placeholder'=>'Description']) ?>
           </td>
           <td>
               <?= $this->render('_form-item', [
                   'form' => $form,
                   'indexSection' => $indexSection,
                   'modelsItem' => $modelsItem[$indexSection],
               ]) ?>
           </td>
           <td class="text-center vcenter" style="width: 40px; verti">
               <button type="button" class="remove-section btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus" style="font-size: 10px"></span></button>
           </td>
       </tr>
    <?php endforeach; ?>
   </tbody>
</table>
<?php DynamicFormWidget::end(); ?>

<div class="form-group">
   <?= Html::submitButton($modelInstrument->isNewRecord ? 'Create' : 'Update', ['class' => 'btn btn-primary']) ?>
</div>

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

_form-item.php

<?php

use yii\helpers\Html;
use wbraganca\dynamicform\DynamicFormWidget;

?>

<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_inner',
    'widgetBody' => '.container-rooms',
    'widgetItem' => '.room-item',
    'min' => 1,
    'insertButton' => '.add-item',
    'deleteButton' => '.remove-item',
    'model' => $modelsItem[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'statement'
    ],
]); ?>
<table class="table table-bordered">
    <thead>
        <tr>
            <th >Statements</th>
            <th class="text-center">
                <button type="button" class="add-item btn btn-success btn-xs"><span class="glyphicon glyphicon-plus" style="font-size: 10px"></span></button>
            </th>
        </tr>
    </thead>
    <tbody class="container-rooms">
    <?php foreach ($modelsItem as $indexItem => $modelItem): ?>
        <tr class="room-item">
            <td class="vcenter">
                <?php
                    // necessary for update action.
                    if (! $modelItem->isNewRecord) {
                        echo Html::activeHiddenInput($modelItem, "[{$indexSection}][{$indexItem}]id");
                    }
                ?>
                <?= $form->field($modelItem, "[{$indexSection}][{$indexItem}]statement")->label(false)->textInput(['maxlength' => true]) ?>
            </td>
            <td class="text-center vcenter" style="width: 40px;">
                <button type="button" class="remove-item btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus" style="font-size: 10px"></span></button>
            </td>
        </tr>
     <?php endforeach; ?>
    </tbody>
</table>
<?php DynamicFormWidget::end(); ?>

InstrumentController.php actionUpdate

public function actionUpdate($id)
    {
        $modelInstrument = $this->findModel($id);
        $modelsSection = $modelInstrument->sections;
        $modelsItem = [];
        $oldItems = [];
        if (!empty($modelsSection)) {
            foreach ($modelsSection as $indexSection => $modelSection) {
                $items = $modelSection->items;
                $modelsItem[$indexSection] = $items;
                $oldItems = ArrayHelper::merge(ArrayHelper::index($items, 'id'), $oldItems);
            }
        }

        if ($modelInstrument->load(Yii::$app->request->post())) {

            // reset
            $modelsItem = [];

            $oldSectionIDs = ArrayHelper::map($modelsSection, 'id', 'id');
            $modelsSection = Model::createMultiple(Section::classname(), $modelsSection);
            Model::loadMultiple($modelsSection, Yii::$app->request->post());
            $deletedSectionIDs = array_diff($oldSectionIDs, array_filter(ArrayHelper::map($modelsSection, 'id', 'id')));

            // validate Instrument and Section models
            $valid = $modelInstrument->validate();
            $valid = Model::validateMultiple($modelsSection) && $valid;

            $itemsIDs = [];
            if (isset($_POST['Item'][0][0])) {
                foreach ($_POST['Item'] as $indexSection => $items) {
                    $itemsIDs = ArrayHelper::merge($itemsIDs, array_filter(ArrayHelper::getColumn($items, 'id')));
                    foreach ($items as $indexItem => $item) {
                        $data['Item'] = $item;
                        $modelItem = (isset($item['id']) && isset($oldItems[$item['id']])) ? $oldItems[$item['id']] : new Item;
                        $modelItem->load($data);
                        $modelsItem[$indexSection][$indexItem] = $modelItem;
                        $valid = $modelItem->validate();
                    }
                }
            }

            $oldItemsIDs = ArrayHelper::getColumn($oldItems, 'id');
            $deletedItemsIDs = array_diff($oldItemsIDs, $itemsIDs);

            if ($valid) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $modelInstrument->save(false)) {

                        if (! empty($deletedItemsIDs)) {
                            Item::deleteAll(['id' => $deletedItemsIDs]);
                        }

                        if (! empty($deletedSectionIDs)) {
                            Section::deleteAll(['id' => $deletedSectionIDs]);
                        }

                        foreach ($modelsSection as $indexSection => $modelSection) {

                            if ($flag === false) {
                                break;
                            }

                            $modelSection->instrument_id = $modelInstrument->id;

                            if (!($flag = $modelSection->save(false))) {
                                break;
                            }

                            if (isset($modelsItem[$indexSection]) && is_array($modelsItem[$indexSection])) {
                                foreach ($modelsItem[$indexSection] as $indexItem => $modelItem) {
                                    $modelItem->section_id = $modelSection->id;
                                    if (!($flag = $modelItem->save(false))) {
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $modelInstrument->id]);
                    } else {
                        $transaction->rollBack();
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }

        return $this->render('update', [
            'modelInstrument' => $modelInstrument,
            'modelsSection' => (empty($modelsSection)) ? [new Section] : $modelsSection,
            'modelsItem' => (empty($modelsItem)) ? [[new Item]] : $modelsItem
        ]);
    }

我从wbraganca的网站复制了代码。我根据需要更改代码。但是更新,就像我说的要在我的“区段”上更新并添加更多项目时所说的,该字段添加了3个字段,而不仅仅是一个。

我阅读了文档,但仍然找不到错误。

Here is the Video to what happen when I click on the add button

0 个答案:

没有答案