php Zend Forms - populate() 和 setDefaults()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1301889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:56:39  来源:igfitidea点击:

Zend Forms - populate() and setDefaults()

phpzend-frameworkforms

提问by Scott

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.

如果我想在表单上使用“populate($data)”或“setDefaults($data)”方法,需要如何组织数组?这些函数需要什么样的数组?我无法在文档中找到此信息。

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

另外,我知道我可以在创建元素本身时设置值,但这不是我需要的。

回答by Michi

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

form->populate() 方法接受一个数组,其中的键是表单字段的名称。

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:

Zend_Db_Table_Row 对象实现了一个可以在这里使用的 toArray() 方法(就像许多其他对象一样)。所以你可以做这样的事情:

$form = new MyForm;

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

$form->populate($row->toArray());

回答by Steve

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

数组键是字段名称,数组值是字段值。

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

回答by Devon

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

仅供参考 - 在 Zend_Form 中,$form->populate($data)只需调用$form->setDefaults($data).

回答by cristianojeda

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