Getting AbstractType from request

477 views Asked by At

The user sumbits a form that was build using the symfony 2 framework with abstract type:

<?php
$form = $this->createForm(new MyAbstractType(), new MyEntity());

I receive this post request in an action:

public function receiveFormRequestAction(Request $request){
    //How do I get the abstract type from the request?
}

I need to be able to create the AbstractType used on the form using only information in the request.

  1. Is it possible?
  2. How do you do it?

Thanks.

Edit:

Sorry if i wasn't clear enough. in the method "recieveFormRequestAction" i don't know what abstract type i am going to get, so i cant bind the form directly to MyAbstractType.

This action can, in theory, recieve any AbastractType and bind it.

3

There are 3 answers

0
JavierIEH On BEST ANSWER

I ended up doing this:

  1. The method getName() on my forms returned exactly the same name as the Form class name

    Class MyAbstractType extends AbstractType
      [...]
      public function getName(){
        return "MyAbstractType";
    }
    
  2. Now i can get the type using the hash on the parameter keys

    public function myAction(Request $request){
    $parameterKeys = $request->request->keys();
    $formName = $parameterKeys[0];
    

Ugly as hell, but i needed a quick solution. Until there is a cleaner one, i'm accepting this.

0
greg0ire On
  1. Yes

  2. Like this:

    // first, create the very same form
    $form = $this->createForm(new MyAbstractType(), new MyEntity());
    // bind the form with your request
    $form->bind($request);
    // Optional step : validate the form
    if ($form->isValid()) {
        // your object is ready, get it like this:
        $object = $form->getData();
    } else {
         // handle the validation errors.
    }
    
0
noetix On

You need to bind the Request object to the form.

$form->bind($request);

Then you can run things like $form->isValid() and $form->getData().