将数据从控制器传递到类型symfony2

xeo*_*eon 25 symfony

如果我在我的表单中显示"实体"类型的字段,并且我想根据从控制器传递的参数过滤此实体类型,我该怎么做...?

//PlumeOptionsType.php
public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('framePlume', 'entity', array(
        'class' => 'DessinPlumeBundle:PhysicalPlume',
        'query_builder' => function(EntityRepository $er) {
                                return $er->createQueryBuilder('pp')
                                    ->where("pp.profile = :profile")
                                    ->orderBy('pp.index', 'ASC')
                                    ->setParameter('profile', ????)
                                ;
                            },

    ));
}

public function getName()
{
    return 'plumeOptions';
}

public function getDefaultOptions(array $options)
{
    return array(
            'data_class'      => 'Dessin\PlumeBundle\Entity\PlumeOptions',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'plumeOptions_item',
    );
}
}
Run Code Online (Sandbox Code Playgroud)

在控制器内部,我创建表单:

i have that argument that i need to pass in my action code:
$profile_id = $this->getRequest()->getSession()->get('profile_id');
...
and then i create my form like this
$form = $this->createForm(new PlumeOptionsType(), $plumeOptions);
Run Code Online (Sandbox Code Playgroud)

$ plumeOptions只是一个要坚持的类.但它与另一个名为PhysicalPlume的类有一对一的关系.现在,当我想在我的代码中显示'framePlume'时,我想显示一个过滤的PhysicalPlume实体.

Lou*_*une 40

您可以将参数传递给表单类,如下所示:

//PlumeOptionsType.php
protected $profile;

public function __construct (Profile $profile)
{
    $this->profile = $profile;
}
Run Code Online (Sandbox Code Playgroud)

然后在buildForm的query_builder中使用它:

$profile = $this->profile;

$builder->add('framePlume', 'entity', array(
    'class' => 'DessinPlumeBundle:PhysicalPlume',
    'query_builder' => function(EntityRepository $er) use ($profile) {
                            return $er->createQueryBuilder('pp')
                                ->where("pp.profile = :profile")
                                ->orderBy('pp.index', 'ASC')
                                ->setParameter('profile', $profile)
                            ;
                        },

));
Run Code Online (Sandbox Code Playgroud)

最后在你的控制器中:

// fetch $profile from DB
$form = $this->createForm(new PlumeOptionsType($profile), $plumeOptions);
Run Code Online (Sandbox Code Playgroud)

  • 传递表单类型现已弃用:http://stackoverflow.com/questions/34027711/passing-data-to-buildform-in-symfony-2-8-3-0 (6认同)