0

以下のように、ユーザー ロール コレクションのドロップ ダウン メニューを 1 つ作成します。

  class UserType extends AbstractType
    {
        public function buildForm(FormBuilder $builder, array $options)
        {
            $builder
                ->add('userRoles',null, array('multiple'=>false))
            ;
        }

しかし、次のエラー メッセージが表示されます。

Expected an object, but got a collection. Did you forget to pass
"multiple=true" to an entity field?

コレクションを複数選択できないようにする方法はありますか!?

4

1 に答える 1

2

"multiple" を false に設定した場合、使用しているフィールド タイプ ("entity") は単純なオブジェクトを入力として想定します。あなたの目的のために、CallbackTransformer を使用してコレクションとオブジェクトの間で変換することができます。

$builder->add(
    $builder->create('userRoles', null, array('multiple' => false))
        ->addModelTransformer(new CallbackTransformer(
            // transform the collection to its first element
            function (Collection $coll) { return $coll[0]; },
            // transform the element to a collection
            function (MyEntity $entity) { return new ArrayCollection(array($entity)); }
        ))
);

最新の Symfony2 マスターを使用しない場合は、prependNormTransformer()代わりに非推奨の方法を使用する必要がありaddModelTransformer()ます。

于 2012-05-26T08:12:49.847 に答える