zf2 create select/drop down box and populate options in controller?

不羁的心 提交于 2019-12-05 11:24:09
Daniel M

Check the API (the docs are terrible, so check the code).

Use the Zend\Form\Element\Select class and set the options attribute like so:

$element->setAttribute('options', array(
    'key' => 'val',
    ...
));

Output the element using the FormRow or FormSelect view helper.

This site is also a good source for examples and information: http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html

Example:

$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.

$form = new Loginform();      
$form->get('usernames')->setValueOptions($usernames );

$usernames is an array

Ref Click Here

Mr Coder

Zend Framework 2.2 , select options have been moved into 'options' instead of 'attributes' so above code will be changed too

$this->add(array(     
    'type' => 'Zend\Form\Element\Select',       
    'name' => 'usernames',
    'attributes' =>  array(
       'id' => 'usernames'              
    ),
    'options' => array(
        'label' => 'User Name',
        'options' => array(
            'test' => 'Hi, Im a test!',
            'Foo' => 'Bar',
        ),
    ),
));

If you want to do it in controller then do it like this way

$form->get('ELEMENT_NAME')->setAttribute('options' ,array('KEY' => 'VALUE'));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!