ZF-12172: formSelect Helper will not properly call __toString if object is passed as value

Description

When passing an object to Zend_View_Helper_FormSelect, the __toString method will not be called since the value is cast to an array in with array_map('strval', (array) $value);

This causes PHP error if some properties of the object do not implement __toString

Test Case


class Foo
{
    public $_filter;

    public $_value;

    public function __construct()
    {
        $this->_filter = new Zend_Filter();
    }

    public function setValue($value)
    {
        $this->_value = $this->_filter->filter($value);
        return $this;
    }

    public function __toString()
    {
        return $this->_value;
    }
}

$foo = new Foo();
$foo->setValue('bar');

echo $view->formSelect('test',
            $foo,
            null,
            array('bar','baz','bat'));

The above will throw a fatal error that Zend_Filter cannot be converted to string. I have a fix that I will apply to Zend_View_Helper_FormSelect:



if (is_object($value)) {
    //if the object can be iterated, loop through
    if ($value instanceof Iterator) {
    $temp = array();
    foreach($value as $key => $value) {
        $temp[$key] = (string) $value;
    }

    $value = $temp;
    } else {
    $value = array((string) $value);
    }
} else {
    $value = array_map('strval', (array) $value);
}

Comments

No comments to display