0

I am writing a field override tpl file, in which I want to sum up two INT fields to one INT field. In the file I tried the code:

$sum = $field_one + $field_two;

The problem is that I get an a notice that Drupal doesn't know what are these variable ($field_one, $field_two). I tried using "field_get_item", but I didn't succeed. I guess I use it wrong.. Can someone help me get these two fields to my override .tpl file.

How can I get these fields and calculate?

Thanks.

1 Answer 1

2

If you look at the comment in the beginning of the template file you're overriding, you should notice that it lists the variables available for any override code.

For instance, in field.tpl.php (used as starting point for overrding field templates), you should see the following line inside that comment:

* - $element['#object']: The entity to which the field is attached.

This gives you the name of the global ($element['#object']) to examine to look for the values of the fields.

Now, you need to look "inside" this object to figure out how to access the values of these fields. To do so, the Devel module is what you need, so install and enable this for your (test) site.

Then put the following near the top of your template override file:

<?php dpm($element['#object']); ?>

When you look at the page again as administrator (clear cache and reload if necessary), there should be a Krumo accordion in the message area that expands this object. Expanding it will tell you how to get to the value of each field present in the entity. For instance, it may tell you that the value of field_one is $element['#object']->field_one['und'][0]['value'].

Now, you should be able to extract and add the fields, e.g.:

<?php
$field_one = $element['#object']->field_one['und'][0]['value'];
$field_two = $element['#object']->field_two['und'][0]['value'];
$sum = $field_one + $field_two;
?>

Disable Devel and delete the call to dpm() on a production site.

1
  • Thank you so much. fantastic Answer! I really appreciate your answer. problem solved.
    – EB84
    Commented Jan 12, 2014 at 8:53

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.