Yii2: вложенная динамическая форма wbraganca добавил больше полей - PullRequest
0 голосов
/ 16 сентября 2018

Я использую динамическую форму wbragnaca для yii2, кнопка «добавить и удалить» работает правильно при создании, безупречно. Но когда я обновляю инструмент, вложенная форма, которая является элементом, заключается в том, что, когда я нажимаю кнопку добавления, она добавляет 3 поля вместо одного.

Вот форма, прежде чем я нажимаю на кнопку Предметы - Выписка:

Форма инструмента до

Вот после нажатия кнопки «Добавить» на элементе:

Форма инструмента после

Вот мой дизайн базы данных:

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 поля, а не только одно.

Я прочитал документацию и все еще не могу найти ошибку.

Вот видео о том, что происходит, когда я нажимаю кнопку добавления

...