dou4624 2015-10-01 14:32
浏览 47
已采纳

使用Doctrine2注释进行Symfony2验证

I have the following Doctrine entity and I want to use its restriction also for validation.

/**
 * @var string
 *
 * @ORM\Column(type="string", length=40)
 * @Assert\Valid
 */
private $birthName;

I use the following validation, which works for symfony specific annotaions but not Doctrine set restrictions!

// Validate data
$validator = $this->get('validator');
$errors = $validator->validate($user);

if (count($errors) > 0) {
    $response = new JsonResponse(array(
        'error' => 'User could not be created.' . PHP_EOL . (string)$errors
    ));
    $response->setStatusCode(400);

    return $response;
}

What can I do to let symfony validator use the doctrine restrictions as settings?

Status quo:
I read [1] and [2] but so far I do not use forms because I have a controller returning JSON. If you know how to make this work with forms would also help a lot!

  • 写回答

1条回答 默认 最新

  • doufang3001 2015-10-01 15:11
    关注

    Doctrine mappings have nothing to do with validation. The code @ORM\Column(type="string", length=40) only maps a property to a database field, and sets max length of a database field to be equal 40 characters, if you would create a schema using doctrine.

    But thus doesn't take any part of the validation process. So you need to set an assertion rule by something like

       /**
       * @Assert\Length(max = 40)
       */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?