D
D
dimonfreeman2019-05-06 12:09:16
Yii
dimonfreeman, 2019-05-06 12:09:16

Yii2 dynamicform remove last fields on update and duplicate first ones, where is error?

Yii2 dynamicform remove last fields on update and duplicate first..

?php DynamicFormWidget::begin([
                'widgetContainer' => 'dynamicform_wrapper', 
                'widgetBody' => '.container-items', 
                'widgetItem' => '.item', 
                'limit' => 70, 
                'min' => 0,
                'insertButton' => '.add-item', 
                'deleteButton' => '.remove-item', 
                'model' => $modelsAttributeLists[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'attr_name',
                    'attr_value',
                    'attr_id',
                ],
            ]); ?>

            <div class="panel panel-default">
                <div class="panel-heading">
                        Атрибут товара
                    <button type="button" class="pull-right add-item btn btn-success btn-xs"><i class="fa fa-plus"></i> Добавить атрибут</button>
                    <div class="clearfix"></div>
                </div>
                <div class="panel-body container-items"><!-- widgetContainer -->
                    <?php foreach ($modelsAttributeLists as $index => $modelAttributeList): ?>
                        <div class="item panel panel-default"><!-- widgetBody -->
                            <div class="panel-heading">
                                <span class="panel-title-attribute">Атрибут: <?= ($index + 1) ?></span>
                                <button type="button" class="pull-right remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
                                <div class="clearfix"></div>
                            </div>
                            <div class="panel-body">
                                <?php
                                    // necessary for update action.
                                    if (!$modelAttributeList->isNewRecord) {
                                        echo Html::activeHiddenInput($modelAttributeList, "[{$index}]id");
                                    }
                                ?>

                                <div class="row">
                                    <div class="col-sm-6">
                                        <?= $form->field($modelAttributeList, "[{$index}]attr_id")->dropDownList(
                                                ArrayHelper::map(AttributeName::find()->all(), 'id', 'name'),
                                                        ['prompt'=>'Выбрать атрибут']
                                        ); ?>
                                    </div>
                                    <div class="col-sm-6">
                                        <?= $form->field($modelAttributeList, "[{$index}]attr_value")->textInput(['maxlength' => true]) ?>
                                    </div>
                                </div><!-- end:row -->
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php DynamicFormWidget::end(); ?>

and controller
` public function actionUpdate($id)
{

    $model = $this->findModel($id);
    $modelsAttributeLists = $model->attributeLists;
    $modelsJunction = $model->junctionTable;

    if ($model->load(Yii::$app->request->post())) {
  
        if ($model->url == null) {
            //generate translite url
            $model->url = Inflector::slug(Inflector::transliterate($model->name), '-', true);
        }

        //currency
        $model->price_foreign = $_POST['Product']['price_foreign'];

        //attributeLists
        $oldIDs = ArrayHelper::map($modelsAttributeLists, 'id', 'id');
        $modelsAttributeLists = Model::createMultiple(AttributeList::classname(), $modelsAttributeLists);
        Model::loadMultiple($modelsAttributeLists, Yii::$app->request->post());

        $oldBrandIDs = ArrayHelper::map($modelsJunction, 'id', 'id');
        $modelsJunction = Model::createMultiple(ProductBrandCategory::classname(), $modelsJunction);
        Model::loadMultiple($modelsJunction, Yii::$app->request->post());

        $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsAttributeLists, 'id', 'id')));
        $deletedBrandIDs = array_diff($oldBrandIDs, array_filter(ArrayHelper::map($modelsJunction, 'id', 'id')));


        if (Yii::$app->request->isAjax) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ArrayHelper::merge(
            ActiveForm::validateMultiple($modelsAttributeLists),
            ActiveForm::validate($modelsAttributeLists)
             );
          }
        // validate all models

        $valid = $model->validate();
        $valid = Model::validateMultiple($modelsAttributeLists) && $valid;
        $valid = Model::validateMultiple($modelsJunction) && $valid;

        if ($valid) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($flag = $model->save(false)) {
                    if (!empty($deletedIDs)) {

                        AttributeList::deleteAll(['id' => $deletedIDs]);
                    }
                    foreach ($modelsAttributeLists as $modelAttributeList) {
                        $modelAttributeList->product_id = $model->id;
                        if (!($flag = $modelAttributeList->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }

                    if (!empty($deletedBrandIDs)) {
                        ProductBrandCategory::deleteAll(['id' => $deletedBrandIDs]);
                    }
                    foreach ($modelsJunction as $modelJunction) {
                        $modelJunction->product_id = $model->id;
                        if (!($flag = $modelJunction->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }

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

        $model->save();

    } else {
        return $this->render('update', [
            'model' => $model,
            'modelsAttributeLists' => (empty($modelsAttributeLists)) ? [new AttributeList] : $modelsAttributeLists,
            'modelsJunction' => (empty($modelsJunction)) ? [new ProductBrandCategory] : $modelsJunction,
        ]);
    }
}`

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-05-06
@slo_nik

Good afternoon.
Use Model::loadMultipleinstead $model->load()
Read about tabular input and as an add - on working with multiple models .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question