How to pass parameters in a Symfony route?

Member

by dedrick , in category: PHP Frameworks , a year ago

How to pass parameters in a Symfony route?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , a year ago

@dedrick 

In Symfony, you can pass parameters in a route using placeholders in the route path. These placeholders are defined by enclosing a variable name with curly braces ({}) and can be used to capture and extract values from the URL.


Here's an example of a route with a placeholder for a product_id parameter:

1
2
3
4
5
6
7
8
9
use SymfonyComponentRoutingAnnotationRoute;

/**
 * @Route("/product/{product_id}")
 */
public function showProduct($product_id)
{
    // ...
}


In this example, the {product_id} placeholder is used to capture a value from the URL and pass it as an argument to the showProduct method.


You can also specify requirements and defaults for a parameter by adding a regular expression pattern and a default value inside the placeholder. Here's an example:

1
2
3
4
5
6
7
/**
 * @Route("/product/{product_id<d+>}", defaults={"product_id"=1})
 */
public function showProduct($product_id)
{
    // ...
}


In this example, the product_id parameter is restricted to only accept numeric digits (d+) and a default value of 1 is provided if the parameter is not present in the URL.


To generate a URL with parameters, you can use the path function in Twig or the generateUrl method in a controller:

1
<a href="{{ path('product_show', {'product_id': 123}) }}">View product</a>


1
$url = $this->generateUrl('product_show', ['product_id' => 123]);


In both cases, the product_id parameter is passed as an associative array to the function or method, and the URL is generated with the correct value.