2

table にロールを含むチェックボックス リストを作成したいのですがGroup、1 つのチェックボックスがロールです。コードのオーバーライドがあります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()電話から来ています。ここでの 3 番目のオプションはオプション配列ではなく、フィールドの初期値です。

于 2013-02-10T15:18:30.180 に答える