ZF3-填充从数据库中选择 [英] ZF3 - Populate Select from Database

查看:113
本文介绍了ZF3-填充从数据库中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Zend Framework 3做一些工作,我需要以选择的形式显示一个填充有来自数据库的选项的选择.我正在使用Zend Tutorial博客部分中使用的SQL Abstraction.这样做的目的是显示已构建的表单,并添加一个简单选择,其中包含从其他表返回的数据,所有表单都在使用users表(具有国家/地区ID)工作,我想将该ID链接到正确的表,然后显示选择的所有国家/地区.

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

谢谢大家.

推荐答案

您将为表单编写一个工厂.在该工厂中选择数据,然后通过construct或某些set方法传递给表单,然后将该数据用作值选项.

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
             ]
         ]);
    }
}

并将您的表单放在config中的factory键下

and put your form under factories key in config

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

现在,当您通过FormElementManager调用表单时,工厂将触发,它将调用存储库并获取数据,并将其传递给表单.

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

别忘了在模块配置中添加Zend\Form.

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

这种方法在zf3中效果很好.

This approach works well with zf3.

这篇关于ZF3-填充从数据库中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆