Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Forms - populate() and setDefaults()

Let's say I have a form that collects a first name and a last name:

$first_name = new Zend_Form_Element_Text('first_name');
$first_name->setLabel("First Name")
    ->setRequired(true);

$last_name = new Zend_Form_Element_Text('last_name');
$last_name->setLabel("Last Name")
    ->setRequired(true);

$form = new Zend_Form();
$form->addElement($first_name)
    ->addElement($last_name)

If I want to use the "populate($data)" or the "setDefaults($data)" method on the form, how does the array need to be organized? What kind of an array do these functions expect? I haven't been able to find this information in the docs.

Also, I know that I can set the value when creating the element itself, but this is not what I need.

like image 697
Scott Avatar asked Aug 19 '09 18:08

Scott


2 Answers

The form->populate() method takes an array where the keys are the names of the form fields.

The Zend_Db_Table_Row object implements a toArray() method which can be used here (as do many other objects). So you can do stuff like:

$form = new MyForm;

$table = new MyTable;
$rowset = $table->find($id);
$row = $rowset->current();

$form->populate($row->toArray());
like image 154
Michi Avatar answered Sep 17 '22 13:09

Michi


Array keys are the field names, array values are the field values.

$data = array( 'first_name' => 'Mickey', 'last_name' => 'Mouse' );
like image 20
Steve Avatar answered Sep 17 '22 13:09

Steve