Symfony2 -- Creating a form that use's differents entities

时间:2016-04-21 22:07:00

标签: php symfony

I've been using Symfony a bit and i'm trying to figure out a way to create a form. I need to use a MVC based solution.

My form needs to ask several information of different Entities and then i need to process that information extracting it in the database. The database wont be a problem.

I was just figuring out how do i make a form with different types of entities ?

And how do i make a scrolldown menu with the data contained in the database for an entity ?

2 个答案:

答案 0 :(得分:0)

如果@chalasr的评论不适用,即实体不相关,则可以在控制器中执行以下操作。只需为每个实体{x}类型表单创建一个$ form变量,如下所示:

$formA = $this->createForm(AppBundle\Entity\EntityAType($entityA));
$formB = $this->createForm(AppBundle\Entity\EntityBType($entityB));
...

return array(
    'formA' => $formA->createView(),
    'formB' => $formB->createView(),
    ...
);

答案 1 :(得分:0)

你可以简单地组合表格,同时保持每个单独的

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ReallyBigFormType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('foo', FooType::class, [
                // label, required, ... as well as options of FooType
            ])
            ->add('bar', BarType::class, [
                // label, required, ... as well as options of BarType
            ])
        ;

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([]);
    }

}

并将FooTypeBarType定义为常规表格

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType

class FooType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'foo.name',
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'AppBundle\Entity\Foo',
        ]);
    }

}