Tool
Tool

Reputation: 12488

Symfony2: how to catch a DataTransformer exception?

I have a datatransformer in symfony 2:

namespace Techforge\ApartmentBundle\Form\DataTransformer;

use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\DataTransformerInterface;
use Doctrine\Common\Persistence\ObjectManager;

class SearchboxToCityTransformer implements DataTransformerInterface {


public function reverseTransform($string)
{
    //...
    if(!$city)
        throw new TransformationFailedException(sprintf('City not found.'));
}
//...

I can't figure out how to catch this exception in my controller.

I thought it was going to be thrown upon a form bind:

$form->bindRequest($request);

But that doesn't appear to be the case (I tested this out, and also tested out other parts in my controller).

Also, I'm pretty sure that I triggered the exception because the field didn't appear in the parameter bag (nothing was returned from the reverseTrasnform() function.)

Anyone has any ideas?

Upvotes: 0

Views: 1371

Answers (2)

Bernhard Schussek
Bernhard Schussek

Reputation: 4841

TransformationFailedExceptions will result in an invalid field in the form. If you want the exception to bubble up higher, throw a different exception.

Upvotes: 3

Cerad
Cerad

Reputation: 48865

The short answer is: you don't.

Take a look at Symfony\Component\Form\Form::bind()

    try {
        // Normalize data to unified representation
        $normData = $this->clientToNorm($clientData);
        $synchronized = true;
    } catch (TransformationFailedException $e) {
    }

So TransformationFailedException are silently ignored. The behaviors is a bit puzzling but more than likely you are trying to do validation inside of a transformer which is not what transformers were intended for.

Move the error checking code code to a validator and things should fall into place.

Upvotes: 3

Related Questions