Zend Forms - populate() and setDefaults()

☆樱花仙子☆ 提交于 2019-12-21 04:15:11

问题


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.


回答1:


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

$data = array( 'first_name' => 'Mickey', 'last_name' => 'Mouse' );



回答2:


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());



回答3:


FYI - in Zend_Form, $form->populate($data) just makes a call to $form->setDefaults($data).




回答4:


simple, create an array

$data = array('nameInput'=> 'your value');

Add your form to your View

$this->view->form = $form;

then you add data to the form

$form->populate($data);


来源:https://stackoverflow.com/questions/1301889/zend-forms-populate-and-setdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!