zf2 create select/drop down box and populate optio

2019-04-29 16:51发布

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',
            ),
        ));       
    }
}

and I can populate the values in controller action using

$form = new Loginform();
$form->get('usernames')->setAttribute('value', 'user 1');

Any idea how can I do the same for Selection/drop down box in zf2?

Ref: zend framework 2 documentation

4条回答
我只想做你的唯一
2楼-- · 2019-04-29 17:18

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',
        ),
    ),
));
查看更多
何必那么认真
3楼-- · 2019-04-29 17:21
$form = new Loginform();      
$form->get('usernames')->setValueOptions($usernames );

$usernames is an array

Ref Click Here

查看更多
冷血范
4楼-- · 2019-04-29 17:41

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.

查看更多
太酷不给撩
5楼-- · 2019-04-29 17:41

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

$form->get('ELEMENT_NAME')->setAttribute('options' ,array('KEY' => 'VALUE'));
查看更多
登录 后发表回答