1

I have a content type that, on the node page, displays taxonomy term fields, which in turn link to the automatically generated taxonomy term view for that term.

I would like to overwrite the output of these links, which I have attempted to do in the code below.

The problem is that the URL comes out malformed as: /our-work%3Ftid%3D4 rather than /our-work?tid=4. Note that the argument 4 is just an example.

What could be the solution here? Some thoughts:

  • Am I using the right hook?
  • urlencode() doesn't seem to work here.
  • Using Drupal's l() function seems to output HTML, not a processed URL.
  • Using Drupal's url() function doesn't seem to work either, I get the same output when I build the options array, etc.

    function ep3_misc_node_view_alter(&$build) {
        if ($build['#bundle'] == 'work') {
        // We cycle through this array for just integer indexes, since there are also string indices.
            for ($i = 0; isset($build['field_tags'][$i]); $i++) {
                $tid = $build['field_tags'][$i]['#options']['entity']->tid;     
                $build['field_tags'][$i]['#href'] = check_plain('our-work?tid=') . $tid;
            }
        }
    }
    
  • 1
    Why would not url('our-work', array('query' => array('tid'=> $tid))) work? – kiamlaluno Sep 21 '12 at 8:51
  • Ah, apologies - that does produce the correct URL (although my browser misleads me when I hover the link). The only issue is that the URL is absolute, how can I append the site domain to the start? I thought it was relative by default. – njp Sep 21 '12 at 9:20
  • Do you want the URL to be absolute? – kiamlaluno Sep 21 '12 at 9:23
  • Nevermind, I just got confused. Your method is correct, I just needed to set absolute = TRUE. I will accept your answer if you wish to put it below :) – njp Sep 21 '12 at 9:28
3

The function that you should use is url(). If you want to output an absolute URL you should use the following code:

function ep3_misc_node_view_alter(&$build) {
  if ($build['#bundle'] == 'work') {
    for ($i = 0; isset($build['field_tags'][$i]); $i++) {
      $tid = $build['field_tags'][$i]['#options']['entity']->tid;     
      $build['field_tags'][$i]['#href'] = url('our-work', array('absolute' => TRUE, 'query' => array('tid'=> $tid)));
    }
  }
}

If you don't want an absolute URL, replace the call to url() with the following one:

url('our-work', array('query' => array('tid'=> $tid)))

check_plain() is never used to output a URL; in fact, url() doesn't use it.

| improve this answer | |
  • and don't trust what your browser shows when you hover a link. %20 and most links will be decoded for your reading ease. – AyeshK Sep 21 '12 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.