0

How do I print the output of a field as a link on node.tpl.php? I'm able to print the raw output of a field using this:

<?php $display = array('label' => 'hidden');
$view = field_view_field('node', $node, 'field_podcast_url', $display);
print drupal_render($view);?><?php $display = array('label' => 'hidden');?>

The problem occurs when I try to make it as a link using this method:

<?php $display = array('label' => 'hidden'); 
$view = field_view_field('node', $node, 'field_podcast_url', $display); ?>
<a href="<?php print drupal_render($view); ?>">text</a>

The output looks like this:

http://www.podtrac.com/pts/redirect.mp3/feeds.soundcloud.com/stream/211653270-scott-johnson-27-tms-846.mp3 ">text

and the link points to this:

http://controldaily.dev/<div class=

I've looked around at solving this issue and can't find a solution. Anything else just shows nothing.

1 Answer 1

1

This looks like it's happening because you are trying to input the entire rendered field (including styling) into the links href.

As per the description:

The field_view_value() function can be used to output a single formatted field value, without label or wrapping field markup.

To use field_view_field, try something like:

if($node->type == 'article')
{
    $link_field = field_view_field('node', $node, 'field_href');
    print l(t($link_field['#items'][0]['safe_value']), $link_field['#items'][0]['safe_value']);
}

This example assumes a node of article type, and a field with a machine name field_href. running it through l() (despite using the safe value) will help ensure it is sanitised properly before being output.

You can also take a look at the Link field module:

The link module can be count to the top 50 modules in Drupal installations and provides a standard custom content field for links. With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

2
  • This is a great start but I need to pass this through a media player so how do I print the output like <a href="$output">? Commented Jul 6, 2015 at 2:01
  • the l() function produces it for you? do you mean you need a specific id or class? there is no functional difference between manually creating the tag with <a> and the l() except l() sanitises the output first
    – Geoff
    Commented Jul 6, 2015 at 2:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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