Siffer
Siffer

Reputation: 353

How to generate active hidden inputs in Yii2 for array values

I have a multidimensional array value for form attribute that I need to be included with form as hidden inputs.

$model->ids = ['first' => [1, 2], 'second' => [22]];

I can't use activeHiddenInput as it gives error

// gives error: "Array to string conversion"
<?= Html::activeHiddenInput($model, 'ids')?>

Expected outcome:

<input type="hidden" name="formName[ids][first][]" value="1" />
<input type="hidden" name="formName[ids][first][]" value="2" />
<input type="hidden" name="formName[ids][second][]" value="22" />

.. or ..

<input type="hidden" name="formName[ids][first][0]" value="1" />
<input type="hidden" name="formName[ids][first][1]" value="2" />
<input type="hidden" name="formName[ids][second][0]" value="22" />

What would be the best approach to solve this in yii2 framework concept?

Upvotes: 2

Views: 1561

Answers (1)

Siffer
Siffer

Reputation: 353

So this is how I solved with in case anyone needs it.

I extended yii/bootstrap/Html class with following methods:

/**
 * Generates list of hidden input tags for the given model attribute when the attribute's value is an array.
 *
 * @param Model $model
 * @param string $attribute
 * @param array $options
 * @return string
 */
public static function activeHiddenInputList($model, $attribute, $options = [])
{
    $str = '';
    $flattenedList = static::getflatInputNames($attribute, $model->$attribute);
    foreach ($flattenedList as $flattenAttribute) {
        $str.= static::activeHiddenInput($model, $flattenAttribute, $options);
    }
    return $str;
}

/**
 * @param string $name
 * @param array $values
 * @return array
 */
private static function getflatInputNames($name, array $values)
{
    $flattened = [];
    foreach ($values as $key => $val) {
        $nameWithKey = $name . '[' . $key . ']';
        if (is_array($val)) {
            $flattened += static::getflatInputNames($nameWithKey, $val);
        } else {
            $flattened[] = $nameWithKey;
        }
    }
    return $flattened;
}

Calling Html::activeHiddenInputList($model, 'ids'); will give output of

<input id="formname-ids-first-0" type="hidden" name="formName[ids][first][0]" value="1" />
<input id="formname-ids-first-1" type="hidden" name="formName[ids][first][1]" value="2" />
<input id="formname-ids-second-0" type="hidden" name="formName[ids][second][0]" value="22" />

Upvotes: 1

Related Questions