I dug into the rendering code in Zend_View_Helper_FormSelect. Based on how the optgroup element is created I can see that there's no way to add an id or class to the optgroup. Here is a patch that should allow for the following use case but should still be backwards compatible. This is not necessarily the best way to do this and could probably be a lot better: I put it together very quickly. The existing code doesn't seem to follow the Zend Framework coding standards so I kept my new code similar to the code that's already there. Again, this could be a lot more extensible than it is (e.g. it only allows for id and not class or other arbitrary decorators).
Here is the use case that will give the desired output in my previous
email (id attribute on optgroup elements):
$optgroupTest = new Zend_Form_Element_Select('optgroup_test');
$options = array (
array(
'id' => 'option_group_1',
'label' => 'Option Group 1',
'options' => array (
'A' => 'Option A',
'B' => 'Option B',
'C' => 'Option C',
),
),
array(
'id' => 'option_group_2',
'label' => 'Option Group 2',
'options' => array (
'D' => 'Option D',
),
),
);
$optgroupTest
->setLabel('Optgroup Test')
->addMultiOptions(
$options
)
;
Here is the patch against Zend Framework 1.9.5 (tags/release-1.9.5)
that will make the above use case work (patch attached as well):
Index: View/Helper/FormSelect.php
===================================================================
--- View/Helper/FormSelect.php (revision 18900)
+++ View/Helper/FormSelect.php (working copy)
@@ -116,6 +116,15 @@
$translator = $this->getTranslator();
foreach ((array) $options as $opt_value => $opt_label) {
if (is_array($opt_label)) {
+ $opt_id = '';
+ if (is_integer($opt_value)) {
+ $opt_array = $opt_label;
+ if (array_key_exists('id', $opt_array)) {
+ $opt_id = ' id="' . $opt_array['id'] . '"';
+ }
+ $opt_value = $opt_array['label'];
+ $opt_label = $opt_array['options'];
+ }
$opt_disable = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
@@ -124,6 +133,7 @@
$opt_value = $translator->translate($opt_value);
}
$list[] = '<optgroup'
+ . $opt_id
. $opt_disable
. ' label="' . $this->view->escape($opt_value) .'">';
foreach ($opt_label as $val => $lab) {
---
Thanks,
Bradley
FormSelect.patch
Description: Binary data
