Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 how to render custom field

I've added a custom field called 'field_header' to the basic page content type. How do I access this field on the page.tpl.php template so I can display it wherever I want? Ideally I would like to remove it from $content as well. Thanks!

like image 485
martincho Avatar asked Nov 10 '11 02:11

martincho


2 Answers

Don't forget not every page is necessarily a node page so you'd really be better off trying to access this in node.tpl.php, not page.tpl.php.

In node.tpl.php you can render the particular field like this:

echo render($content['field_header']);
hide($content['field_header']); // This line isn't necessary as the field has already been rendered, but I've left it here to show how to hide part of a render array in general.

If you absolutely have to do this in page.tpl.php then you want to implement a preprocess function in your template file to get the variable you need:

function mymodule_preproces_page(&$vars) {
  if ($node = menu_get_object() && $node->type == 'page') {
    $view = node_view($node);
    $vars['my_header'] = render($view['field_header']);
  }
}

Then in page.tpl.php you'll have access to the variable $my_header which will contain your full rendered field.

like image 130
Clive Avatar answered Oct 19 '22 08:10

Clive


In your node.tpl you have to use following code, for example field name : field_header

 <!-- For Showing only custom field's Value Use below code -->
 <h2 class="title"><?php print $node->field_header['und']['0']['value'];?></h2>

 <!-- ========================= OR  ========================= -->

 <!-- For Showing custom field Use below code , which shows custom field's value and title-->
 <h2 class="title"><?php print render(field_view_field('node', $node, 'field_header'));  ?></h2>

 <!-- ========================= OR  ========================= -->

 <h2 class="title"><?php print render($content['field_header']); ?></h2>
like image 25
Chirag Shah Avatar answered Oct 19 '22 07:10

Chirag Shah