我对 Assert/NotBlank() 有疑问。 它就是行不通。 每次当我发送空白表单时,我都会看到 500,
SQLSTATE[23000]: Integrity constraint violation: 1048 Column '***' cannot be null
,而不是一些错误。
我在实体中有这个:
use Symfony\Component\Validator\Constraints as Assert;
...
/**
* @var string
*
* @ORM\Column(name="text", type="text")
* @Assert\NotBlank()
*/
private $text;
...
额外: 控制器: 控制器,用于将广告添加到数据库。
public function insertAdAction($categoryId, Request $request)
{
$em = $this->getDoctrine()->getManager();
$category = $em->getRepository('DbBundle:Category')->findAll();
$ads = new Ads();
$form = $this->createForm(new InsertAdType(), $ads, array(
'categoryId' => $categoryId,
'name' => $request->cookies->get('name'),
'phone' => $request->cookies->get('phone'),
'email' => $request->cookies->get('email'),
'password' => $request->cookies->get('password'),
));
$form->handleRequest($request);
if ($form->isValid()) {
try {
$user = new User();
$validator = $this->get('validator');
$validator->validate($ads);
$byCategory = $em->getRepository('DbBundle:Category')->findOneBy(array('id' => $categoryId), array());
$categoryName = $byCategory->getName();
$phone = $form['phone']->getData();
$ads->setCategory($categoryName);
$ads->setCategoryUrl($this->get('WebPortalBundle')->seoUrl($categoryName));
$ads->setCountry($form['country']->getData());
$ads->setText(nl2br($form['text']->getData()));
$ads->setTitleUrl($this->get('WebPortalBundle')->seoUrl($form['title']->getData()));
$ads->setSubcategoryUrl($this->get('WebPortalBundle')->seoUrl($form['subcategory']->getData()));
$ads->setIp($request->getClientIp());
if (!$em->getRepository('DbBundle:User')->findOneBy(array('phone' => $form['phone']->getData()))) {
$user->setPhone($phone);
$em->persist($user);
}
$ads->setPath(implode(',', $this->uploadImg($form['file']->getData())));
$em->persist($ads);
$em->flush();
$response = new Response();
$time = time() + 31536000;
$response->headers->setCookie(new Cookie('name', $form['name']->getData(), $time));
$response->headers->setCookie(new Cookie('email', $form['email']->getData(), $time));
$response->headers->setCookie(new Cookie('phone', $form['phone']->getData(), $time));
$response->headers->setCookie(new Cookie('password', $form['password']->getData(), $time));
$response->send();
} catch (Exception $ex) {
throw new \ErrorException;
}
}
return $this->render('WebPortalBundle:Default/InsertAd:insertAd.html.twig', array('category' => $category, 'insertForm' => $form->createView()), $this->get('WebPortalBundle')->cache($request));
}
我做错了什么?
我敢打赌,您的表单类型中没有
setDefaultOptions
方法。
use Symfony\Component\OptionsResolver\OptionsResolver;
...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DBBundle\Entity\Ads',
));
}