通过输入表单加载实体并将未找到的错误消息添加到特定字段

时间:2016-02-13 15:08:30

标签: symfony symfony-forms symfony-2.6

想要在不存在时通过表单输入字段加载用户实体向字段添加错误消息

    $builder->setMethod('get');
    $builder->add('username', 'text'); // add error to this field when username dont exist
    $builder->add('token', 'text') // add error on this field when token dont match with current token
        // transformer should set token to null
        ->addModelTransformer(new CallbackTransformer(
            function ($original) {
                return $original;
            },
            function ($submitted) {
                return null;
            }
        ));
    $builder->add('submit', 'submit');

1 个答案:

答案 0 :(得分:1)

// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    /**
     * @Assert\NotBlank(message="Name is empty")
     */
    protected $name;
}

http://symfony.com/doc/current/reference/constraints.html

我不确定您在检查token的位置。不要忘记在$form->isValid()

之后添加$form->handleReqest($reqest)