passing data from controller to Type symfony2

后端 未结 2 1315
一生所求
一生所求 2020-11-29 03:17

if i show a field of type \"entity\" in my form, and i want to filter this entity type based on a argument I pass from the controller, how do i do that.. ?

/         


        
相关标签:
2条回答
  • 2020-11-29 03:29

    You can pass parameters to the form class as follows:

    //PlumeOptionsType.php
    protected $profile;
    
    public function __construct (Profile $profile)
    {
        $this->profile = $profile;
    }
    

    Then use it in the query_builder of your buildForm:

    $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)
                                ;
                            },
    
    ));
    

    And finally in your controller:

    // fetch $profile from DB
    $form = $this->createForm(new PlumeOptionsType($profile), $plumeOptions);
    
    0 讨论(0)
  • 2020-11-29 03:46

    You can use $plumeOptions to pass everything your argument, but you'll need to add a getDefaultOptions() in PlumeOptionsType to specify the default value for your option. See for instance https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/Type/CheckboxType.php to see what this method should look like.

    0 讨论(0)
提交回复
热议问题