How to pass parameter to FormType constructor from

2020-02-08 05:48发布

问题:

In Symfony2.7 i was able to pass parameter to Form Type constructor directly from controller while creating the form, however in Symfony3 i'm not able to do it!

Before in Symfony2.7

$form = $this->createForm(new NewsType("posted_by_name"));

After in Symfony3

$form = $this->createForm(NewsType::class); // no idea how to pass parameter?

Update: I also wanted to access it from:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    // how to access posted_by_name here which is sent from controller
}

Any help will be highly appreciated..

回答1:

Thanks for your time! i resolved this myself:

I removed parameter from NewsType constructor and added data to postedBy form field using $options array, and passed data to $options array from controller, please check following:

NewsType

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('postedBy', HiddenType::class, array(
            'data' => $options['postedBy']
            )
        )
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'postedBy' => null,
    ));
}

Controller

$form = $this->createForm(NewsType::class, $news, array(
    'postedBy' => $this->getUser()->getFullname(),
);

UPDATE: Please use below code if you want to access $options array from addEventListener:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $postedBy = $event->getForm()->getConfig()->getOptions()['postedBy'];
}

Hope it helps somebody! 



回答2:

You need to define your form as service.

namespace AppBundle\Form\Type;

use App\Utility\MyCustomService;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class NewsType extends AbstractType
{
    private $myCustomService;

    private $myStringParameter;

    public function __construct(MyCustomService $service, $stringParameter)
    {
        $this->myCustomService   = $service;
        $this->myStringParameter = $stringParameter;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Your code
    }
}

Add to your service configuration:

#src/AppBundle/Resources/config/services.yml
services:
    app.form.type.task:
        class: AppBundle\Form\Type\NewsType
        arguments:
            - "@app.my_service"
            - "posted_by_name"
        tags:
            - { name: form.type }


回答3:

You are both right.

@Muzafar and @jkucharovic, the question is when to use which...

As Bernard Schussek shows in Symfony Forms 101:

1 Don't pass Dynamic Data to constructor..

2 ... but use Custom Options instead

3 Do pass Global Settings to constructor (or services)