wbraganca / yii2-dynamicform

It is widget to yii2 framework to clone form elements in a nested manner, maintaining accessibility.
Other
436 stars 438 forks source link

Do not create new model via 'createMultiple' method, but use existing when update is required #209

Open just-greg-me opened 7 years ago

just-greg-me commented 7 years ago

We we create new model the Yii validator is see that it's new, and the validators see this like new model, so, we can't work clearly with unique fields

pczi commented 7 years ago

I had the same problem, everything works fine if you respect the following 3 points: (1) Don't forget to put the hidden "id" field in the dynamic part of your form. (2) In actionUpdate, first populate with the old records: $modelActions = $model->inspectActions; (3) Then use the $pk parameter of the createMultiple like this (attention, $pk defaults to 'id' so set this parameter if your pk is different, mine is ID_Action): $oldIDs = ArrayHelper::getColumn($modelActions, 'ID_Action'); $modelActions = Model::createMultiple(Actions::classname(), $modelActions, 'ID_Action'); Model::loadMultiple($modelActions, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::getColumn($modelActions, 'ID_Action')));

-> createMultiple will then match the dynamic models by their Primarykey and create new ones if you added some records dynamically.

marcinmisiak commented 7 years ago

I think You need add PK in $model[] in foreach (line 35, 38) `<?php

namespace app\modules\portfolio\models;

use Yii; use yii\helpers\ArrayHelper;

class Model extends \yii\base\Model { /**