Symfony2 - 如何在角色,表组,FOSUserBundle的twig中创建列表复选框

时间:2012-09-26 09:23:05

标签: forms symfony checkbox

我想在表Group中创建一个包含角色的复选框列表,一个复选框是一个角色。 我有代码覆盖GroupFormType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);
    $builder->add('roles', 'choice', array(
            'choices'   => ???,//i don't know how to get roles in database
        'empty_value' => false,
        'multiple' => true,
        'expanded' => true,
        'required'  => false,
    ));
}

如果我这样做'choices' => array(1 => 'one', 2 => 'two'),它就有效! 带注释的数据库中的字段角色(DC2Type:array)

然后,我使用以下代码创建了AddRolesFieldSubscriber

public static function getSubscribedEvents()
{
    // Tells the dispatcher that we want to listen on the form.pre_set_data
    // event and that the preSetData method should be called.
    return array(FormEvents::PRE_SET_DATA => 'preSetData');
}

public function preSetData(DataEvent $event)
{
    $data = $event->getData();
    $form = $event->getForm();


    // During form creation setData() is called with null as an argument
    // by the FormBuilder constructor. We're only concerned with when
    // setData is called with an actual Entity object in it (whether new,
    // or fetched with Doctrine). This if statement let's us skip right
    // over the null condition.
    if (null === $data) {
        return;
    }

        $form->add($this->factory->createNamed('roles', 'choice', array(
                'choices'   => $data->getRoles(),
                'empty_value' => false,
                'multiple' => true,
                'expanded' => true,
                'required'  => false,
        )));
}

并更改GroupFormType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);

    $subscriber = new AddRolesFieldSubscriber($builder->getFormFactory());
    $builder->addEventSubscriber($subscriber);
}

但我有一个例外:

  

注意:xxx \ vendor \ symfony \ symfony \ src \ Symfony \ Component \ Form \ Extension \ Core \ ChoiceList \ ChoiceList.php第457行中的数组到字符串转换   500内部服务器错误 - ErrorException

1 个答案:

答案 0 :(得分:1)

问题来自您的createNamed()电话。这里的第三个选项是 not options数组,但是字段的初始值。