Home > other >  <optgroup> in admin form field
<optgroup> in admin form field

Time:12-15

I have an admin form with a few select fields declared in my _prepareForm method like the example below:

protected function _prepareForm()
{
    $form = new Varien_Data_Form(array(
        'id' => 'datacenter_action_form',
        'action' => $this->getUrl('*/*/saveConfig'),
        'method' => 'post',
        'enctype' => 'multipart/form-data'
    ));
    $fieldset = $form->addFieldset('base_fieldset', array('legend' => 'Example');
    $fieldset->addField('entity', 'select', array(
        'name' => 'action[entity]',
        'title' => 'Entity',
        'label' => 'Entity',
        'required' => true,
        'values' => array('one','two')
    ));

    ...

    return parent::_prepareForm();
}

I was wondering if it's possible to add optgroups to the field values the same way that is possible in source models by nesting the values, something like:

...
$fieldset->addField('entity', 'select', array(
        'name' => 'action[entity]',
        'title' => 'Entity',
        'label' => 'Entity',
        'required' => true,
        'values' => array('value' => array('one','two'), 'label' => 'Numbers')
    ));
...

Where the expected output would be:

<select>
    <optgroup label="Numbers">
        <option>one</option>
        <option>two</option>
    </optgroup>
</select>

Obs.: I already tried to model the same way as in the source model (by nesting values), but it don't seemed to work

CodePudding user response:

It's possible by nesting the options like:

...
$fieldset->addField('entity', 'select', array(
        'name' => 'action[entity]',
        'title' => 'Entity',
        'label' => 'Entity',
        'required' => true,
        'values' => array(
                    array('value' => array(
                        array('value' => 'one', 'label' => 'One'),
                        array('value' => 'two', 'label' => 'Two')
                    ), 'label' => 'Numbers'))
         ));
...

I had nested it wrongly :)

  • Related