The setDefaults method from Zend_Form expects an array, but sometimes you have an object with getter and setter methods you want to use as default. In this case, you can use a PHP ReflectionObject to extend Zend_Form like this:
We can then use this code
to set an object like this
For the setDefaultsFromObject method to work, your form fields must match the names of the getters of the object. For example, the value for the field city is retrieved with the method getCity(). Note how the checkbox for the Terms and conditions is left untouched because the object has no method for it.
The method only works for simple cases where you have no subforms and no array notation in element names. If you need subforms or array notation, have a look at the original setDefaults method.
If your object has only public fields, then converting the the object with $arr = (array) $object is the easier way. But when some values can only be reached with getters or if your fields are private or protected (as they should be in good design) then a simple array conversion will not work.
Easier, but not universal
If your object has only public fields, then converting the the object with
$arr = (array) $objectis the easier way. But when some values can only be reached with getters or if your fields are private or protected (as they should be in good design) then a simple array conversion will not work.