我在将数据保存到数据库之前验证了我的数据,但到目前为止,当关闭javascript验证时,我无法检测对象是否有效。我是这样做的:
$editForm = $this->createEditForm($post, $category_id, $section_id, $topic_id);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('topic_show', array('category_id'=> $category_id, 'section_id'=> $section_id, 'id'=> $topic_id)));
}
unfortunatelly方法isValid()每次都返回true然后我从mysql中得到错误。
我尝试了不同的方法,取自here
$validator = $this->get('validator');
$errors = $validator->validate($post);
if (count($errors) > 0) {
throw $this->createNotFoundException('Unable to find Post entity.');
/*
* Uses a __toString method on the $errors variable which is a
* ConstraintViolationList object. This gives us a nice string
* for debugging
*/
$errorsString = (string) $errors;
return new Response($errorsString);
}
但它也不起作用......
更新
我的内容'导致错误的属性
/**
* @var string
*
* @ORM\Column(name="content", type="text")
*/
private $content;
答案 0 :(得分:1)
您必须在Entity
中设置Constraints
,或者可以在FormType
manually中设置{{3}}来为您的字段设置验证规则。
这是一个例子
use Symfony\Component\Validator\Constraints as Assert;
...
/**
* @var string
*
* @ORM\Column(name="content", type="text")
* @Assert\NotBlank(
* message = "Your error message here if content is empty"
* )
*/
private $content;