How do I enable translations on Symfony2 callback validation error messages? - validation

I'm early in a project and I've created some basic functionality, including a custom callback validator (validates end date is after start date). I've since started refactoring to enable translation. I've so far had no issues... until I started looking at translating my custom callback validation.
I read a post online that claimed that I could put my translation key value as my error message and Symfony will automatically translate... but this doesn't seem to be the case for me. Can someone tell me how, or provide a link to documentation, to enable translations in my custom validations?
Here's my current validation code with the translation key included:
<?php
namespace CG5\BFG\CoreBundle\Validators;
use Symfony\Component\Validator\ExecutionContext;
class EndDateValidator
{
static public function isEndDateValid($entity, ExecutionContext $context)
{
if ($entity->getEndDate() <= $entity->getStartDate())
$context->addViolationAtSubPath('endDate', 'validation.invalid.enddate', array(), null);
}
}

I got the same problem. Because symfony2 looks in the "validators" Catalogue for those messages, you have to put your custom error message also in that Catalogue. For example under app/Resources/translations/validators.en.yml.
You need to clear the cache for it to work.

Related

Accessing dynamic links in the format of domain.com/<dynamic_page_name> in CodeIgniter

I am using code Igniter for my PHP project. I want to give provision in my site such that users can create new pages of their own, and access them directly from domain.com/their_page_name.
But, my developers have raised a concern that, 1000's of dynamic links that are presented in the format of domain.com/ is "not good for site's performance". For some 10-15 pages, it is fine. But, beyond that, it would effect the site's performance.
So, they proposed that the URL format should be like www.domain.com/something/page_name (here, 'something' is the controller name, as they mentioned it)
But, I really can't sacrifice my framework nor my requirement.
Is there any way that I can achieve the format of "www.domain.com/page_name" without effecting the site's performance?
Thanks in advance.
No issues on
Www.domain.com\userpagename.
It's not a framework issues. Codeigniter support this type of URL.you can create n no of URL.
Performance will matter how you are handling that particular controller or that particular function.
If may be 10 may be 100 ,work around same way.
You just have to put route accordingly.
$route[default_controller]=userurl;
$route[userurl/(:any)]=userurl yourfunction/$1`;
What it seems you need is dynamic controller, which can be done using Codeigniter's build in function _remap().
A code example is:
public function _remap($method){
if($method != null){
$this->yourFunction($method);
} else {
// handle the error as you like
}
}
public function yourFunction($key){
// your code logic here
}
All this code block goes inside your controller.
Edit: the performance is exactlu the same as going with domain.com/controller/method. What it matters, as stated above, is how you handle the data.

Custom Symfony2 Validator Constraint Messages

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!

Magento email template: Block template inheritance broken

Problem
When I try to add a block into my transactional email template in the following manner:
{{block type='core/template' area='frontend' template='invent/baskettimer/email_items.phtml' record=$record}}
I get the following error, and nothing is rendered.
CRIT (2): Not valid template file:frontend/base/default/template/invent/baskettimer/email_items.phtml
Troubleshooting
Normally this warning points to a typo which is breaking the inheritance but I have quadruple checked and this should work.
I then copied the file into the base and did a test, it rendered correctly.
Create a custom block and set the template, same error is displayed.
Theory
To me it seems template inheritance is broken / not implemented for emails, so it is always looking in base, I cannot put my templates there so I am not sure how to call them.
Possible workarounds
Render the block to html then send it to as a variable to render, problem with this is I am sending the emails from Model level and am having a hard time pre rendering the block, even with a helper.
Render the data using a method, don't really want to do this as it is message / against MVC.
Any help is much appreciated.
Bounty update
So I have traced down the problem, it is probably an easy solution now.
The problem is that I am calling it from a cronjob does not have the correct store view, it is fairly easy to replicate similar situation by using a shell script, then changing the _appCode to null.
<?php
require_once 'abstract.php';
class Mage_Shell_Shell extends Mage_Shell_Abstract
{
protected $_appCode = ''; // works - remove to not work
/**
* Run script
*
*/
public function run()
{
Mage::getModel('invent_baskettimer/email')->sendJob();
}
}
$shell = new Mage_Shell_Shell();
$shell->run();
So basically the question has become:
How do I call a block->toHtml() regardless of store view?
There is not way of setting a cronjob to be like that. Lucky magento lets you emulate your store views, see the following to emulate the default store.
public function cronjob()
{
$iDefaultStoreId = Mage::app()
->getWebsite()
->getDefaultGroup()
->getDefaultStoreId();
$appEmulation = Mage::getSingleton('core/app_emulation');
$initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($iDefaultStoreId);
.. do your stuff here ..
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
}
For more info see: http://inchoo.net/ecommerce/magento/emulate-store-in-magento/

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

Silverlight 4: Localization of built-in data annotation validation exceptions

I would like use data annotations to handle validation in my Silverlight app. The built-in validation attributes (primarily StringLength and Required) are great, and make life very easy. However, they seem to have one critical flaw. If my locale is set to fr-CA, for example, the validation exceptions are still in English - 'The Name field is required', 'The field Name must be a string with a maximum length of 20', etc.
This is a major problem. It means that if I want localized error messages for the built-in validation attributes, I have to manually add ErrorMessage/ErrorMessageResourceType to every validation attribute on every validatable property in my business layer, and manually add translated strings for every error message.
So... am I missing something here? Is there a way to automatically have the built-in validation attributes localized? Or some other easier way of doing this? Or am I just completely out of luck, and stuck with the manual route?
Any comments or thoughts would be appreciated.
Ok, I got around this by simply subclassing the built-in validation attributes. Problem solved!
internal class LocalizedStringLengthAttribute : StringLengthAttribute
{
public LocalizedStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, LanguageResources.Resource.Error_StringLength, name, MaximumLength);
}
}

Resources