Search code examples
phpnode.jssymfonyrequestput

PUT/PATCH request with not allowed fields


I have an application which i'm writing in Symfony 4 framework. I have a PUT/PATCH request which might contain bad request fields. For example Entities user shouldn't contain fields description. In such sitaution I'd like to block request and return bad request response . I wonder what's the best way to do it in Symfony 4?

In node.js implenentation such problem looks like below: 

router.patch('/tasks/:id', async (req, res) => {
    const updates = Object.keys(req.body)
    // allowed fields
    const allowedUpdates = ['description', 'completed']
    // check if there are bad fields
    const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
    if (!isValidOperation) {
        return res.status(400).send({ error: 'Invalid updates!' })
    }
    /*
    some response code
    /*
})

How can I do something similar in Symfony 4 framework?


Solution

  • first, by default when option allow_extra_fields is set to false (default), form with extra fields would not validate, more about this setting: https://symfony.com/doc/current/reference/forms/types/form.html#allow-extra-fields

    next you can check if $form->getExtraData() is an empty array, this means that there are no extra fields

    if extra field were to be found to get bad request response you can either:

    throw new BadRequestHttpException();
    

    or without exception:

    return $this->json(['error' => 'your error'], Response::HTTP_BAD_REQUEST);
    
    return new JsonResponse(['error' => 'your error', Response::HTTP_BAD_REQUEST]);