3

I am new to Drupal and am realising that there are a number of ways to perform even the most basic task but it is hard to know which way is right.

When rendering fields from a custom content type which of the following ways is correct/most efficient/safest way or am I wrong and there is another even better way?

Option 1 - this way seems a little verbose but I have read in a number of places that this is the correct way to render individual fields.:

<?php $included = field_view_field( 'node', $node, 'field_what_s_included', array('label' => 'hidden') );
            print render($included);
        ?>

Option 2 - This way seems much neater and is also written about a lot:

<?php print render($content['field_what_s_included']; ?>

Thanks for clarifying this for me.

James

2

Option 2 is the preferred option.

Use the default node.tpl.php as a reference.

You can see it uses the hide() function to hide fields it doesn't want to render and the render() function to render fields.

This is because all the processing you are doing in option 1 with field_view_field() has already been done and is ready to render, so you don't need to do it again.

I recommend doing some reading on overriding themeable output, which involves overriding markup with theme functions and template files.

  • Hey Rooby, thanks for your speedy reply. That clears things up for me. What situation would I use option 1? Thanks again. – jim_at_jibba Feb 23 '15 at 23:26
  • @jim_at_jibba You would use that for example in a preprocess function in order to fill the $content variable with renderable data. – berliner Feb 24 '15 at 0:10
  • Some use cases would be if you want the output of a field and it isn't already available to you, or if you want to render a field using a different display mode than what has already been generated. – rooby Feb 24 '15 at 0:10
  • Perfect, thank you both very much. I can see how Drupal is very powerful but it can be pretty confusing at times. – jim_at_jibba Feb 24 '15 at 0:21
  • @berliner: in this case though you generally wouldn't use the preprocess function to call field_view_field() to populate content because that's already been done for node fields. – rooby Feb 24 '15 at 0:53

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.