zf2 创建选择/下拉框并在控制器中填充选项? [英] zf2 create select/drop down box and populate options in controller?
问题描述
为了创建一个文本输入框,我在 zend framework2 中使用了以下代码
To Create a text input box I used folling code in zend framework2
use Zend\Form\Form;
class Loginform extends Form
{
public function __construct()
{
$this->add(array(
'name' => 'usernames',
'attributes' => array(
'id' => 'usernames',
'type' => 'text',
),
'options' => array(
'label' => 'User Name',
),
));
}
}
并且我可以使用
$form = new Loginform();
$form->get('usernames')->setAttribute('value', 'user 1');
知道如何对 zf2 中的选择/下拉框执行相同操作吗?
Any idea how can I do the same for Selection/drop down box in zf2?
参考:zend 框架 2 文档
推荐答案
检查 API(文档很糟糕,所以检查代码).
Check the API (the docs are terrible, so check the code).
使用 Zend\Form\Element\Select
类并像这样设置 options 属性:
Use the Zend\Form\Element\Select
class and set the options attribute like so:
$element->setAttribute('options', array(
'key' => 'val',
...
));
使用 FormRow
或 FormSelect
视图助手输出元素.
Output the element using the FormRow
or FormSelect
view helper.
该站点也是示例和信息的良好来源:http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html
This site is also a good source for examples and information: http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html
示例:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'usernames',
'attributes' => array(
'id' => 'usernames',
'options' => array(
'test' => 'Hi, Im a test!',
'Foo' => 'Bar',
),
),
'options' => array(
'label' => 'User Name',
),
));
如果需要,您还可以在控制器中分配选项,如上所示.
You can also assign the options in the controller if you need to, as shown above.
这篇关于zf2 创建选择/下拉框并在控制器中填充选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!