6

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"?

gremo
  • 47,186
  • 75
  • 257
  • 421

1 Answers1

5

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('....');
ZhukV
  • 2,892
  • 6
  • 25
  • 36
  • First, thanks. You method should work and at least provides some good user feedback about what's happening. Maybe there is a "standard" way to do this, I'll way for a better way (if any) or accept your answer. – gremo Nov 03 '13 at 19:10
  • I can not find another methods for customize this message, but only symfony form catch this exception, and not events for control. https://github.com/symfony/Form/blob/master/Form.php#L612 So, as solution, you can use POST_SUBMIT and control synchronized property, but i have not tried – ZhukV Nov 04 '13 at 05:54
  • The exception is meant for debug only, not to be exposed, the answer provided is the way to go. Otherwise one should use one of the submit listener and use `$form->addError(new FormError('my message'))` on the proper field with the proper message. It will cause the root to be invalid anyway with the good mapping and the good message. – Heah Nov 16 '16 at 12:04