1

カスタム制約バリデーターを作成しました。バリデーターは機能しています。しかし、php テンプレートで CUSTOM バリデーターのエラーメッセージを翻訳するにはどうすればよいでしょうか? 他のバリデータ メッセージは機能しているので、翻訳はapp/config/validators.XX.yml.

私の行動では:

$form = $this->createFormBuilder()
             ->add('date_id', 'choice', array(
                ....
                'constraints' => array(new CheckChoicesDateId(array('date_ids' => $date_ids))),
                ....
            ))

バンドル/バリデーター/制約内

class CheckChoicesDateId extends Constraint
{
    public $invalidMessage = '{{ value }}';
    public $date_ids;
    public function __construct($options = null)
    {
        parent::__construct($options);

        if (null === $this->date_ids ) {
            throw new MissingOptionsException('Option date_ids must be given for constraint ' . __CLASS__, array('date_ids'));
        }
    }
}

バンドル/バリデーター/制約内

class CheckChoicesDateIdValidator extends ConstraintValidator {

    public function validate($value, Constraint $constraint) {

        if ($value == NULL || !isset($value)) {
            $this->context->addViolation($constraint->invalidMessage, array(
                '{{ value }}' => 'error.date.0',
                //I also tried $this->get('translator')->trans('error.date.0');
                // with the error message: Call to undefined method GET
            ));
        }


        if (is_numeric($value)) {
            $t = array_key_exists($value, $constraint->date_ids);
            if ($t == NULL) {
                $this->context->addViolation($constraint->invalidMessage, array(
                    '{{ value }}' => 'error.date.1',
                ));
            }
        }
        return;
    }

}

私のテンプレートでは:

<?php echo $view['form']->errors($form['date_id']) ?>
//I also tried
<?php echo $this->get('translator')->trans($view['form']->errors($form['date_id'])) ?>
4

1 に答える 1

0

私には解決策がありますが、それは良くないと思います:

アクションでは、考えられるエラーごとに変数を渡します。

'constraints' => array(new CheckChoicesDateId(array('date_ids' => $date_ids, 'error_date_0 => $this->get('translator')...., 'error_date_1 => $this->get('translator')....  ))),

カスタムバリデーターでは、エラーごとに正しい変数を.で呼び出します$constraint->error_date_X

良くありませんが、機能しています。誰かがより良い解決策を持っているなら、それを投稿してください!

于 2013-03-20T17:56:07.297 に答える