Japaneseization of validation messages in Silex

Asked 2 years ago, Updated 2 years ago, 68 views

Validation of form entries in Silex 2.x.
I saved the translation in YAML, so I read it as follows.

$app->register(newSilex\Provider\ValidatorServiceProvider());
$app->register(newSilex\Provider\LocaleServiceProvider());
$app->register(newSilex\Provider\TranslationServiceProvider(), array(
    'locale' = > "ja"
));
$app['translator'] = $app->extend('translator', function($translator,$app){
    $translator->addLoader('yaml', new Symphony\Component\Translation\Loader\YamlFileLoader());

    $translator->addResource('yaml',__DIR__.'/../resources/lang/ja.yml', "ja", 'validators');

    return$translator;
});

Check point

$inputs=[
    "name" = > $request-> get("name")
];

$constrain=newAssert\Collection([]
    'name' = > new Assistant\NotBlank()
]);

$errors=$app['validator']->validate($inputs,$constraint);
foreach($errors as$error){
    echo$error->getMessage();
}

In the ja.yml file

This value should not be blank.—The value is empty.

I was able to translate the result of getMessage() into Japanese, but for example, if the name field is empty, I would like to use the expression "My name is empty."
"I was able to write "":attribute value "":value"" is incorrect"" for Ravel, but what is common with Silex?"

Translating $error->getPropertyPath() with $app['translator']->trans() and replacing placeholders such as ":attribute" with str_replace() may be a temporary form, but I don't think it's the right way to do it.

I look forward to working with you if there is a good way.

php symfony2 silex

2022-09-30 19:17

1 Answers

If you want to configure error messages for each field (properties), you can specify your own error messages in an optional array that you pass to the constraint constructor as follows:

$constrain=newAssert\Collection([]
    'name' = > new Assistant\NotBlank (['message' = > 'Name is empty'],
]);

If you want to use user input values in your own error message, you can use the placeholder {{value}}.

$constrain=newAssert\Collection([]
    'age' = > new Assert\Range (['min' = > 18, 'message' = > 'Not available for under 18 years of age ({{value}}}'],
]);


2022-09-30 19:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.