LogicHook to calculate field

@2di7
The hook ‘process_record’ called for each record of a module separately.

Can I suggest an option? You can decide your task if you will use special parametr ‘function’ for a filed. As an example:
I make the field ‘age_years’. The field is calculating the age of contact.

  1. The file - custom/Extension/modules/Contacts/Ext/Vardefs/age_years.php:
<?php
$dictionary['Contact']['fields']['age_years'] = 
  array (
    'name' => 'age_years',
    'vname' => 'LBL_AGE_YEARS',
    'type' => 'int',
    'len' => '3',
    'comment' => '',
    'importable' => true,
    'function' => array(
        'name' => 'get_age_years', 
        'returns' => 'html', 
        'onListView' => 'true',
         'include' => 'custom/modules/Contacts/Contacts_fields_functions.php'
    ),
    'studio' => 'false',
    'source' => 'non-db',
    'inline_edit' => 0,
  );
 ?>
  1. The file -
    custom/modules/Contacts/Contacts_fields_functions.php
<?php
function get_age_years($focus, $field, $value, $view) {
    if ($view == 'ListView') {
        if (isset ($focus['ID']) && !empty($focus['ID'])) {
            $contact = new Contact();
            $contact->retrieve($focus['ID']);
            if (!empty($contact->birthdate)) {
                $age_years=ageYears($contact->birthdate);
            }else{
                $age_years = '-';
            }
            return $age_years;
        } else {
            return "?";
        }
    } elseif ($view == 'DetailView') {
            if (!empty($focus->birthdate)) {
                $age_years=ageYears($focus->birthdate);
            }else{
                $age_years = '-';
            }
            return $age_years;
    }
}
function ageYears ($birthdate){
    global $timedate;
    $birthdate_date = date_create_from_format($timedate->get_date_format(),$birthdate);
    $age_years = date("Y") - $birthdate_date->format("Y");
    if (date("md") < $birthdate_date->format("md")) {
        $age_years = $age_years - 1;
    }
    if ($age_years < 0 || $age_years > 999){
        $age_years = '-';
    }
    return $age_years;
}
2 Likes