Reputation: 1952
In Zend Framework I'm trying to create a select element that will automatically turn into a hidden element if there is only one item the user can select. I want it to behave just like a Select element if it has more than one value so I know that I need to extend the class using the following:
class Application_Form_Element_SingleSelect extends Zend_Form_Element_Select{}
But I'm not sure how to get it to output as a hidden element.
Update
This was the final code I came up with:
public function render(Zend_View_Interface $view = null){
$options = $this->getMultiOptions();
// check to see if there is only one option
if(count($options)!=1){
// render the view
return parent::render($view);
}
// start building up the hidden element
$returnVal = '<input type="hidden" name="' . $this->getName() . '" ';
// set the current value
$keys = array_keys($options);
$returnVal .= 'value="' . $keys[0] . '" ';
// get the attributes
$attribs = $this->getAttribs();
// check to see if this has a class
if(array_key_exists('class', $attribs)){
$returnVal .= 'class="' . $attribs['class'] . '" ';
}
// check to see if this has an id
if(array_key_exists('id', $attribs)){
$returnVal .= 'id="' . $attribs['id'] . '" ';
} else {
$returnVal .= 'id="' . $this->getName() . '" ';
}
return $returnVal . '>';
}
Upvotes: 0
Views: 393
Reputation: 8186
you need to override render method which is responsible for generating html through all decorators added to that element .
class Application_Form_Element_SingleSelect extends Zend_Form_Element_Select{
public function render(Zend_View_Interface $view = null)
{
$options = $this->getMultiOptions();
return count($options) > 1 ? parent::render($view) : '' ;
}
}
Upvotes: 1