如何以Symfony形式在单个GET参数中传递所有表单数据

时间:2017-12-04 01:24:47

标签: php forms symfony

我正在构建Symfony表单:

    $builder
        ->add('myEntity', EntityType::class, [
            'class' => MyEntity::class
        ])
        ->add('anotherEntity', EntityType::class, [
            'class' => AnotherEntity::class
        ])
    ;

当我提交此表单时,其所有参数都作为单独的GET参数传递

http://my.url/?myEntity=foo&anotherEntity=bar

我想将它们放在一个数组变量中

http://my.url/?singleVar[myEntity]=foo&singleVar[anotherEntity]=bar

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以将所有名称的名称更改为myArray[],然后您就可以使用myArray[0] .. [1]等来访问它们了。

答案 1 :(得分:0)

创建一个包含两个实体的模型,然后只需为其创建表单:

的appbundle \型号\ MyModel.php:

<?php

namespace AppBundle\Model;

use AppBundle\Entity\MyEntity;
use AppBundle\Entity\AnotherEntity;

class MyModel
{
    private $myEntity;
    private $anotherEntity;

    public function getMyEntity()
    {
        return $this->myEntity;
    }

    public function setMyEntity(MyEntity $entity)
    {
        $this->myEntity = $entity;

        return $this;
    }

    public function getAnotherEntity()
    {
        return $this->anotherEntity;
    }

    public function setAnotherEntity(AnotherEntity $entity)
    {
        $this->anotherEntity = $entity;

        return $this;
    }
}

的appbundle \表格\ MyModelType.php:

<?php

namespace AppBundle\Form;

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

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

use AppBundle\Model\MyModel;
use AppBundle\Entity\MyEntity;
use AppBundle\Entity\AnotherEntity;

class MyModelType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('myEntity', EntityType::class, [
                    'class' => MyEntity::class
            ])
            ->add('anotherEntity', EntityType::class, [
                    'class' => AnotherEntity::class
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => MyModel::class
        ]);
    }
}

在你的控制器和行动中:

<?php

use AppBundle\Model\MyModel;
use AppBundle\Entity\MyEntity;
use AppBundle\Entity\AnotherEntity;

use AppBundle\Form\MyModelType;

// In your action:

$model = new MyModel();

$form = $this->createForm(new MyModelType(), $model, ['method' => 'GET']);

$form->handleRequest($request);

if ($form->isValid())
{
    // $model->getMyEntity() and $model->getAnotherEntity() contain the set entities.
}

这是干编码的,因此可能存在拼写错误,但你应该明白这一点。