Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize DataTransformer error message in Symfony?

My simple data transformer transforms a number to an entity and vice-versa. It's pretty like the example in the official documentation.

The reverseTransform method converts a number to an entity and when it fails it throws a TransformationFailedException with a descriptive message:

public function reverseTransform($number)
{
    if (!$number) {
        return null;
    }

    $issue = $this->om
        ->getRepository('AcmeTaskBundle:Issue')
        ->findOneBy(array('number' => $number))
    ;

    if (null === $issue) {
        throw new TransformationFailedException(sprintf(
            'An issue with number "%s" does not exist!',
            $number
        ));
    }

    return $issue;
}

However the form field using the above transformer gets a generic error message "This value is not valid". Even changing the exception text (that I would expect to be used as validation message, but it's not...) doesn't change the error message.

How can I display the exception text instead of "This value is not valid"?

like image 695
gremo Avatar asked Nov 03 '13 15:11

gremo


1 Answers

In no way, because symfony catch this exception and set own message (field incorrect). If your want customize this message, you must set validator to this field.

Maybe I'm wrong, but did not find anything.

For example:

public function reverseTransform($number)
{
    if (!$number) {
        return null;
    }

    $issue = $this->om
        ->getRepository('AcmeTaskBundle:Issue')
        ->findOneBy(array('number' => $number))
    ;

    if (null === $issue) {
        // Nothig action
        //throw new TransformationFailedException(sprintf(
        //    'An issue with number "%s" does not exist!',
        //    $number
        //));
    }

    return $issue;
}

And add NotBlank/NotNull validator to field.

UPD

And you can set the parameter "invalid_message" in form type.

For example:

$builder
  ->add('you_field', 'text', array('invalid_message' => 'An issue number not found'))
  ->get('you_field')->addModelTransformer('....');
like image 136
ZhukV Avatar answered Oct 14 '22 04:10

ZhukV