Search code examples
phpsymfonyfosrestbundlejmsserializerbundlesymfony-3.2

Symfony 3.2 binding post values to form in REST api


I use following libraries/technologies:

JMSSerializer, FOSRestBundle + Symfony 3.2 + PHP 7.1

When I try to make POST request to my POST endpoint I can't get form to work.

Files:

Country.php -> POPO Entity

CountryType.php

<?php

declare(strict_types = 1);
namespace AppBundle\Form;

use AppBundle\Model\Entity\Country;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CountryType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name' , TextType::class)
            ->add('iso_alpha_2_code', TextType::class)
            ->add('iso_alpha_3_code', TextType::class)
            ->add('is_numeric_code', IntegerType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Country::class,
            'csrf_protection' => false,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getName() : string
    {
        return '';
    }
}

CountryController.php postAction

public function postAction(Request $request)
    {
        $country = new Country();
        $form = $this->createForm(CountryType::class,  $country);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            die('ok');
            // TODO INSERT DATA then redirect
            return $this->routeRedirectView('get_country', ['id' => $country->getId()]);
        }

        return $this->get('fos_rest.view_handler')->handle(View::create($form));
    }

The problem is that it doesn't enter if block because both isSubmited() and isValid() methods return false. When I call $form->getData() it returns

CountryController.php on line 40: Country {#306 -id: null -name: null -isoAlpha2Code: null -isoAlpha3Code: null -isNumericCode: null }

The request I make:

Request to API

Could you give me a tip what I do wrong?


Solution

  • This is how I do form submission when using FOSRest bundle, I hope this will put you in right direction. This is an example registration action. You will notice that you have to submit the form manually

    $form->submit($request->request->all()); and then check if it is valid or not

    public function postRegistrationAction(Request $request){
        $form = $this->createForm(UserType::class, null, [
            'csrf_protection' => false,
        ]);
        $form->submit($request->request->all());
        if (!$form->isValid()) {
            return $form;
        }
        /**
         * @var $user User
         */
        $user = $form->getData();
        $em = $this->getDoctrine()->getManager();
    
        //Set the user role
        $user->setRoles(array('ROLE_USER'));
    
        //Encode the password
        $password = $request->request->get('password');
        $encodedPassword = $this->get('security.password_encoder')->encodePassword($user, $password['first']);
        $user->setPassword($encodedPassword);
    
        $token = $this->get('lexik_jwt_authentication.encoder')->encode(['username' => $user->getUsername(), 'role' => $user->getRoles(), 'name' => $user->getName()]);
    
        $em->persist($user);
        $em->flush();
        $view = FOSView::create();
        $view
            ->setData(['token' => $token])
            ->setStatusCode(200);
        return $view;
    }