Rúben Silva
Rúben Silva

Reputation: 21

ZF3 - Populate Select from Database

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.

Upvotes: 1

Views: 1080

Answers (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.

Upvotes: 1

Related Questions