Kai Qing
Kai Qing

Reputation: 18843

Render individual page fields once only in Drupal 7 page.tpl.php

So I gather I can render a specific element of the $page['content'] array like so...

<?php print render(field_view_field('node', $node, 'field_image')); ?>

Where out of the box this will render the element as expected with standard defaults. Ok, so how can I make sure that hand plucked element no longer renders in the <?php print render($page['content']) ?> call later?

Why do I want something dumb like this? Because every page WILL have a header image with a few css tricks for overlays, design and such. But not every page will have attachments, links, and so on... you know, things that are additional fields in the page. So I can't manually print out each field since I don't know how many or what else there is. All I know for sure is the field_image I'm printing above is wrapped in a ton of markup for styling and must be done this way. Same for a few other fields.

Basically I'm looking for a way to unset the field immediately after use.

Does anyone know how to achieve this? I'd rather not make a view or a custom block that displays for specific pages. I eventually have to hand this over to a client who will not be able to wrap their heads around a single page being administered over many places in the CMS.

Upvotes: 1

Views: 2319

Answers (2)

jordanmt
jordanmt

Reputation: 116

You can in fact control the display of individual fields for content types in Drupal without having to resort to the function you've used.

Since you know in advance which field(s) you want to suppress, you can turn off its display in the content type settings.

In Drupal 7, see:
Admin >> Structure >> Content types >> your content type >> Manage display
Under "Format" select < Hidden > for the field that you want to omit.

This will prevent the field contents from being displayed within the usual node contents, but field_view_field will naturally still work.

You can also fine-tune your field formats based on different view modes, e.g. choose to display the field within teasers but not in full content.

Upvotes: 3

Kai Qing
Kai Qing

Reputation: 18843

Looks like this will work:

<?php
print render(field_view_field('node', $node, 'field_image'));
MYTHEME_remove_item($page['content'], 'field_image');
?>

and in template.php file I made this function:

function MYTHEME_remove_item(&$content, $field)
{
    foreach($content['system_main']['nodes'] AS $key => $val){
        unset($content['system_main']['nodes'][$key][$field]);
    }
}

This is ridiculous, in my opinion. I would think a system as robust as drupal would have a solution for something like this. If anyone knows the proper way to do this I will gladly mark them as correct. In the meantime, for others facing similar situations, this worked for me.

Upvotes: 0

Related Questions