1
votes

I use symfony 2.63 + FosRestBundle (@stable) +JMSSerializer (@stable).

I cant update one field of entity using PUT or PATCH method. It works fine with GET, POST and DELETE, but when I want to update one field of entity using PUT or PATCH then isValid() return always false.

The most strange is if I change method PATCH to POST(in request and in controller) entity is updated correctly and all works fine.

CRSF is disabled by:

disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY

Example request 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

Controller:

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

1 Answers

0
votes

I believe this line will help you. You just need to set up some options while creating form.

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