2015-10-01 20 views
0

虽然以前我问过同样的问题Symfony PUT does not contain all entity properties mapped,我已经有一些#hack解决方案来解决问题,但是当表单更复杂时,包含选择(数组)或映射实体(对象)解决方案不再适用。所以我想出了很肮脏的想法,使其工作,如FOSRestBundle一次只更新一个字段使用PUT

 if(is_object($event->getForm()->getData())) $event->setData($event->getForm()->getData()->getId()); 
     if(is_array($event->getData()) && empty($event->getData())) 
     { 
      $event->setData([$event->getForm()->getData()]); 
     } 
     if($event->getForm()->getData() instanceof \DateTime) $event->setData($event->getForm()->getData()->format('Y-m-d H:i:s')); 
     if(!is_array($event->getData()) && (is_string($event->getForm()->getData()) || is_integer($event->getForm()->getData()))) 
     { 
      $event->setData($event->getForm()->getData()); 
     } 

但它甚至不工作完美。所以我必须多问一次在发送json响应时是否有更好的解决方案来更新一个值,因为如果我发送{"user":{"firstName":"John"}}属于User表单的所有其他字段都是空的,并且我无法发送整个资源。我找不到解决这个问题的办法。

而这里的控制器

/** 
* This endpoint updates an existing Client entity. 
* 
* @ApiDoc(
* resource=true, 
* description="Updates an existing Client entity", 
*) 
* @ParamConverter("user", class="Software:User", options={"mapping": {"user": "guid"}}) 
*/ 
public function putAction(Request $request, $user) 
{ 
    $form = $this->createForm(new UserType(['userType' => 'client', 'manager' => $this->getDoctrine()->getManager()]), $user, ['method' => 'PUT']); 
    $form->handleRequest($request); 

    if($form->isValid()) 
    { 
     $manager = $this->getDoctrine()->getManager(); 
     $manager->flush(); 

     return $this->view([ 
      'user' => $user 
     ]); 
    } 

    return $this->view($form); 
} 

回答

1

我要回答我的问题。

答案是用PATCH方法代替PUT。 下面是修改后的代码:

/** 
* This endpoint updates an existing Client entity. 
* 
* @ApiDoc(
* resource=true, 
* description="Updates an existing Client entity", 
*) 
* @ParamConverter("user", class="Software:User", options={"mapping": {"user": "guid"}}) 
*/ 
public function patchAction(Request $request, $user) 
{ 
    $form = $this->createForm(new UserType(['userType' => 'client', 'manager' => $this->getDoctrine()->getManager()]), $user, ['method' => 'PATCH']); 
    $form->handleRequest($request); 

    if($form->isValid()) 
    { 
     $manager = $this->getDoctrine()->getManager(); 
     $manager->flush(); 

     return $this->view([ 
      'user' => $user 
     ]); 
    } 

    return $this->view($form); 
} 

请查找引用: Symfony2 REST API - Partial update

http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/

仔细阅读PATCH与PUT章节。