2

Is it possible to render a field on a node twice with different field formatters?

I have a content type with the a field type "Email". This field needs to give me as output:

  • A link to the default email form ("Email contact form")
  • The original input in the field ("Default email link")

I have put the field formats in quotes above.

Does anyone have a clue on how to do this, or if this is even possible?

3 Answers 3

1

Here is the correct way to do what you are after. See field_view_field for some documentation on rendering a field.

  • You will need to replace "HOOK" with the name of your function name.
  • You will need to add the correct settings for the display types (can be added to the display types array to keep the data together).
  • The settings data can be found in the module that defines the field formatter. Looking through the field formatter definitions is probably the easiest way to find the correct settings for the display you are trying to achieve.
  • You will need to ensure your field is called "field_email" or update the code.

Code:

<?php

function HOOK_preprocess_node(&$vars) {

    $display_types = array(
        'email_contact',
        'email_default',
    );

    foreach ($display_types as $type) {
        $vars['content']['field_email_' . $type] = field_view_field(
            'node',
            $vars['node'],
            'field_email',
            array(
                'type' => $type,
                'settings' => array(...),
                'label' => 'above',
            )
        );
    }
}
2

You can output the field twice, using different formatters in the template

e.g, in node.tpl.php something like:

$output = array();
$email = field_get_items('node', $node, 'field_email');
$output[] = field_view_value('node', $node, 'field_email', $email[0], array(
            'type' => 'email_contact'));
$output[] = field_view_value('node', $node, 'field_email', $email[0],array(
            'type' => 'email_default'));
print implode(PHP_EOL, $output);
7
  • As a string the fifth param is not a formatter but a view mode.
    – Sam Becker
    Commented May 15, 2013 at 1:09
  • Yes, it may need a display array instead. Commented May 15, 2013 at 1:18
  • Hi thx for trying to help me with this. I would like to try your answer but can't figure out where to put it... Could you please explain it a bit more. Commented May 15, 2013 at 10:04
  • @JimmyRaets you could put the code in node.tpl.php Commented May 15, 2013 at 23:15
  • 1
    Never put such code in a template file. There are the preprocess functions for that.
    – avpaderno
    Commented Jun 18, 2015 at 10:12
0

Not in core ways. You can, however, render field twice in tpl.php, but it will not give you two formatters.

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.