How to customize/localize Assert messages in Symfony2? - symfony

When you use #Assert\NotBlank constraint and the given field is empty, then you get the error:
This value should not be blank
I would like to change this message application-wide, without changing Symfony2 source code. How to accomplish that?

Cutomizing validation error messages is quite simple, but can seem tricky at first.
Default locale
First of all you should change the default locale of your application. In versions 2.0.x the correct value to change is framework.session.default_locale. For future reference, starting from 2.1.0 it'll be framework.default_locale. Consult the docs for correct syntax.
A locale should consist of your language and region and is defined as language_REGION (list of languages, list of countries). The locale used in Germany for german would be de_DE for example.
Validation messages
Validation messages are hard coded in their respective constraint classes.
Translating validation messages
Symfony uses Twig to render all the validation messages. The process itself is complicated and falls out of the scope of this question, but the important part is that each constraint message is sent through a translation filter, which depending on the user's locale (default_locale by default) translates the messages to the proper language.
To change any of the translations, simply copy the validation translation file from vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/translations/validators.{lang}.xlf to app/Resources/translations/validators.{lang}.xlf where {lang} is the language part of your default locale.
Having done the former, simply change the default messages to what ever you see more fit. If the language you need support for doesn't exist, copy any translation file to the same directory and modify that file instead.
To read more about how translation works in Symfony2, visit the official documentation on translation.

Additionally to the instructions by gilden, you have to make sure the framework.translator block in config/config.yml is uncommented (it's commented by default nowadays). If you don't do that, you'll still end up with the original English messages.

If anyone has doubts in 2021, here's all I had to do to switch "Error" (eng) constraint message to "Erreur" (fr):
Go to your config/packages/translation.yaml file
Edit it by replacing "en" to "fr" (or your language) :
Test it on your localhost :
Note :
here is the Symfony 5.2 doc I used to help me out
All I did was set a Default_locale (!! not detect where the user comes from !!)

Related

Symfony2 translation returns only english

I am trying to get along with translation service in symfony2. The problem I am facing is that this code always returns the english version of the key
$translator = $this->get('translator');
$translator->setlocale('fr'); // locale gets ignored
die($translator->trans('pisica')); //always outputs cat altough the translation in french exists too.
I would like to specify in controller witch locale I am using because it is best for what I am trying to acomplish
Set the Locale in the Request object, not in the translator service.
$request->setLocale('fr');
$translator->trans('something');

Symfony2, create a fake UploadedFile for functional test

I have a REST api written in Symfony2 with an API call to upload a file.
This file can't be more than 40MB and must respect some format.
I would like to know how I can create a fake UploadedFile
according to Symfony2 documentation , it seems possible to precise the mime type, size and name , and even a mysterious "test" parameters (which i first thought was to be put as true when one want to tell Symfony it's a fake one) but it does not work (it wants a valid file path)
So how does people do, as in my case I can't put a 50mo file in my repository just for the sake of one functional test.

Translated Symfony routes with multiple parameters

As the title suggests, I'm using Symfony in conjunction with the JMSTranslationBundle and JMSI18nBundle in order to serve translated routes.
Here's my currently configured route:
/{location}/{profession}/{specialty}
So the route
/berlin/arzt/allgemein
is successfully pushed to the correct controller and action.
The JMSI18nBundle is automagically prefixing my English routes with /en/. This works for every other route with a non-dynamic component (such as /profile/{slug}/). This DOES NOT work, however, when using the English version of the above example. i.e.
/en/berlin/doctor/general
I'm guessing the router is not reading this properly as the English version of the normal route, and instead tries to assign location = en, profession = berlin, etc, which is obviously incorrect.
I've tried defining optional parameters, more complicated regexes, and trailing slashes for the translation (all with cache flushes in between). None of this works. What DOES work, is inserting a pointless non-dynamic component, i.e. /en/s/berlin/doctor/general etc
As a part of the business requirements, we don't want this additional pointless non-dynamic URL component.
So, my question is: how can I use (prefixed) translatable URLs in Symfony that contain nothing but dynamic fields?
Your help is greatly appreciated!
Solved:
As is the norm with Friday-afternoon problems, I found I had a $ inside my translated route rule, like so:
/{location}/{$profession}/{specialty}
Removing it and flushing the cache resulted in the route working.
tl;dr - PEBKAC

spring form error tag: check for specific error (only display invalid if the not null is not present for example)

So I have a String I need to check for a valid format for which I used a pattern, and whether the entered value is valid according to some business rules for which I used a custom validator. Now the customer would prefer it if the error message associated with the latter is only shown if the former didn't occur. But as far as I know there is no way to make this distinction.
Or can anyone think of a way to do this?
The trick is: have two different constraints (annotations),
one for the pattern, that accept null,
and a second for not null.
By default the javax.validation.constraints.Pattern "validator" accept null.
Accepts String. null elements are considered valid.
(javax.validation.constraints.Pattern javadoc)
So what you need to do in the end is this:
#NotNull(message="{validation.notNull}")
#Pattern(pattern="123" message="{validation.notPattern}")
String myString;
Added:
(Comment)
Not really the desired behaviour since I want to reuse the bean object but the conditions aren't the same for each page. – Jack Nickels 5 mins ago
In this case you can use the so called groups (See JSR303 Bean Validation Spec, Chapter 4.1.2 groups -- there is also an example). Use the default Group for #Pattern and an other group for #NotNull. Now you can enable or disable the Validation rules according the groups you specify for validation.
validator.validate(myObject, Default.class);
validator.validate(myObject, MyGroup.class);
There is one problem left: in Spring 3.0 you can not Specify the Group you want to use for the automatic validation process. But in 3.1 you can, according to that Feature Request SPR-6373 (I have not tryed it, but I hope it works)

Is there a way to restrict file types on a file field, using AGX tagged values?

Using argo uml and archgenxml, I have a file field. I would like to restrict it to one extension: .ttf
Can I do this using a tagged value?
Also is there a glossary for the AGXProfile which would answer this?
You could try the allowable_content_types mime type property of FileField|ImageFields but I can't find anything that indicates that validation is done on that property. IOW, this wouldn't show the user an error if they uploaded something else. If you want that, you're going to have to write an AT field validator yourself that takes the file and validates it against the mimetype_registry.

Resources