April 07, 2014

April 07, 2014
In this article, we are going to discuss about How to translate the validation Error messages in Symfony 2 framework. Translation is the communication of the meaning of a source-language text by means of an equivalent target-language text. Here, we are going to translate the validation error messages in Symfony 2 framework.

Here is the Example for the Model class "Car"

<?php
namespace  Phpcmsframework\Test Bundle\Entity;
use  Doctrine\ORM\Mapping as  ORM;
use  Symfony\Component\Validator\Constraints as  Assert;

/ **
 * Car Class - buzz buzz
 * @ ORM \ Entity (repositoryClass = "Phpcmsframework\Test Bundle\Entity\CarRepository")
 * @ ORM \ Table (name = "cars")
 * /
class  Car
{
    / **
     * @ ORM \ Id
     * @ ORM \ Column (type = "integer", name = "id")
     * @ ORM \ GeneratedValue (strategy = "AUTO")
     * /
    private  $ id ;

    / **
      * The serial number of the car
      * @ Assert \ NotBlank (message = "The name can not be left blank!")
      * @ Assert \ regex (pattern = "/ ^ ([A-Z0-9]) {1,} $ /", message = "Please use only capitalized letters and dashes")
      * @ ORM \ Column (type = "string", name = "serial", nullable = true)
      * @ Var string
      * /
    private  $ serial ;

    / * Getter and Setter Methods are hidden * /
}

If a new car is added by /cars/add, it is first check, whether the "serial" field is not empty, then if the serial number has only capital letters and dashes (eg: A-BZ-K55).

To view the error messages now fit into another language to translate, "{language}. Yml validators." Must be in the project folder for the translations. A new file will be created with ".Yml" is my preference here. Support XML or similar from Symfony2 formats can also be selected. The translations are (mostly) in the folder /src/Phpcmsframework/Test Bundle/Resources/translations.

In this example, the German translation would look like this:

#/src/Phpcmsframework/Test Bundle/Resources/translations/validators.de_DE.yml. 'Please use only letters capitalized and Dashes': 'Please use only capital letters and dashes'

0 comments:

Post a Comment