[Drupal] How to set destination as the link value in the l(), in case of urls with parameters

| | 1 min read

We can use l() to add links in our Drupal pages. However, while using the output of drupal_get_destination() in the l() as link, it might end up in the wrong functionality. If the drupal_get_destination() returns a url with parameters involved, then using it directly in the l() would cause the link to redirect to the wrong page.

This is because l() processes the link provided, which will result in the decoding and encoding of query parameters inside the link multiple times and will return an invalid path.

To overcome this, we need to parse the URL with the drupal_parse_url() and then use the 'path' part of the result as link and 'query' part as query itself.

Here is a sample code for doing the same:


  $destination = drupal_get_destination();
  $destination = $destination['destination'];
  $url = drupal_parse_url($destination);
  $form['row']['cancel'] = array(
    '#markup' => l(t('Cancel'), $url['path'], array('query' => $url['query'])),
    '#attributes' => array(
      'id' => 'edit-cancel',
      'class' => array('active'),
    ),
  );

If you have any doubts regarding the same, please feel free to get in touch. We are one of the leading Drupal development companies in India. We provide Drupal development offshore services. To know more contact us.