Firstly sorry for my bad english!
I'm using the Yii2-dynamicforms extension to nested forms in Yii 2.
Following this guide, I was able to make Create Action work properly, but Update Action partially.
Let me explain using my case...
I can create a Mission (missao) with many Groups (grupo) and many Slots for each group;
On Update, I can add some Slots for existing Groups, but when I try to add a new Group and new slots for this new Group, I got an error Undefined offset: 2 // for example
The error occurs near this section of my Update Action in controller:
// get Slots data from POST
$newSlotIds = [];
$loadsData['_csrf'] = Yii::$app->request->post()['_csrf'];
for ($i=0; $i < count($modelsGrupos); $i++) {
$loadsData['MissaoSlot'] = Yii::$app->request->post()['MissaoSlot'][$i];
// ERROR POINTS TO THE LINE BELOW
$modelsSlots[$i] = Model::createMultiple(MissaoSlot::classname(), $modelsSlots[$i], $loadsData);
Model::loadMultiple($modelsSlots[$i], $loadsData);
$newSlotIds = array_merge($newSlotIds, ArrayHelper::getColumn($loadsData['MissaoSlot'], 'id'));
}
On Yii log, i see this:
Failed to set unsafe attribute 'id' in 'app\models\MissaoGrupo'.
/var/www/html/qg_armapoint/modules/admin/controllers/MissaoController.php (134)
The line 134:
Model::loadMultiple($modelsGrupos, Yii::$app->request->post());
I have reviewed all my code following his example and didn't find the error.
Can anyone help me, please?
My Update Action in Controller:
use app\models\Missao;
use app\models\MissaoGrupo;
use app\models\MissaoSlot;
use app\base\Model;
use yii\helpers\ArrayHelper;
/**
........
*/
public function actionUpdate($id)
{
// retrieve existing Missao (mission) data
$model = $this->findModel($id);
// retrieve existing Grupos (groups) data
$oldGrupoIds = MissaoGrupo::find()->select('id')->where(['missao_id' => $id])->asArray()->all();
$oldGrupoIds = ArrayHelper::getColumn($oldGrupoIds,'id');
$modelsGrupos = MissaoGrupo::findAll(['id' => $oldGrupoIds]);
$modelsGrupos = (empty($modelsGrupos)) ? [new MissaoGrupo] : $modelsGrupos;
// retrieve existing Slots data
$oldSlotIds = [];
foreach ($modelsGrupos as $i => $modelGrupo) {
$oldSlots = MissaoSlot::findAll(['grupo_id' => $modelGrupo->id]);
$modelsSlots[$i] = $oldSlots;
$oldSlotIds = array_merge($oldSlotIds, ArrayHelper::getColumn($oldSlots, 'id'));
$modelsSlots[$i] = (empty($modelsSlots[$i])) ? [new MissaoSlot()] : $modelsSlots[$i];
}
// handle POST
if ($model->load(Yii::$app->request->post())) {
// get Groups data from POST
$modelsGrupos = Model::createMultiple(MissaoGrupo::classname(), $modelsGrupos);
Model::loadMultiple($modelsGrupos, Yii::$app->request->post());
$newGrupoIds = ArrayHelper::getColumn($modelsGrupos, 'id');
// get Slots data from POST
$newSlotIds = [];
$loadsData['_csrf'] = Yii::$app->request->post()['_csrf'];
for ($i=0; $i < count($modelsGrupos); $i++) {
$loadsData['MissaoSlot'] = Yii::$app->request->post()['MissaoSlot'][$i];
$modelsSlots[$i] = Model::createMultiple(MissaoSlot::classname(), $modelsSlots[$i], $loadsData);
Model::loadMultiple($modelsSlots[$i], $loadsData);
$newSlotIds = array_merge($newSlotIds, ArrayHelper::getColumn($loadsData['MissaoSlot'], 'id'));
}
// delete removed data
$delSlotIds = array_diff($oldSlotIds, $newSlotIds);
if (! empty($delSlotIds)) MissaoSlot::deleteAll(['id' => $delSlotIds]);
$delGrupoIds = array_diff($oldGrupoIds, $newGrupoIds);
if (! empty($delGrupoIds)) MissaoGrupo::deleteAll(['id' => $delGrupoIds]);
// validate all models
$valid = $model->validate();
$valid = $this->validaMissao($modelsGrupos, $modelsSlots) && $valid;
if ($valid) {
if ($this->saveMissao($model, $modelsGrupos, $modelsSlots)) {
return $this->redirect(['view', 'id' => $model->id]);
}
}
}
return $this->render('update', [
'model' => $model,
'modelsGrupos' => $modelsGrupos,
'modelsSlots' => $modelsSlots,
]);
}
protected function saveMissao($modelMissao, $modelsGrupos, $modelsSlots)
{
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($go = $modelMissao->save(false)) {
foreach ($modelsGrupos as $i => $modelGrupo) {
$modelGrupo->missao_id = $modelMissao->id;
if ($go = $modelGrupo->save(false)) {
foreach ($modelsSlots[$i] as $j => $modelSlot) {
$modelSlot->grupo_id = $modelGrupo->id;
if (! ($go = $modelSlot->save(false))) {
$transaction->rollBack();
break;
}
}
}
}
}
if ($go) {
$transaction->commit();
}
} catch (Exception $e) {
$transaction->rollBack();
}
return $go;
}
app\base\Model
namespace app\base;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* @param string $modelClass
* @param array $multipleModels
* @return array
*/
public static function createMultiple($modelClass, $multipleModels = [], $data = null)
{
$model = new $modelClass;
$formName = $model->formName();
$post = empty($data) ? Yii::$app->request->post($formName) : $data[$formName];
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
The view
<div role="tabpanel" class="tab-pane" id="aba-slots">
<br/>
<div class="panel panel-default">
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.container-grupos',
'widgetItem' => '.grupo',
//'limit' => 4,
'min' => 1,
'insertButton' => '.add-grupo',
'deleteButton' => '.remove-grupo',
'model' => $modelsGrupos[0],
'formId' => 'frm_missao',
'formFields' => [
'nome',
],
]); ?>
<div class="panel panel-default">
<div class="panel-heading">Grupos / Slots</div>
<div class="panel-body container-grupos">
<?php foreach ($modelsGrupos as $i => $modelGrupo): ?>
<div class="row grupo"> <!-- Item Grupo - INICIO -->
<table class="table">
<tr>
<th style="width:5%">#</th>
<th>Grupo</th>
<th>Slot</th>
</tr>
<tr>
<td><button class="btn btn-danger remove-grupo"><i class="fa fa-minus"></i></button></td>
<td class="col-md-4">
<?php
// necessary for update action.
if (! $modelGrupo->isNewRecord) {
echo Html::activeHiddenInput($modelGrupo, "[{$i}]id");
}
?>
<?= $form->field($modelGrupo, "[{$i}]nome")->textInput(['maxlength' => true, 'placeholder' => 'Nome do Grupo'])->label(false) ?>
</td>
<td><!-- Slots -->
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_inner',
'widgetBody' => '.container-slots',
'widgetItem' => '.slot',
//'limit' => 10,
'min' => 1,
'insertButton' => '.add-slot',
'deleteButton' => '.remove-slot',
'model' => $modelsSlots[$i][0],
'formId' => 'frm_missao',
'formFields' => [
'nome',
],
]); ?>
<table class="table container-slots">
<?php foreach ($modelsSlots[$i] as $j => $modelSlot): ?>
<tr class="slot">
<td>
<?php
// necessary for update action.
if (! $modelSlot->isNewRecord) {
echo Html::activeHiddenInput($modelSlot, "[{$i}][{$j}]id");
}
?>
<?= $form->field($modelSlot, "[{$i}][{$j}]nome")->textInput(['maxlength' => true, 'placeholder' => 'Nome do Slot'])->label(false) ?>
</td>
<td style="width:5%"><button class="btn btn-danger btn-xs remove-slot"><i class="fa fa-minus"></i></button></td>
</tr>
<?php endforeach; ?>
<tfoot>
<tr>
<td colspan="2"><button class="btn btn-info btn-xs add-slot"><i class="fa fa-plus"></i> Novo Slot</button></td>
</tr>
</tfoot>
</table>
<?php DynamicFormWidget::end(); ?>
</td><!--Slots - fim -->
</tr>
</table>
</div> <!-- Item Grupo - FIM -->
<?php endforeach; ?>
</div>
<div class="panel-footer">
<button class="btn btn-primary btn-xs add-grupo"><i class="fa fa-plus"></i> Novo Grupo</button>
</div>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
Thank You!
EDIT: Added MissaoGrupo Model
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%missao_grupo}}".
*
* @property integer $id
* @property string $nome
* @property integer $missao_id
*
* @property Missao $missao
* @property MissaoSlot[] $missaoSlots
*/
class MissaoGrupo extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%missao_grupo}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nome'], 'required'],
[['missao_id'], 'integer'],
[['nome'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'nome' => 'Grupo',
'missao_id' => 'Missao ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getMissao()
{
return $this->hasOne(Missao::className(), ['id' => 'missao_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getMissaoSlots()
{
return $this->hasMany(MissaoSlot::className(), ['grupo_id' => 'id']);
}
}
It's quite simple. Consider this scenario:
In code:
if it's properly selected there might be no DB record with id equal to '2'. Because of that in code below:
$i
will never be equal to '2' so there won't be$modelsSlots[2]
. But in following code$i
might have value of '2' so you have error that you try to use not existing array offset. (e.g. there are 5 modelsGroups but none of them has id equal to '2')I advise to change this code to something like that:
Beside of that you should add 'id' parameter as safe attribute in Model's validation rules to get rid of error in log file:
EDIT:
How about this sample: