前一段时间我提出了同样的问题Symfony PUT does not contain all entity properties mapped,我有一些#hack解决方案来解决问题但是当表单更复杂时,包含选择(数组)或映射实体(对象),解决方案是不再适用。所以我提出了非常肮脏的想法,以使其工作,如
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);
}
答案 0 :(得分: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章节。