zend form custom attribute in select option?

前端 未结 6 1023
慢半拍i
慢半拍i 2020-12-29 09:04

I want know how to add custom attribute for option in a select field of Zend form.

PHP:

$option_values = array(\"multiOptions\" => array(
    \"US         


        
6条回答
  •  别那么骄傲
    2020-12-29 09:32

    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:

    s
     * @author Dominik Marczuk
     */
    class Zend_Form_Element_SelectAttribs extends Zend_Form_Element {
    
        public $options = array();
    
        public $helper = 'selectAttribs';
    
        /**
         * Adds a new 

    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:

    \n") {
            $info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
            extract($info); // name, id, value, attribs, options, listsep, disable
    
            // force $value to array so we can compare multiple values to multiple
            // options; also ensure it's a string for comparison purposes.
            $value = array_map('strval', (array) $value);
    
            // now start building the XHTML.
            $disabled = '';
            if (true === $disable) {
                $disabled = ' disabled="disabled"';
            }
    
            // Build the surrounding select element first.
            $xhtml = '_htmlAttribs($attribs)
                    . ">\n  ";
    
            // build the list of options
            $list = array();
            $translator = $this->getTranslator();
            foreach ($options as $opt_value => $option) {
                $opt_disable = '';
                if (is_array($disable) && in_array($opt_value, $disable)) {
                    $opt_disable = ' disabled="disabled"';
                }
                $list[] = $this->_build($option, $disabled);
            }
    
            // add the options to the xhtml and close the select
            $xhtml .= implode("\n   ", $list) . "\n";
    
            return $xhtml;
        }
    
        protected function _build($option, $disabled) {
            $html = ' $value) {
                $html .= " $attrib=\"$value\"";
            }
            return $html.$disabled.">".$option['label']."";
        }
    }
    

    With this, you should be ready to go:

    $elt = new Zend_Form_Element_SelectAttribs('whatever');
    $elt->addOption($value,$label,array('attribname' => 'attribvalue'));
    

提交回复
热议问题