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!

图片转代码服务由CSDN问答提供 功能建议

我有以下Doctrine实体,我也希望将其限制用于验证。 \ n

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

我使用以下验证,该验证适用于symfony特定注释但不适用于Doctrine设置限制! \ n

  //验证数据
 $ validator = $ this-> get('validator'); 
 $ errors = $ validator-> validate($ user); 
 
if  (count($ errors)> 0){
 $ response = new JsonResponse(array(
'error'=>'无法创建用户。'。PHP_EOL。(string)$ errors 
));  
 $ response-> setStatusCode(400); 
 
返回$ response; 
} 
   
 
 

我该怎么办? 让symfony验证器使用doctrine限制作为设置?

现状:
读取[ 1 ]和[ 2 ]但到目前为止我不使用表单,因为我有一个控制器返回JSON。 如果您知道如何使用表单进行此操作也会有很多帮助!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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)
       */
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题