symfony2 isValid()方法总是返回true
问题描述:
我将数据保存到数据库之前验证我的数据,但到目前为止,当关闭javascript验证时,我无法检测对象是否有效。下面是我如何做它:symfony2 isValid()方法总是返回true
$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)));
}
可惜的方法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);
}
采取但它也没有工作......
UPDATE
我的 '内容' 属性,它导致错误
/**
* @var string
*
* @ORM\Column(name="content", type="text")
*/
private $content;
答
您必须在您的设置Constraints
r Entity
或者您可以在您的FormType
manually中为您的字段设置验证规则。
这里是你的`实体的例子
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;
你有什么['Constraints'(http://symfony.com/doc/current/book/validation.html#basic-constraints) '或'FormType'? – 2014-09-06 19:03:08
不,它看起来像在symfony中,默认情况下需要任何属性 – Leo 2014-09-06 19:05:38
不,您必须使用['NotBlank()'](http://symfony.com/doc/current/reference/constraints/NotBlank.html)或['NotNull()'](http://symfony.com/doc/current/reference/constraints/NotNull.html)使字段是必需的。 – 2014-09-06 19:08:15