使用 PUT 或 PATCH 更新给出 isValid() false 的结果

Update using PUT or PATCH give result of isValid() false

我使用 symfony 2.63 + FosRestBundle (@stable) +JMSSerializer (@stable)。

我无法使用 PUT 或 PATCH 方法更新实体的一个字段。 它适用于 GET、POST 和 DELETE,但是当我想使用 PUT 或 PATCH 更新实体的一个字段时,isValid() return 始终为 false。

最奇怪的是,如果我将方法 PATCH 更改为 POST(在请求和控制器中)实体会正确更新并且一切正常。

CRSF 被禁用:

disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY

示例请求 headers:

PATCH /app_dev.php/panel/api/event/simple/12 HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
Accept: application/json, text/plain, */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/app_dev.php/panel
Content-Length: 28
Cookie: PHPSESSID=mlbupodjs66qrc1ubvkn5ehah5
Connection: keep-alive

控制器:

namespace KM\AdminpanelBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializationContext;
use KM\AdminpanelBundle\Entity\Event;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Routing\ClassResourceInterface;

class EventApiController extends FOSRestController implements ClassResourceInterface {


    /**
     * @Rest\PATCH("/simple/{id}", requirements={"id": "\d+"})
     * @var Request $request
     * @var Integer $id
     * @Rest\View()
     */
    public function putAction(Request $request, $id) {


        $event = $this->getDoctrine()->getRepository('KMAdminpanelBundle:Event')->find($id);

        $form = $this->createFormBuilder($event)
                ->add('Name', 'text', array('attr' => array('maxlength' => 30), 'label' => false))
                ->add('CreatedOn', 'datetime')
                ->getForm();
        $form->handleRequest($request);

        if ($form->isValid()) {

            $event->setCreatedOn(new \DateTime('today'));
            $em = $this->getDoctrine()->getManager();
            $em->persist($event);
            $em->flush();

        } else {

            $form->submit($request);
            $errors = dump((string) $form->getErrors(true));
            return ['errors' => $errors];
        }
        return ['id' => $id, 'info' => 'Its OK'];
    }

}

相信这条线会对你有所帮助。您只需要在创建表单时设置一些选项即可。

$form = $this->createFormBuilder($event, array('method' => 'PATCH'))
                ->add...