laminas / laminas-form

Validate and display simple and complex forms, casting forms to business objects and vice versa
https://docs.laminas.dev/laminas-form/
BSD 3-Clause "New" or "Revised" License
80 stars 52 forks source link

\Laminas\Form\View\Helper\FormSelect does not allow class attribute for <option>s #239

Closed mattfletcher closed 1 year ago

mattfletcher commented 1 year ago

Bug Report

Q A
Version(s) 2.1.x-dev

Summary

It is not possible to set a class="" attribute on a

Current behavior

The class attributes specified on the valueOptions array are stripped out.

How to reproduce

$valueOptions = [];
foreach (countries() as $country) {
    $valueOptions[] = [
        'name'  => $country['name'],
        'class' => 'fi fi-' . strtolower($country['iso_3166_1_alpha2']),
        'value' => $country['iso_3166_1_alpha2'],
        'label' => $country['name'] . ' (+' . $country['calling_code'] . ')',
    ];
}

usort($valueOptions, static fn($a, $b) => $a['name'] <=> $b['name']);

$element = new Select(self::COUNTRY_CALLING_CODE);
$element->setLabel('Country calling code');
$element->setValueOptions($valueOptions);

Expected behavior

Each option would have a class attribute of "fi fi-gb" (etc)

Xerkus commented 1 year ago

class is an attribute, not an option:

$valueOptions = [];
foreach (countries() as $country) {
    $valueOptions[] = [
        'name'  => $country['name'],
        'attributes' => [
            'class' => 'fi fi-' . strtolower($country['iso_3166_1_alpha2']),
        ],
        'value' => $country['iso_3166_1_alpha2'],
        'label' => $country['name'] . ' (+' . $country['calling_code'] . ')',
    ];
}

usort($valueOptions, static fn($a, $b) => $a['name'] <=> $b['name']);

$element = new Select(self::COUNTRY_CALLING_CODE);
$element->setLabel('Country calling code');
$element->setValueOptions($valueOptions);

There is a test asserting class attribute is utilized, so marking this as not a bug:

https://github.com/laminas/laminas-form/blob/c6100a664879b6f5638b0fae0c844051f2159902/test/View/Helper/FormSelectTest.php#L71C98-L71C98

froschdesign commented 1 year ago

This can also be found in the documentation:

Attributes on the options are supported by providing the options as a specification array instead of key-value pairs:

https://docs.laminas.dev/laminas-form/v3/element/select/#basic-usage