繁体   English   中英

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

[英]How to pass all form data in single GET parameter in Symfony form

我正在构建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

我怎样才能做到这一点?

您可以将所有名称更改为myArray[] ,然后可以使用myArray[0] .. [1] .. etc访问它们

创建一个包含两个实体的模型,并为此简单地创建表单:

AppBundle \\ Model \\ 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 \\ Form \\ 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.
}

这是干式编码的,因此可能在这里和那里都有错别字,但是您应该明白这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM