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

时间:2015-01-17 16:24:16

标签: php rest symfony fosrestbundle jmsserializerbundle

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

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

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

CRSF被禁用:

disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY

示例请求标头:

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'];
    }

}

1 个答案:

答案 0 :(得分:0)

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

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