ZF3 - Populate Select from Database

大城市里の小女人 提交于 2019-12-11 05:03:32

问题


I'm doing some work using Zend Framework 3 and I need to display in the form a select populated with options comming from the database. I am using SQL Abstraction used in the Zend Tutorial blog part. The idea is to show the form that is already build and add a simple select with data returned from a different table, all the form is working using the users table (which has the country id) and i would like to link that id to the correct table and then show all the countries in the select..

Thank's everyone.


回答1:


You will write a factory for your form. Select data in that factory and pass to form via construct or some set method, and use that data as value options.

class MyFormFactory implements FactoryInterface {
    public function __invoke($container, $options) {
         $data = []; // call repository via $container and fetch your data
         $form = new MyForm();

         $form->setCountries($data);

         return $form;
    }
}

class MyForm extends \Zend\Form\Form {
    private $countries = [];

    public function setCountries(array $countries) {
         $this->countries = $countries;
    }

    public function init(){
         $this->add([
             'type' => Select::class,
             'name' => 'countries',
             'options' => [
                  'label' => 'Countries',
                  'value_options' => $this->countries
             ]
         ]);
    }
}

and put your form under factories key in config

return [
     'form_elements' => [
          'factories' => [
              MyForm::class => MyFormFactory::class
          ]
     ]
];

Now when you call your form over FormElementManager, your factory will trigger, it will call repository and fetch data, pass it to your form.

Don't forget to add Zend\Form in your modules config.

This approach works well with zf3.



来源:https://stackoverflow.com/questions/49609300/zf3-populate-select-from-database

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