Symfony2表单中的验证无效

时间:2012-10-26 08:25:32

标签: symfony

我创建了一个表单,当我将其发送到服务器时,我收到内部服务器错误,因为有空字段是不允许的。但我想知道因为我使用以下代码检查表单,因此通常应该跳过数据库操作。可能是什么原因?

控制器:

public function newAction(Request $request) {

    $objTrip = new Trip();
    $objForm = $this->createForm(new TripType, $objTrip);

    if ($request->isMethod('POST')) {
        $objForm->bind($request);

        if ($objForm->isValid()) {
            $objEm = $this->getDoctrine()->getManager();
            $objEm->persist($objTrip);
            $objEm->flush();

            $response = new Response(json_encode(array('success' => true)));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }

        // Es traten Fehler auf
        $arrErrors = array();
        foreach($objForm as $objField) {

            if($objField->hasErrors())
                foreach($objField->getErrors() as $objError)
                    $arrErrors[] = array($objField->var['id'] => $objError->getMessage());
        }
        $response = new Response(json_encode(array('success' => false, 'errors' => $arrErrors)));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    return array('form' => $objForm->createView());
}

实体:

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(type="string", length=100)
 * @Assert\MinLength(
 *     limit=3
 * )
 */
protected $startLocation;

/**
 * @ORM\Column(type="string", length=100)
 */
protected $endLocation;

/**
 * @ORM\Column(type="datetime")
 */
protected $startTime;

/**
 * @ORM\Column(type="decimal", scale=2)
 */
protected $price;

4 个答案:

答案 0 :(得分:2)

@Gerrit,嗨,看起来你没有使用NotBlank约束。 MinLength跳过空值。

答案 1 :(得分:0)

 /**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(type="string", length=100)
 * @Assert\MinLength(
 *     limit=3
 * )
 */
protected $startLocation;

/**
 * @ORM\Column(type="string", length=100)
 */
protected $endLocation;

/**
 * @ORM\Column(type="datetime")
 */
protected $startTime;

/**
 * @ORM\Column(type="decimal", scale=2)
 */
protected $price;

答案 2 :(得分:0)

当您获得实体中不存在的formtype字段时,通常会出现您提到的错误。

你能告诉我们FormType吗?

答案 3 :(得分:0)

@Flask,不仅仅是 - 对于我来说,当我没有为notnull字段设置正确的(例如)NotBlank验证器并关闭html5验证或进行功能测试时,通常会出现内部异常,但是很高兴看看FormType: )

顺便说一下。 (抱歉为offtop)我只能评论自己的答案是正常的吗?