FOSRestBundle icon indicating copy to clipboard operation
FOSRestBundle copied to clipboard

Using RequestBodyParamConverter with get parametr.

Open MaxBoltik opened this issue 9 years ago • 4 comments
trafficstars

When I need to update an entity, I need to put "id" in the request body. But there is no way to pass id in query string.

For example, I want update Person and get person entity by {id}:

    /**
     * @Route("/update/{id}", name="update")
     * @ParamConverter("person", converter="fos_rest.request_body", options={"deserializationContext"={"groups"={"person:update"}}})
     * @param Person $person
     * @return mixed
     */
    public function updatePerson(Person $person){....}

To solve this I extends DoctrineObjectConstructor and add following code:

    /**
     * @param array                  $data
     * @param DeserializationContext $context
     *
     * @return array
     */
    private function attachIdentifiersFromRequest($data, DeserializationContext $context)
    {
        $request = $this->requestStack->getCurrentRequest();

        if ($request && in_array($request->getMethod(), ['PUT', 'PATCH']) && $context->getDepth() == 1) {
            if ($request->attributes->has('id')) {
                $data['id'] = $request->attributes->get('id');
            }
        }

        return $data;
    }

Сan you add such a possibility? Or solve the problem some other way.

MaxBoltik avatar Dec 01 '15 08:12 MaxBoltik

DoctrineObjectConstructor is part of jms/serializer package. Using FOSRest information on this object can not be possible here.

soullivaneuh avatar Mar 15 '16 15:03 soullivaneuh

But I :+1: The request. Actually I have to do this:

/**
 * @param PowerDNSDomain                   $domain
 * @param PowerDNSRecord                   $record
 * @param PowerDNSRecord                   $updatedRecord
 * @param ConstraintViolationListInterface $validationErrors
 *
 * @ParamConverter("updatedRecordData", converter="fos_rest.request_body")
 *
 * @return View
 */
public function putAction(PowerDNSDomain $domain, PowerDNSRecord $record, PowerDNSRecord $updatedRecord, ConstraintViolationListInterface $validationErrors)
{
    if ($validationErrors->count() > 0) {
        return $this->handleBodyValidationErrorsView($validationErrors);
    }

    $record->setName($updatedRecord->getName().'.'.$domain->getName())
           ->setContent($updatedRecord->getContent())
           ->setTtl($updatedRecord->getTtl())
           ->setPrio($updatedRecord->getPrio());

    $this->get('manager.dns')->saveRecord($record);

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

Two parameters and manual copy, that is overkill.

Would be greate to have a system that will merge submitted data with the retrieved object automatically.

Any idea and/or ETA on this?

soullivaneuh avatar Mar 15 '16 15:03 soullivaneuh

Any update on this one?

devantoine avatar Sep 10 '19 14:09 devantoine

Any updates?

kluevandrew avatar Feb 04 '21 22:02 kluevandrew