如何仅将请求对象的差异更改应用于表单


How to apply only diff changes from request object to form

我正在使用fosrestbundle实现补丁方法,我想创建合适的补丁方法。

为此,我创建了controler,有一个patchAction,它接受一个参数Entity,Entity是通过我自己编写的ParamConverter创建的。Entity被传递给EntityType,问题出在这里。我只想更新已更改的字段,当我传递Entity来形成它时,将请求中的对象设置为null。实体是POPO

这是的流程

  1. 用户将PATCH请求发送到/pentity/{entity},比方说/pentity/12
  2. Param转换器将12转换为适当的实体,向DB请求数据
  3. EntityFormType将Entity作为参数,并将数据从请求设置为实体
  4. 实体存储到数据库

问题是,表单在接受整个Entity对象后,会为表单上为null的字段设置null。我更喜欢它接受这些值并将其设置为默认值。

我没有也不能使用ORM学说。

代码:

 /**
 * @ParamConverter("Entity", class="Entity")
 */
public function patchAction(Entity $entity, Request $request)
{
    var_dump($entity); // object mapped from DB
    $form = $this->createForm(new EntityType(), $entity);
    $form->handleRequest($request);
    $form->submit($request);
    var_dump($entity);exit; //here I get only values that i passed through patch method, rest of them is set to null
}

我在考虑表单事件或创建类似diff方法的东西,但可能有更好的解决方案?

您需要使用method选项集创建表单。

$form = $this->createForm(new EntityType(), $entity, array(
    'method' => $request->getMethod(),
));

如果使用PATH方法发送请求,则Symfony将仅更新已发送的字段。

如何在Symfony中伪造PATCH方法:http://symfony.com/doc/current/cookbook/routing/method_parameters.html#faking-方法的方法