zf2创建选择/下拉框并在控制器中填充选项?

Dev*_*per 5 zend-framework2

要创建一个文本输入框,我在zend framework2中使用了folling代码

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',
            ),
        ));       
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以使用控件操作填充值

$form = new Loginform();
$form->get('usernames')->setAttribute('value', 'user 1');
Run Code Online (Sandbox Code Playgroud)

知道如何在zf2中的选择/下拉框中执行相同的操作?

参考:zend框架2文档

Dan*_*l M 14

检查API(文档很糟糕,所以检查代码).

使用Zend\Form\Element\Select该类并设置options属性,如下所示:

$element->setAttribute('options', array(
    'key' => 'val',
    ...
));
Run Code Online (Sandbox Code Playgroud)

使用FormRowFormSelect视图助手输出元素.

该站点也是示例和信息的良好来源: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',
    ),
));    
Run Code Online (Sandbox Code Playgroud)

如果需要,您还可以在控制器中分配选项,如上所示.