ZF2 get values from database into form class

浪子不回头ぞ 提交于 2019-12-06 14:51:28

问题


In ZF2, suppose I have a Select in the form:

    $this->add([
        'type' => 'Zend\Form\Element\Select',
        'name' => 'someName',
        'attributes' => [
            'id' => 'some-id',
        ],
        'options' => [
            'label' => 'Some Label',
            'value_options' => [
                '1' => 'type 1',
                '2' => 'type 2',
                '3' => 'type 3',
            ],
        ],
    ]);

How can I put the values 'type 1', 'type 2', 'type 3', etc. from a database query into value_options?


回答1:


By registering a custom select element with the form element manager, you can use a factory to load the required form options.

namespace MyModule\Form\Element;

class TypeSelectFactory
{
    public function __invoke(FormElementManager $formElementManager)
    {
        $select = new \Zend\Form\Element\Select('type');
        $select->setAttributes(]
            'id' => 'some-id',
        ]);
        $select->setOptions([
            'label' => 'Some Label',
        ]);

        $serviceManager = formElementManager->getServiceLocator();
        $typeService  = $serviceManager->get('Some\\Service\\That\\Executes\\Queries');

        // getTypesAsArray returns the expected value options array 
        $valueOptions = $typeService->getTypesAsArray();

        $select->setValueOptions($valueOptions);

        return $select;
    }
}

And the required configuration for module.config.php.

'form_elements' => [
    'factories' => [
        'MyModule\\Form\\Element\\TypeSelect'
            => 'MyModule\\Form\\Element\\TypeSelectFactory',
    ]
],

You can then use MyModule\\Form\\Element\\TypeSelect as the type value when adding the element to a form.

Also make sure to read the documentation regarding custom form elements; this describes how to use the form element manager correctly, essential for the above to work.



来源:https://stackoverflow.com/questions/35975766/zf2-get-values-from-database-into-form-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!