7

I always tend to forget these built-in Symfony functions for making links.

Ijas Ameenudeen
  • 9,069
  • 3
  • 41
  • 54
andyuk
  • 38,118
  • 16
  • 52
  • 52

4 Answers4

9

If your goal is to have user-friendly URLs throughout your application, use the following approach:

1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager):

recent_questions:
   url:    questions/recent/:page
   param:  { module: questions, action: recent, page: 1 }

2) Once the routing rule is set, use the url_for() helper in your template to format outgoing URLs.

<a href="<?php echo url_for('questions/recent?page=1') ?>">Recent Questions</a>

In this example, the following URL will be constructed: http://myapp/questions/recent/1.html.

3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the :/page portion of the URL) will become request parameters.

You can also use the link_to() helper to output a URL without using the HTML <a> tag.

jamz
  • 4,991
  • 4
  • 24
  • 19
  • Just a nit, but the URL will not be constructed with the .html part unless the application is configured to do so (by default it is not). – Nathan Strong Oct 10 '08 at 04:50
1

This advice is for symfony 1.0. It probably will work for later versions.

Within your sfAction class:

string genUrl($parameters = array(), $absolute = false)

eg. $this->getController()->genUrl('yourmodule/youraction?key=value&key2=value', true);

In a template:

This will generate a normal link.

string link_to($name, $internal_uri, $options = array());

eg. link_to('My link name', 'yourmodule/youraction?key=value&key2=value');

andyuk
  • 38,118
  • 16
  • 52
  • 52
0

In addition, if you actually want a query string with that url, you use this:

link_to('My link name', 'yourmodule/youraction?key=value&key2=value',array('query_string'=>'page=2'));

Otherwise, it's going to try to route it as part of the url and likely break your action.

thrashr888
  • 1,477
  • 1
  • 17
  • 24
0

You can generate URL directly without define the rule first.

If you want to generate URL in the actions, you can use generateUrl() helper:

$this->generateUrl('default', array('module'=>'[ModuleName]','action'=>'[ActionName]'))

If you want to generate URL in the templates, you can use url_for() helper:

url_for('[ModuleName]/[ActionName]', $absolute)

set $absolute as true/false, dont forget to use echo if you want to display it.

But if you want to make a link (something like <a href=""></a>), link_to() helper will do.

priyabagus
  • 2,718
  • 1
  • 14
  • 10