3

I'm designing REST API with Symfony2.

For POST and PUT request i'm using a FormType. Something like :

class EmailType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('subject', 'textarea')
        [...]
        ;
    }

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

But when I POST, i'm must pass fields with a namespace like :

{
    "email": {
        "subject": "subject"
    }
}

But I don't want this top-level namespace !

Any ideas ?

2 Answers 2

7

A form type has to have a name because if you register it as a service tagged as a form type, you need to somehow reference it. In the following code snippet, email is the name of the form type:

$form = $this->formFactory->create('email', $email);

That's why you have to return a name in the form type class:

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

So, instead of creating a form type without a name, just create a form — a particular instance of that form type — with an empty name:

$form = $this->formFactory->createNamed(null, 'email', $email);

An empty string — '' — instead of null works as well.

Sign up to request clarification or add additional context in comments.

4 Comments

I know you didn't like the approach I suggested above. Could you add some detail in your answer about how this is a better way of dealing with this issue. Thanks.
@StuBez I think it is worth changing this to the answer, as it is the better solution to attack this problem.
@Dan I can't see any way to change the accepted answer but you could try contacting the person who asked the question.
Totally meant to call out to @Gilles
-3

I've used Symfony forms for JSON based APIs. You just need to change your getName() method to return '':

public function getName()
{
    return '';
}

This, cobined with the FOSRestBundle, made working with POSTed data very easy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.