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)
       */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码