I want to calculate the average of two fields of type number, and have this average in a third field to make different sorts in views.

For example:

  • I have a content X which has as fields: A, with the number 6, B, with the number 8;
  • I would like a field C, in which would be automatically calculated the average, namely 7;
  • The field C would then allow me to do different sorting with views.

Do you know what is the best approach to do this (drupal 8 or 7) ?


You may work with this approach.
The following code snippet for drupal 7.

  1. Create field C of type number.
  2. Hide the field C in add/edit content type form.

     * Implements hook_form_alter().
    function yourModule_form_alter(&$form, &$form_state, $form_id) {
      if ($form_id == 'CONTENT_TYPE_NAME_node_form'){
        $form['field_c']['#access'] = FALSE;

  1. Update the field programmatically by implementing hook_node_presave like the following:

 * Implements hook_node_presave().
function yourModule_node_presave($node) {
  $value_a = isset($node->field_a[LANGUAGE_NONE][0]['value']) ? $node->field_a[LANGUAGE_NONE][0]['value'] : 0;
  $value_b = isset($node->field_a[LANGUAGE_NONE][0]['value']) ? $node->field_a[LANGUAGE_NONE][0]['value'] : 1;
  $average = (int) ($value_a / $value_b);
  $node->field_c[LANGUAGE_NONE][0]['value'] = $average;
  • Thanks a lot berramou for your answer. I will test it. In case, do you know the approach for drupal 8? – Hgfdsoiu Jan 21 '19 at 21: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.