Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether parameter exists or not in the request

I have this function:

/**
 * @Secure(roles="IS_AUTHENTICATED_FULLY")
 * @Route("/chequearFabricanteDistribuidor", name="chequearFabricanteDistribuidor", condition="request.headers.get('X-Requested-With') == 'XMLHttpRequest'")
 * @Method("GET")
 */

public function chequearFabricanteAction(Request $request)
{
    $em       = $this->getDoctrine()->getManager();
    $entities = $em->getRepository('AppBundle:FabricanteDistribuidor')->findOneBy(
        array( 'nombre' => $request->query->get('fabricante')['nombre'] )
    );

    $response['valid'] = true;

    if ($entities) {
        $response['valid'] = false;
    }

    return new JsonResponse($response);
}

The function needs to be called from two different forms and the only different is the request var that holds the value. In the first form is: $request->query->get('fabricante')['nombre'] while in the second is $request->query->get('distribuidor')['nombre'] so I'm asking if the right way to handle this could be:

if (isset($request->query->get('fabricante'))) 
{
   $nombre = $request->query->get('fabricante')['nombre'];
}
else
{
   $nombre = $request->query->get('distribuidor')['nombre'];
}

Is this right? Exists a better one?

like image 722
ReynierPM Avatar asked Mar 03 '15 03:03

ReynierPM


People also ask

How do you find whether a parameter exist in the request object?

getParameter() is used to return the value of a request parameter passed as query string and posted data which is encoded in the body of request. This method is provided by the interface ServletRequest which returns the value of a request parameter as a String, or null if the parameter does not exist.

What are request parameters?

Request parameters are used to send additional information to the server. A URL contains these parameters. There are two types of parameters: Query Parameter: These are appended to the end of the request URL, Query parameters are appended to the end of the request URL, following '?'

Can a get request have query parameters?

For GET requests, input can be specified only as query parameters, because a GET request cannot have a body. This example shows a GET request on the search resource, with two query parameters in the query string.


1 Answers

As Cerad posted on the responses, you could use:

$request->query->has('distribuidor')
like image 178
Alex Mantaut Avatar answered Sep 17 '22 15:09

Alex Mantaut