Symfony - validate empty query parameter values Symfony - validate empty query parameter values symfony symfony

Symfony - validate empty query parameter values


If you want to force your parameters to be checked, you can change config file as explained in the documentation, Here is the sample:

fos_rest: param_fetcher_listener: force

Then you can set other options like strict, nullable accordingly.

See more details here :

http://symfony.com/doc/current/bundles/FOSRestBundle/configuration-reference.html (archive.org)https://symfony.com/doc/3.x/bundles/FOSRestBundle/index.html#config-referencehttps://symfony.com/doc/3.x/bundles/FOSRestBundle/annotations-reference.html


Just use the allowBlank option of the QueryParam. In your case you would set the allowBlank to false to get the expected behaviour:

The allowBlank option is NOT YET in the FOSRestBundle, but I provided a patch to the FOSRestBundle which has a good chance to land in the next release, version 1.5.0 of the bundle.

This is how your Controller would look like:

/** * Get a single comment. * * @Annotations\QueryParam(name="dealId", requirements="\d+", strict=true, description="The deal the comments belong to.") * @Annotations\QueryParam(name="source", requirements="(forum|blog)", strict=true, allowBlank=false, description="The source of the comments.") * * @Annotations\View() * * @Annotations\Get("/comments/{id}", requirements={"id" = "\d+"}) * */public function getCommentAction(Request $request, ParamFetcherInterface $paramFetcher, $id){    $dealId = $paramFetcher->get('dealId');    $source = $paramFetcher->get('source'); }


The tricky part is allowing source and dealId to be empty but I think it's possible by adding these parameters to your route (so they must be specified in order to access the controller) and using a string prefix for each parameter (i.e. dealid_ and source_), so it's possible to specify an empty value.

You'll also need to modify the regex requirements to allow empty values.

/** * Get a single comment. * * @Annotations\View() * @Annotations\Get("/comments/{id}/dealid_{dealId}/source_{source}",  *    requirements={"id" = "\d+", "dealId" = "\d*", "source" = "(forum|blog)*"}) */public function getCommentAction(Request $request,     ParamFetcherInterface $paramFetcher, $id, $dealId, $source) {    return [ 'id' => $id, 'dealId' => $dealId, 'source' => $source ];}