Question

I added a UniqueEntity constraint to my entity following the documentation. The constraint is working fine, I get the default error message:

This value is already used.

When I replace the message with a translation key like unique_entity.message and add this key in the validators.en.yml (I successfully added other asserts translations to that file), the error message is the translation key itself instead of the translated message.

I tried clearing the cache, it didn't work. I tried checking the source code of the constraints files, but I am lost in the many files, from what I could find, it should work.

Anyone know what I'm doing wrong?

Was it helpful?

Solution

I found the reason, I was using a function get get the list of errors to encode them in json to use with an ajax form, this is the function:

private function getFormErrorMessages(Form $form)
{
    $errors = array();

    foreach ($form->getErrors() as $key => $error) {
        $template = $error->getMessageTemplate();
        $parameters = $error->getMessageParameters();

        $error = $template;

        foreach ($parameters as $var => $value) {
            $error = str_replace($var, $value, $template);
        }

        $errors[] = array(
            'error' => $error,
            'template' => $template,
            'parameters' => $parameters,
        );
    }

    if ($form->count()) {
        foreach ($form as $child) {
            if (!$child->isValid()) {
                $errors = array_merge($errors, $this->getFormErrorMessages($child));
            }
        }
    }

    return $errors;
}

Well, it happens that this function gets the translated normal errors (from Asserts), but not the UniqueEntity ones. Which appears to be translated during the view creation, maybe.

So instead of getting the list of errors, I just returned the new rendered form containing the errors in json and replaced the old one with it and all the errors are translated like they should.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top