oscarotero / form-manager

PHP library to create and validate html forms
MIT License
153 stars 42 forks source link

Optgroup not working in 6.1.0 #88

Closed psaikali closed 3 years ago

psaikali commented 3 years ago

First, thank you for this library, it's saved me countless hours of coding! Great job.

Issue

I've been using 6.0.0 for a while and generating <select> fields with <optgroup> in them. But after updating to 6.1.0 a few days ago, the HTML output for these fields is broken and optgroups no longer work.

Code used

$fields['test'] = Form::select(
    __( 'Test select  with optgroup', 'mbt' ),
    [
        'First optgroup' => [
            'option1_1' => 'First option',
            'option1_2' => 'Second option',
        ],
        'Another optgroup' => [
            'option2_1' => 'Another first option',
            'option2_2' => 'Another second option',
            'option2_3' => 'Third option',
        ],
    ],
    [
        'name'      => 'optgroup_field',
        'id'        => 'optgroup_field',
    ]
);

Before/After

6.0.0: Capture 2020-11-29 à 09 48 59

6.1.0: Capture 2020-11-29 à 09 49 15

In the screenshot below, you can see the expected working version (6.0.0) at the top, and the buggy HTML output generated with 6.1.0: Capture 2020-11-29 à 10 06 56

Has the syntax changed since 6.1.0 for using optgroup in select fields?

Thank you for your help.

oscarotero commented 3 years ago

Hi. Yes, there was a little change in the API in 6.1.0, sorry.

In 6.0.0, the only way to create options is with an array with [value => label]. This makes impossible to assign other attributes to a option (like id, data-*, class, etc..). So in 6.1.0, options can be defined as arrays, in order to assign any attribute. For example:

Form::select('select one option', [
    'option_1' => 'First option',
    'option_2' => [
        'label' => 'Second option',
        'id' => 'option_2'
    ]
]

To assign optgroups to selects, datalist, etc you have the function setOptgroups, taking your example:

$fields['test'] = Form::select(
    __( 'Test select  with optgroup', 'mbt' ),
    [],
    [
        'name'      => 'optgroup_field',
        'id'        => 'optgroup_field',
    ]
)->setOptgroups(
    [
        'First optgroup' => [
            'option1_1' => 'First option',
            'option1_2' => 'Second option',
        ],
        'Another optgroup' => [
            'option2_1' => 'Another first option',
            'option2_2' => 'Another second option',
            'option2_3' => 'Third option',
        ],
    ],
);
psaikali commented 3 years ago

Awesome, thanks @oscarotero :)