【问题标题】:symfony form choice field : set choices option default data from external datasourcesymfony 表单选择字段:从外部数据源设置选择选项默认数据
【发布时间】:2015-06-19 07:50:06
【问题描述】:

如何使用外部数据数组填充选项选项?

$builder->add('gender', 'choice', array(
    'choices' => [array from webservice or other class]
));

文档只显示简单的静态数组 http://symfony.com/fr/doc/2.7/reference/forms/types/choice.html#choices

我试过了:

控制器:

$event = new Event();
$form = $this->createForm(new EventType($this->get('api')), $event);

表格:

class EventType extends AbstractType
{
    protected $myservice;

    public function __construct($myservice)
    {
        $this->myservice = $myservice;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titre')
            ->add('id_rubrique', 'choice', array(
                'choices' => $this->myservice->getRubriques
        ;
    }

    ....
}

这是正确的解决方案吗?

【问题讨论】:

  • 你在使用 EventListeners 吗?
  • 要么这样,要么将您的表单更改为服务,并通过服务注入依赖关系并使用构造函数。 symfony.com/fr/doc/current/reference/…
  • 或者通过控制器传入。

标签: php symfony


【解决方案1】:

将表单定义为服务:

services:
    my.form:
        class: EventType
        arguments:
            - @api

然后在控制器中:

$event = new Event();
$form = $this->createForm('my.form', $event);

【讨论】:

    【解决方案2】:

    例子

    ->add('education', 'choice', array('label' => 'Education *','choices' => $this->getEducation(), 'required' => true, 'empty_value' => 'select', 'empty_data'  => null))
    

    $this->getEducation() 是数组

    //数组('option1Value' => 'option1Name'...

    【讨论】:

      猜你喜欢
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      相关资源
      最近更新 更多