2

我想在 table 中创建一个带有角色的复选框列表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

4

1 回答 1

1

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

于 2013-02-10T15:18:30.180 回答