Custom Symfony2 Validator Constraint Messages - validation

I want to use custom error messages for validation constraints on dozens of fields in my project.
I do not want to set the message on every one of these, because that would be a blatant violation of DRY. Repeating the same string in every declaration like: #NotNull(message="custom msg") would mean that if I decide to change the message in the future I'd have to hunt them all down replace them, but even worse I might use the wrong string on some of them and be inconsistent.
How do you deal with this?
Is the best option really to extend every symfony stock constraint and set my default there, and use my own custom annotation class?
Please note that using the translator is not an option for me, so I am looking for a solution that does not include the symfony translation component.
Thanks a lot for the help in advance.

Assuming you are working with English as the app's language, and you've configured translator: { fallback: en }, you can override these constraint messages universally. Start by creating this file: app/Resources/translations/validators.en.yml
And use the following translation format:
This value should not be blank.: Your custom message here
Whatever the standard message is.: Another custom message
This also works for any other language setting, assuming you've made a validators.lang.yml for it!
You can also place this file in your bundle directory under Resources/translations, and a few other places.
You can read more about this here!

Related

UI5 - Load proper i18n_xy.properties at onInit and later on manually

We have the requirement, that we shall host an SAPUI5 application inside a java-application's host, which our vendor offered to us by implementing and exposing jxbrowser.
This vendor's java application offers an api, which can be accessed from within our SAPUI5 application.
This java api offers also an environment (or config-settings), where, amongst a rich set of settings, also a user language can be obtained.
And this language is neither a sap-logon language param nor is it guaranteed to be always the language which is set up in the "jx-browser" ( if possible at all, like in all real browsers ), and it uses the standard i18n _xy_AB acronym's naming style.
And I want to load the proper i18n_xy.properties at onInit of my first view and set them in the code.
We do have currently 4 of them ( _de,_it,_fr ), and the fallback is also present.
I am a little idiot, because I found some quick n dirty code, but this was about one month ago and I simply forgot the link and all of that. So now I need to ask( and maybe even for a best practice solution to this...)
So, additionally, another (my personal) requirement is, that, once I retrieve the right i18n file, I want to set it, in a way, that, whenever later on, I would use
info = this.getView().getModel("i18n").getResourceBundle().getText("obfuscated");
I always obtain the right text in the right language.
What I think of, is: Load the proper file ( according to the environment settings from the api ) in onInit, set this i18n as the proper one for the rest of the application's runtime and use a easy name for it, which will then be referred to as, maybe this:
info = this.getView().getModel("i18n_loaded").getResourceBundle().getText("obfuscated");
Is this possible, is this the right way, and , if not, which one is, according to some kind of guidelines, the best practice for this scenario ?
You can pass the parameter in the url:
sap-ui-language=en
Or set the default language in your JavaScript code:
sap.ui.getCore().getConfiguration().setLanguage("en-US");
I was not completely aware, that the determination of the used locale also works the other way around.
Meaning, if the ressource bundle contains e.g. 4 i18's,called i18_en, i18_it, i18_de, i18_fr, and the either the app is set up by
sap.ui.getCore().getConfiguration().setLanguage("en-US");
or the url-param, this not only means, that:
All ui-elements will be translated propery, once the locale's acronym is properly spotted
ALSO this is automatically replaced by the proper spotted ressource file and the translated text is retrieved properly....
info = this.getView().getModel("i18n").getResourceBundle().getText("obfuscated");
I was aware of how this fallback determination of a locale works, but I was not aware that it works also the other way around.
I close my question and i do not care about any rewards.

Bitrix CMS, how to get cached data based on GET parameter in template of standart component?

I'm working with a component bitrix:catalog (which is standard one) and faced an issue. I want to add some extra GET parameters to switch view mode. I think there is no need to rewrite whole component to make such switcher, so I added extra keys in result_modifier in a way similar to:
$this->__component->arResultCacheKeys = array_merge($this->__component->arResultCacheKeys, array('key1', "key2"));
Earlier in the same result_modifier I perform adding those extra keys in $arResult['key1'] etc. They seem to be correctly saved, but only for current inquiry such as ?view=list or view=card, that means only one variable value is saved and it does not react on changing of GET parameter. Is there simple and correct way to make that component to cache and to output data based on GET variable? The only idea which came to my mind is to rewrite component by adding extra parameter and checking of GET, but I think there must more simple and correct solution to make in via template. Human Readable Links are turned on. And I want to have auto-cash being turned on as well. If I turn it off it starts working as planned.
One of possible solutions is to rewrite it cache by SetTemplateCachedData but it still seems to me rough and incorrect way for such simple task.
Bitrix masters please help me to find correct solution, google can't help at the moment.
If you use standard bitrix:catalog component, you may be use standart bitrix:catalog.section. In that component.php used standart component cache.
That means you can describe additional parametr in you custom .parameters.php, and set it in bitrix:catalog.section params.
Standart component cache set cacheId based on arParams.
So you include component should look like this:
$APPLICATION->IncludeComponent(
"bitrix:catalog.section",
"",
array(
"IBLOCK_TYPE" => $arParams["IBLOCK_TYPE"],
"IBLOCK_ID" => $arParams["IBLOCK_ID"],
"ELEMENT_SORT_FIELD" => $arParams["ELEMENT_SORT_FIELD"],
"ELEMENT_SORT_ORDER" => $arParams["ELEMENT_SORT_ORDER"],
....
....
"NEW_ADDITIONAL_GET_PARAMS"=> $_GET['view']
),
$component
);
Of course better way somethink like
"NEW_ADDITIONAL_GET_PARAMS"=> (in_array($_GET['view'],array('list','card'))?$_GET['view']:'list')
But may be you need just set right catalog params: SEF_MODE SEF_FOLDER SEF_URL_TEMPLATES

Symfony translation inside validation won't work

If I try to use translations inside validation like described here
http://inchoo.net/tools-frameworks/symfony2-translating-validator-messages/
I get always
not.blank.username
as output on Error. It seems like symfony didn't find the message-translation. I placed all my translationfiles inside app/ressources/translations and they are named as
messages.de.yml
....
What am I doing wrong? Do I have to place the translationfiles insde each Bundle?
Kind regards
EDIT: Problem ist clear and fixed, but when I try to use "MinLength" I get an strange error:
Attempted to load class "MinLength" from namespace
"Symfony\Component\Validator\Constraints" in /var/www/symfony/webprojekt/vendor/symfony/symfony/src/Symfony/Component/Validator/Mapping/Loader/AbstractLoader.php line 64.
Do you need to "use" it from another namespace?
I already included
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;
AM I missing something?
To translate validation messages you need to create files with the following name structure inside translations folder:
validators.LANG.yml
Also, you can check in your config.yml, inside framework, if exists the translator:
framework:
translator: { fallback: %locale% }
This is required.
The accepted answer applies to using the magical default translation domain for the validator config. You can also override this in config/packages/validator.yaml
framework:
validation:
enable_annotations: true
translation_domain: 'validations'
Then in translations/ make a file validations.LANG.yaml, for example translations/validations.en.yaml. You don't need to do this but sometimes it's better to explicitly set these magical bit and know where they're coming from.

How to set up FubuMVC validation

I'm trying to learn FubuMVC and have gotten stuck on validating my input models.
What I want to accomplish is post-validate-redirect. That is, to redirect to same view and show the errors if the model is invalid. I'm using attributes on my models.
Also, how would I specify my own error messages, i.e localization?
I'm using the latest packages of Fubu from nuget.
My registry looks like this:
IncludeDiagnostics(true);
Applies.ToThisAssembly();
Actions.IncludeClassesSuffixedWithController();
Routes
.HomeIs<HomeController>(x => x.Index())
.IgnoreControllerNamesEntirely()
.IgnoreMethodsNamed("Index")
.IgnoreMethodsNamed("Query")
.IgnoreMethodsNamed("Command")
.IgnoreNamespaceText("Features")
.IgnoreMethodSuffix("Html")
.RootAtAssemblyNamespace()
.ConstrainToHttpMethod(x => x.Method.Name.EndsWith("Command"), "POST")
.ConstrainToHttpMethod(x => x.Method.Name.EndsWith("Query"), "GET");
this.UseSpark();
this.Validation();
HtmlConvention<SampleHtmlConventions>();
Views.TryToAttachWithDefaultConventions();
The FubuMVC.Validation package is really just an example of how to use FubuValidation as we haven't built it out for all of the edge cases. Having said that, let me explain a little bit about how it works so we can see if you can use it, or if you should just handroll your own validation behavior.
The ValidationBehavior uses the IValidationFailureHandler interface to "handle" validation failures. The Notification object built up from FubuValidation is shoved into the IFubuRequest when the behavior fires, and then the handler is called.
The ValidationFailureHandler class is wired up by default for all
validation failures. This delegates to the IValidationFailurePolicy to
determine the strategy to use for a given model type (see my post on
policies for an explanation of how this works).
The Validation extension method has an overload which gives a micro-
dsl for configuring these policies:
this.Validation(x => {
x.Failures....
});
From here you can 1) apply custom policies via the ApplyPolicy method
or 2) use the predicate based configuration approach via the IfModel methods.
If you go the predicate route (e.g., x.Failures.IfModelIs()), you can tell FubuMVC.Validation to use FubuContinuations to redirect or transfer to another behavior
chain. Rex recently posted about FubuContinuations if you're looking for some guidance in this area (http://rexflex.net/2011/07/fubumvc-fubucontinuation/).
Hope this helps and feel free to ask away if I didn't explain anything enough,
Josh

CodeIgniter reusable message library

I'm using Message library (http://codeigniter.com/wiki/Message/) to display error messages on my site. This is the code that I'm using to display a message:
$this->message->set('error',$this->config->item('error.login'));
Right now I'm storing common messages in my config file (config/config.php) instead of writing the message every time. Is there a better way to do it? The config file is getting very long.
What I'm looking for is a better way to store re-usable text strings.
CodeIgniter's language class is what you're looking for:
CI Language Class
$this->message->set('error',$this->lang->line('error.login'));
A config file is more or less how you'd want to do it. It is simple, clear and light. But just because you are keeping it in a config file, that does not mean you need to keep it in config.php. The Config class allows you to have multiple config files, so have a special one for messages. Heck, you could even have several special ones for languages, and leave the one you are looking for in the config.php file!
$this->config->load( $this->config->get( "language_file_name" ) );

Resources