Leben++

It's never too late to get a life!

Setting defaults on Zend_Form from an object

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.

Kommentare

Easier, but not universal

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.

Wär das nicht einfacher? $arr

Wär das nicht einfacher?

$arr = (array) $object;
$form->setDefaults($arr);

Kommentar hinzufügen

Der Inhalt dieses Feldes wird nicht öffentlich zugänglich angezeigt.
  • Internet- und E-Mail-Adressen werden automatisch umgewandelt.
  • Keine HTML-Tags erlaubt
  • Zeilen und Absätze werden automatisch erzeugt.
By submitting this form, you accept the Mollom privacy policy.
Inhalt abgleichen