2

I am building a drupal site. I have 2 fields: "prep time" and "cook time". Both fields are:
FIELD TYPE = Integer
WIDGET = Time Period

I need to sum up the two fields to one field (total time), and present it with widget of Time period, Or at least present it in time format ("2 hours 35 min").

Question Update (3/12/2013): In addition, I need to present the date with ISO format in the HTML code (datetime="PT3H45M"). After I am using the Computed Field module, I don't know how to present the computed number as time format ("2 hours 35 min") and add the ISO format in the HTML code. as you will see below, I created a "field--field_preptime.tpl.php" that works great for the "prep time" and the "cook time", but when I am passing the computed value, the out put is wrong - as I don't see the the time format correctly, and the iso foramt in the html code is also wrong.

can someone help me fix it?


here is how I created the prep time and cook time:
I created the following field override template file called: "field--field_preptime.tpl.php"

<?php
function time_to_iso8601_duration($time) { 
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );

    $str = "P";
    $istime = false;

    foreach ($units as $unitName => &$unit) {
        $quot  = intval($time / $unit);
        $time -= $quot * $unit;
        $unit  = $quot;
        if ($unit > 0) {
            if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
                $str .= "T";
                $istime = true;
            }
            $str .= strval($unit) . $unitName;
        }
    }

    return $str;
}
 ?>


<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>    
    <?php foreach ($items as $delta => $item): ?>
    <?php $time = strtotime(render($item), 0); ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>></div>
          <time datetime=<?php print time_to_iso8601_duration($time); ?> itemprop="prepTime"><?php print render($item); ?></time>
    <?php endforeach; ?>
  </div>
</div>

The Output of "prep time", when I am viewing in the "view source" on the relevant page (I don't know how to do the same for the calculated value of "total time"):

<div class="field field-name-field-preptime field-type-number-integer field-label-hidden">
    <div id="md11" class="field-items">    
              <div itemprop="prepTime" class="field-item even"></div>
          <time datetime="PT3H45M" itemprop="prepTime">3 hours 45 min</time>
      </div>
</div>

Thanks.


UPDATE 1/10/2014:
I couldn't do it without using computed fields. when I tried, I got an error: "Notice: Undefined variable: field_cooktime in include() (line 54 of D:\XXX\field--field_totaltime.tpl.php). I got the same error for preptime. I guess that is the reason the output is always 0 sec for total time, even though I put the totaltime field after the preptime and the cooktime fields.

How can I get the value of two fields in my override template, and then Sum up?

Thanks.

2

Re your update 2013-12-03. I've absolutely no idea why your using the Computed field module for this - that seems like a completely unnecessay complication.

As I've already pointed out by me on 2013-11-15, to sum up 2 fields of integer in PHP, you just add them together using the + operator. And to display in a suitable format consisting of hours and minutes, you can use the PHP function format_interval to turn the number of seconds into a suitable string.

So you should have something like this near the beginning of field--field-totaltime.tpl.php (i.e. after the opening comment).

<?php
function time_to_iso8601_duration($time) {

  // Lot of PHP code not shown for brevity

  return $str;
}
?>
<?php
$prep_time = ($element['#object']->field_prep_time['und'][0]['value']);
$cook_time = ($element['#object']->field_cook_time['und'][0]['value']);
$total_time = $prep_time + $cook_time;
$totaltimestring = format_interval($total_time, 2);
?>

is all you need. Below this, you put the template to render the total time.

The template for total time should be very similar to the template you already use for prep time and cook time. Example:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>    
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>></div>
          <time datetime=<?php print time_to_iso8601_duration($total_time); ?> itemprop="totalTime"><?php print $totaltimestring; ?></time>
    <?php endforeach; ?>
  </div>
</div>
|improve this answer|||||
  • Thank you very much for your help. One thing I did not understand - where do I add the the short php code of the calculating? at the top of the file "field--field_totaltime.tpl.php"? I am sorry for all the questions.. – EB84 Dec 3 '13 at 11:32
  • OK, so I succeed on doing that, and the result is fine, but I have warning regarding the computed filed module. the reason I used the computed field module is because I tried to do it without a computed field, but the "total time" field never appeared. I think it's happen because I put all the code in the file "field--field_totaltime.tpl". when the total time field (in panel page) was supposed to be printed, it was assumed as empty (since it's really empty, because the user is not filling this field). even printing text from tpl didn't appear. can we fix it? can we use only the tpl.php file? – EB84 Dec 3 '13 at 19:39
  • Hey again, unfortunately, I can't seems to figure it out, and do it correctly. I am getting errors that "Notice: Undefined variable: field_cooktime in include() (line 54 of D:\XXX\field--field_totaltime.tpl.php). I get the same error for preptime. I guess that is the reason the output is always 0 sec for total time, even though I put the totaltime field after the preptime and the cooktime fields. Do you think you can help me figure it out? – EB84 Jan 10 '14 at 16:52
2

One way to do this is the Computed Field module, which will allow you to use PHP to perform calculations.

To use this, you could add a field, Total time, of type Computed Field. Then you could write some PHP code to calculate the value for Total time based on the other two fields. This way, every time the node is updated, the correct calculation value will be saved in the Total Time field.

If you need to customize the display output, the Computed Field module allows you to optionally add PHP code to output the field for display with custom formatting as well.

But

Please note the warning on the module's page:

This module is intended to be used by PHP developers to insert & execute PHP code on a Drupal website. It does not provide a macro interface, a code builder or anything other than insert your working code here into this text area. You need to have a good working knowledge of PHP and the Drupal API to use this module. To get the best results with this module, pre-test your PHP code in the Body field of a Page in Drupal.

|improve this answer|||||
  • hey, I succeed to use this module and calculate the integer to total time. but, it's store that in seconds, and the out put is 18000 (sec) instead of "5 hours". Here, I don't know how to transform the data to be in hours and display it as "5 hours". Can you help me do that? – EB84 Nov 14 '13 at 9:06
  • If you want it in hours, can't you just divide by 3600? And if you need to round, just use PHP's round function: php.net/manual/en/function.round.php – Patrick Kenny Nov 14 '13 at 11:11
  • I want it in Hours and minutes. the output (and the data can be: "3 hours 45 minutes" or "2 hours 10 minutes" and of course only "4 hours". is there a PHP function for dates? how the date module does that? – EB84 Nov 14 '13 at 11:48
  • Yes, you can use the date function: php.net/manual/en/function.date.php – Patrick Kenny Nov 14 '13 at 13:04
  • I tried to use this solution, But couldn't figure out how to accomplish my goal. couldn't get a right result of presenting correct time period and the ISO format in the html code. Can you maybe sugget how to use this function in my tpl.php file (attached in the question)? – EB84 Dec 3 '13 at 10: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.