Php – Zend_Form_Element_Select default value

PHPzend-framework

In my form, I want to set the selected (default) value for a select element. However, using setDefaults is not working for me.

Here is my code:

$gender = new Zend_Form_Element_Select('sltGender');
$gender->setMultiOptions(array(
    -1 => 'Gender',
    0 => 'Female',
    1 => 'Male'
))
->addValidator(new Zend_Validate_Int(), false)
->addValidator(new Zend_Validate_GreaterThan(-1), false);

$this->setDefaults(array(
    'sltGender' => 0
));

$this->addElement($gender);

My controller is simply assigning the form to a view variable which just displays the form.

It works by using $gender->setValue(0), but it would be easier to set them all at once with an array of default values. Am I misunderstanding something here?

Also, where is the Zend Framework documentation for classes and methods? I am looking for something similar to the Java documentation. The best I could find is this one, but I don't like it – especially because every time I try to search, it crashes.

Best Answer

Have you tried:

$this->addElement($gender);

$this->setDefaults(array(
    'sltGender' => 0
));

Also, take a look at http://framework.zend.com/issues/browse/ZF-12021 .

As you can see, the above issue is similar to the issue you're describing. It seems Zend is very particular about the order you create objects and assign settings.

I'm afraid you're going to have to do things in the order Zend wants you to do them (which doesn't seem well documented, but is only discovered thru trial and error), or hack their library to make it do what you want it to do.

Related Topic