使用formtype编辑对象

时间:2018-06-08 16:39:00

标签: symfony

我正在尝试使用formtype来编辑我的一个对象。 formtype在创建新对象时完美运行,但是当我尝试将现有实体加载到表单中时,我得到以下异常:

必须管理传递给选择字段的“Proxies__CG __ \ App \ Entity \ Language”类型的实体。也许你忘了把它留在实体经理那里?

放入表单的对象是从数据库加载的,因此它已经100%持久存在。

以下是类型:

UNITTYPE

class UnitType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('unitTranslations', CollectionType::class, [
                'entry_type' => UnitTranslationType::class,
                'entry_options' => array('label' => false),
                'allow_add'    => true,
                'allow_delete' => true,
                'prototype'    => true,
                'by_reference' => false,
                'delete_empty' => true,
                'attr' => [
                    'class' => 'UnitTranslationSelector',
                ],
            ])
            ->add('save', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Unit::class
        ));
    }
}

UnitTranslationType

class UnitTranslationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('name', TextType::class, [
                'label' => 'Unit',
                'by_reference' => false
            ])
            ->add('language', EntityType::class, [
                'class' => Language::class,
                'choice_label' => 'name',
                'placeholder' => 'Choose an option',
                'by_reference' => false
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => UnitTranslation::class,
        ));
    }
}

和控制器:

public function createUnit(Request $request, EntityManagerInterface $entityManager)
    {
        $unit = new Unit();

        $unit = $entityManager->getRepository(Unit::class)->find(2);
        dump($unit);

        $form = $this->createForm(UnitType::class, $unit);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            foreach ($unit->getUnitTranslations() as $translation) {
                $translation->setUnit($unit);
            }

            $entityManager->persist($unit);
            $entityManager->flush();

            return $this->redirectToRoute("recipe_list");
        }
        return $this->render('createUnit.html.twig', array('form' => $form->createView()));

    }

1 个答案:

答案 0 :(得分:0)

我知道这个问题很旧,但是我只是通过使用CollectionType而不是EntityType(针对您所用的语言实体)解决了同样的问题。我不确定您的实体的设置方式,但是CollectionType需要在UnitTranslation实体和Language实体之间建立OneToMany或ManyToMany关系。可以在here中找到CollectionType的说明,并在there中找到如何嵌入表单集合。