Getting user input data in FormEvents::SUBMIT

2019-08-18 02:45发布

问题:

I am looking for a way to get user data in the formEvents::SUBMIT event.

I can get it in formEvents::PRE_SUBMIT using

$builder->addEventListener(FormEvents::PRE_SUBMIT, function() {
    //...
    $userInput = $event->getData());
    //...
});

I can get it in formEvents::POST_SUBMIT using

$builder->addEventListener(FormEvents::POST_SUBMIT, function() {
    //...
    $userInput = $event->getForm()->getViewData()
    //...
});

But in formEvents::SUBMIT I cannot find where, though I read it can be accessed: Symfony2: dynamic generation of embedded form

I can find other project getting data using the same method as PRE_SUBMIT, for instance here: https://github.com/Klerik/web-dersen/blob/65ba1bafa574dc2bda6dd2bb738fe0d33a06bf71/src/Catalog/FilmsBundle/Form/EventListener/UploadFileSubscriber.php

or there: https://github.com/alexandresalome/bros/blob/59c111eb481c2fd672f3646390455ddad65dd800/src/Bros/ServerBundle/Form/Type/BrowserType.php

Though in my situation I test with user input that does not fit the Normalisation - $event->getForm()['field']->getData() sends an object without the user data which have been refused. Still I want to retrieve user input to: * change accordingly (testing data validity) my current form (which cannot be done in POST_SUBMIT), * use my form related object (not available in PRE_SUBMIT)

EDIT

Here are the relevant parts of the ...Type Class :

public function buildForm(FormBuilderInterface $builder, Array $options)
{
    $adminUserQuery = $options['admin_user_query'];

    $builder
        ->add('admin_user', 'model', Array( //using Propel as ORM
            'label' => FALSE,
            'multiple' => FALSE,
            'expanded' => FALSE,
            'class' => 'App\\CoreBundle\\Model\\AdminUser',
            'query' => $adminUserQuery,
            'empty_value' => 'form.placeholder.admin_user',
            'property' => 'email',
        ));
    //...

    $builder->addEventListener(
        FormEvents::PRE_SUBMIT, function (FormEvent $formEvent)
    {
        var_dump($formEvent->getData(), '---'); // prints: array(1) { ["admin_user"]=> string(17) "test@email.test" }
        var_dump($formEvent->getData()['admin_user'], '---'); // prints: string(15) "test@email.test"
        //...
    });

    $builder->addEventListener(
        FormEvents::SUBMIT, function (FormEvent $formEvent)
    {
        var_dump($formEvent->getData()); // prints: object(App\CoreBundle\Model\EventUserRole)#1659 {...}
        var_dump($formEvent->getData()->getAdminUser()); // prints: NULL

        //...
    }
    );
}

Anyone ?

回答1:

In the FormEvents::Submit action, you can do this (assuming you are editing a User):

$builder->addEventListener(FormEvents::SUBMIT, function ($event) {
    // Your Entity/Document
    $user = $event->getData();

    // Grab the actual form
    $form = $event->getForm();

    // ...
});