Search code examples
phpsymfonyfosrestbundle

How to apply only diff changes from request object to form


I'm implementing patch method using fosrestbundle and I want to create proper patch method.

To do so I've created controler and there is patchAction which takes an argument Entity, Entity is created passed via ParamConverter which I wrote myself. The Entity is passed to EntityType and here's the problem. I want to update only fields that changed and when I pass Entity to form it set nulls to object that comes from request. Entity is POPO

Here's the flow

  1. User sends PATCH request to /entity/{Entity} let's say /entity/12
  2. Param converter converts 12 to proper Entity asking DB for the data
  3. EntityFormType takes Entity as argument and sets data from request to entity.
  4. Entity is stored to DB

The problem is that form after it takes whole Entity object it sets null for fields that are null on form. I'd prefer if it took these values and set it for example as defaults.

I don't and can't use doctrine ORM.

The code:

 /**
 * @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
}

I was thinking about form events or creating something like diff method but probably there is better solution?


Solution

  • You need to create your form with method option set.

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

    If request is send with PATH method then Symfony will update only sent fields.

    How to fake PATCH method in Symfony: http://symfony.com/doc/current/cookbook/routing/method_parameters.html#faking-the-method-with-method