I want know how to add custom attribute for option in a select field of Zend form.
PHP:
$option_values = array("multiOptions" => array(
"US" => "United States",
"CA" => "Canada",
));
$type=array('big','small');
$option= new Zend_Form_Element_Select('option', $option_values);
HTML:
<select>
<option value='US' type='big'>United States</option>
<option value='CA' type='small'>Canada</option>
</select>
How to add this type attribute in the option?
It is not possible using ZF's implementation of
Zend_Form_Element_Select
. You need to create your own element. I have done something similar, here's the relevant code:Put this into /library/Zend/Form/Element/SelectAttribs.php. You also need a helper to render the element. Put it into your view helpers directory, name it SelectAttribs.php as well. Here's the contents of my file:
With this, you should be ready to go:
I didn't find @mingos's answer complete and had some issues with implementing setting the value. His answer helped a lot with what needed to be extended and changed however. Once I had that start the rest was pretty easy. I just extended ZF1's Select and overrode where I needed:
And the view helper:
class MyNamespace_View_Helper_SelectAttribs extends Zend_View_Helper_FormElement {
}
And implementation in a form would be something like:
I hope that helps someone. Thanks.
You could extend / overwrite the
Zend_View_Helper_FormSelect
helper but the real problem is going to be getting the extra data into each option.By default,
Zend_Form_Element_Select
(viaZend_Form_Element_Multi
) expects two strings for each option, one for thevalue
attribute and an optional one for the text content. You may need to create your own element to handle the extra data.mingos, you forgot about setvalue method of multiselect.
you shoul add something like:
No need for custom form element at all, what u can do is: $element->setAttrib('disable', array(1, 2, 5));
As explained at http://pietervogelaar.nl/set-attribute-on-select-option-with-zend_form/
Using addMultiOption($value,$label) I just set the value parameter to something like:
and when it renders you get:
Hope this helps....
Okay, value gets escaped but optionClasses does not so inside the loop that adds the addMultiOptions(val,lable) I do something like this:
and then after the loop just do a setAttrib('optionClasses',$optionClasses)
And that actually works...
I answered this for another question but could not find a way to add a comment here to reference it; It was Zend Framework addMultiOption adding custom parameters like "rel" for options