简体   繁体   中英

symfony translation for custom assert

I created custom assert for check value, only digit and I need create translate message for this costume assert. I create all what need, but after validate I get trans key instead of trans message

[
  {
    "property_path": "phone",
    "message": "contains.numeric"
  }
]

This what I have

\\AppBundle\Validator\Constraints\ContainsNumericValidator
class ContainsNumericValidator extends ConstraintValidator
{
private $repository;

public function __construct(UserRepository $repository)
{
    $this->repository = $repository;
}

public function validate($value, Constraint $constraint)
{
    if (!preg_match('/^[0-9]+$/', $value, $matches)) {
        $this->context->buildViolation($constraint->message)
            ->setParameter('{{ string }}', $value)
            ->addViolation();
    }
}
}


\\AppBundle\Validator\Constraints\ContainsNumeric
/**
 * @Annotation
 */
class ContainsNumeric extends Constraint
{
    public $message = 'contains.numeric';
}

and in my entity

use AppBundle\Validator\Constraints as AppAssert;

/**
 * @ORM\Table(name="users")
 */
class User extends AbstractUser implements UserInterface
{
/**
 * @AppAssert\ContainsNumeric()
 * @ORM\Column(name="phone", type="string", nullable=true)
 */
private $phone;

and my xlf app/Resources/translations/validators.en.xlf

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
    <body>
        <trans-unit id="contains.numeric">
            <source>contains.numeric</source>
            <target>Please enter an valid data.</target>
        </trans-unit>
    </body>
</file>
</xliff>

In your translation file you need to attribute resname like this:

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
    <body>
        <trans-unit id="contains.numeric" resname="contains.numeric">
            <source>contains.numeric</source>
            <target>Please enter an valid data.</target>
        </trans-unit>
    </body>
</file>
</xliff>

In fact resname value is the key used to choose translation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM