概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:50:04 | 205 次阅读 | 评论: 0 | 来源: 网络整理

Sometimes, you may want to display constraint validation error messages differently based on some rules. For example, you have a registration form for new users where they enter some personal information and choose their authentication credentials. They would have to choose a username and a secure password, but providing bank account information would be optional. Nonetheless, you want to make sure that these optional fields, if entered, are still valid, but display their errors differently.

The process to achieve this behavior consists of two steps:

  1. Apply different error levels to the validation constraints;
  2. Customize your error messages depending on the configured error level.

1. Assigning the Error Level

2.6 新版功能: The payload option was introduced in Symfony 2.6.

Use the payload option to configure the error level for each constraint:

  • Annotations
    // src/AppBundle/Entity/User.php
    namespace AppBundleEntity;
    
    use SymfonyComponentValidatorConstraints as Assert;
    
    class User
    {
        /**
         * @AssertNotBlank(payload = {severity = "error"})
         */
        protected $username;
    
        /**
         * @AssertNotBlank(payload = {severity = "error"})
         */
        protected $password;
    
        /**
         * @AssertIban(payload = {severity = "warning"})
         */
        protected $bankAccountNumber;
    }
    
  • YAML
    # src/AppBundle/Resources/config/validation.yml
    AppBundleEntityUser:
        properties:
            username:
                - NotBlank:
                    payload:
                        severity: error
            password:
                - NotBlank:
                    payload:
                        severity: error
            bankAccountNumber:
                - Iban:
                    payload:
                        severity: warning
    
  • XML
    <!-- src/AppBundle/Resources/config/validation.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    
        <class name="AppBundleEntityUser">
            <property name="username">
                <constraint name="NotBlank">
                    <option name="payload">
                        <value key="severity">error</value>
                    </option>
                </constraint>
            </property>
            <property name="password">
                <constraint name="NotBlank">
                    <option name="payload">
                        <value key="severity">error</value>
                    </option>
                </constraint>
            </property>
            <property name="bankAccountNumber">
                <constraint name="Iban">
                    <option name="payload">
                        <value key="severity">warning</value>
                    </option>
                </constraint>
            </property>
        </class>
    </constraint-mapping>
    
  • PHP
    // src/AppBundle/Entity/User.php
    namespace AppBundleEntity;
    
    use SymfonyComponentValidatorMappingClassMetadata;
    use SymfonyComponentValidatorConstraints as Assert;
    
    class User
    {
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addPropertyConstraint('username', new AssertNotBlank(array(
                'payload' => array('severity' => 'error'),
            )));
            $metadata->addPropertyConstraint('password', new AssertNotBlank(array(
                'payload' => array('severity' => 'error'),
            )));
            $metadata->addPropertyConstraint('bankAccountNumber', new AssertIban(array(
                'payload' => array('severity' => 'warning'),
            )));
        }
    }
    

2. Customize the Error Message Template

2.6 新版功能: The getConstraint() method in the ConstraintViolation class was introduced in Symfony 2.6.

When validation of the User object fails, you can retrieve the constraint that caused a particular failure using the getConstraint() method. Each constraint exposes the attached payload as a public property:

// a constraint validation failure, instance of
// SymfonyComponentValidatorConstraintViolation
$constraintViolation = ...;
$constraint = $constraintViolation->getConstraint();
$severity = isset($constraint->payload['severity']) ? $constraint->payload['severity'] : null;

For example, you can leverage this to customize the form_errors block so that the severity is added as an additional HTML class:

{%- block form_errors -%}
    {%- if errors|length > 0 -%}
    <ul>
        {%- for error in errors -%}
            {% if error.cause.constraint.payload.severity is defined %}
                {% set severity = error.cause.constraint.payload.severity %}
            {% endif %}
            <li{% if severity is defined %} class="{{ severity }}"{% endif %}>{{ error.message }}</li>
        {%- endfor -%}
    </ul>
    {%- endif -%}
{%- endblock form_errors -%}

参见

For more information on customizing form rendering, see How to Customize Form Rendering.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务