Symfony 1 - Helper - UrlHelper

Symfony UrlHelpers add some features to the URL management.

In this Symfony UrlHelpers tutorial, we will see how to use them with some examples.

Let's start with the link_to UrlHelper:

<?php echo link_to(    'My page',
                    'level/index',
                    array('confirm' => 'go?',
                        'absolute' => true,
                        'query_string' => 'foo=32',
                        'anchor' => 'hello',
                        'post' => true,
                    ));
?>

This PHP code will produce this HTML one:

<a onclick="if (confirm('go?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'post'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_csrf_token'); m.setAttribute('value', '233b63974612c39e150408705a579803'); f.appendChild(m);f.submit(); };return false;" href="http://myproject/frontend_dev.php/level?foo=32#hello">My page</a>

It will ask you if you accept to continue or not.
You have to use the right syntax such as "module/action", otherwise this will not work correctly.
As you can see, it will create a lot of JavaScript code.
You will have less code if you remove the post option and will can add the popup option and set it to true to open a new window when clicking.

The button_to UrlHelper is exactly the same as the link_to one.
You can use the same options.

There also the link_to_if that creates the link only if the condition is true:

echo link_to_if($user->isAdministrator(), 'Delete this page', 'my_module/my_action');

For the mail_to UrlHelper, it helps to correctly format the famous mailto link:

echo mail_to('webmaster@example.com', 'send us an email', array('encode' => true));

And for finish, the url_for UrlHelper. It will create a link with the routing rule passed as argument or directly with the "module/action" duo. An absolute path can be passed as well:

echo url_for('my_module/my_action');
=> /path/to/my/action
echo url_for('@my_rule');
=> /path/to/my/action
echo url_for('@my_rule', true);
=> http://myapp.example.com/path/to/my/action

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.