Ajouve
Ajouve

Reputation: 10089

Symfony2 DataTransformer after handleRequest

I have an API and I am sending a reference of an entity, I'm using a DataTransformer to get my entity but the DataTransformer is always called before the $form->handleRequest($request) the value is always null and it could't works

My Controller

public function newAction(Request $request)
    {
        $orderNewFormType = $this->get('competitive_bo.api_bundle.form.type.order_new');
        $card = new Card();

        try {
            $form = $this->createForm($orderNewFormType, $card);
            $form->handleRequest($request);
        } catch (TransformationFailedException $e) {
            return $this->notFoundErrorResponse(
                'Business not found'
            );
        }

        if ($form->isValid()) {
            return $this->okResponse(array());
        }

        $validatorErrorFormatter = $this->get('competitive_bo.api_bundle.formatter.validator_error');
        $errors = $validatorErrorFormatter->formatFromFormError($form->getErrors(true));

        return $this->badRequestErrorResponse(
            'Invalid data',
            $errors
        );
    }

The form type

class OrderNewFormType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('customer', 'entity', array(
                'class' => 'CompetitiveBOBusinessBundle:Customer',
                'property' => 'id'
            ))
            ->add('business', 'business', array(
                'mapped' => false,
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection'   => false,
            'data_class'        => Card::class
        ));
    }

    public function getName()
    {
        return null;
    }
}

The Business form type

class BusinessReferenceFormType extends AbstractType
{
    /**
     * @var ReferenceToBusinessTransformer
     */
    private $referenceToBusinessTransformer;

    public function __construct(ReferenceToBusinessTransformer $referenceToBusinessTransformer)
    {
        $this->referenceToBusinessTransformer = $referenceToBusinessTransformer;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addViewTransformer($this->referenceToBusinessTransformer);
    }

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

    public function getParent()
    {
        return 'text';
    }
}

And the DataTransformer

/**
 * Class ReferenceToBusinessTransformer
 */
class ReferenceToBusinessTransformer implements DataTransformerInterface
{
    /**
     * @var BusinessRepository
     */
    private $businessRepository;

    public function __construct(BusinessRepository $businessRepository)
    {

        $this->businessRepository = $businessRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function transform($reference)
    {
        var_dump($reference);
        $business = $this->businessRepository->findOneBy(array(
            'reference' => $reference
        ));

        if (null === $business) {
            throw new TransformationFailedException;
        }

        return $business;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!($value instanceof Business)) {
            throw new TransformationFailedException;
        }

        return $value->getReference();
    }
}

The var_dump($reference) is always null

And I have my test

public function testNewAction($getParams, $postParam, $responseCode)
    {
        $client = static::createClient();

        $router = $client->getContainer()->get('router');
        $route = $router->generate('competitivebo_api_order_new',$getParams);

        $client->request('POST', $route, $postParam);
        $response = $client->getResponse();

        $this->assertJsonResponse($response, $responseCode);
    }

With the post params

'customer' => 1,
'business' => LoadBusinessData::REFERENCE_1,
'name' => 'Test',

The exception TransformationFailedException is always thrown during the $this->createForm(...) so the request is not handled

Upvotes: 1

Views: 137

Answers (1)

Federkun
Federkun

Reputation: 36964

According with the documentation,

When null is passed to the transform() method, your transformer should return an equivalent value of the type it is transforming to (e.g. an empty string, 0 for integers or 0.0 for floats).

Upvotes: 2

Related Questions