1

I have a flag called "Mark as SOLD" which can be flagged only by node author. When he flags it as "Sold", I want the node teaser to print a translatable string t('SOLD'), so that everyone else (even anonymous) can see that this item is now sold.

In my corolla template.php I already have custom function that gives classes to different flags:

    function corolla_preprocess_node(&$variables) {
  $flag = flag_get_flag('sold'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-sold';
  }
$flag = flag_get_flag('withdraw'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-withdraw';   
  }
}

But I know that I need to modify this function and/or node--type.tpl.php to actually print a string t('SOLD').

How can I achieve this?

3

You can set a new variable in your preprocess function and print it in your node--type.tpl.php as follows:

In template.php

function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'YOUR_CONTENT_TYPE') {
    $flag = flag_get_flag('sold');
    if ($flag && $flag->is_flagged($node->nid)) {
      $variables['classes_array'][] = 'node-flag-sold';
      $variables['flagged_text'] = t('Sold');
    }
  }
}

And in your node--YOUR-CONTENT-TYPE.tpl.php, put simply this snippet wherever you want to print the string:

<?php if ($flagged_text): ?>
  <?php print $flagged_text; ?>
<?php endif; ?>

or the same code shorter:

<?php if ($flagged_text) print $flagged_text; ?>

But the first one is better for readability and follows the Drupal's coding standards for template files.

2
  • Thanks.I ended up doing it with just this inmy node--type.tpl ` <?php $flag = flag_get_flag('sold'); if ($flag->is_flagged($node->nid)): ?> <div class="sold"><img src="/css/images/sold3.png" /><div class="sold-text"><?php print t('SOLD') ?></div></div> <?php endif; ?> `
    – drupalina
    Oct 1 '13 at 21:40
  • 1
    This would also work, but you should avoid putting complex logic in your template files. It is always better to prepare your variables for the template in the preprocess functions. Oct 2 '13 at 6:24

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.