Drupal Field Importance, how to arbitrarily score entities

Submitted by swim on Fri, 01/10/2014 - 04:16

Before I dive into the method behind this module let me explain the use case. Our client had very little time and required at first a simple way to attribute a score (numeric value) per entity type field instance. The total score for the submitted entity is then calculated from each field score where a value has been entered. Finally these are displayed in an administrative view with a comparison to the total amount of points possible for that entity.

Attributing a numeric score to a field on an entity type instance basis is a little tricky. First off we need to be aware of three types of information which will help store & retrieve our scores. Field name, entity type & the bundle; in a very basic sense this means each field per bundle will have a unique score; or the ability to have one. The use case I had was very simplistic and would only range over one or maybe two entity types; we used entityforms to generate a total score based on the submitted field values.

The total score would of course be the sum of all the fields (with values) scores for that entity.

Currently the module allows the administrator to associate one field value per one score, for multiple values these are ordered and linked sequentially.


/**
 * Recalc field instance total score, do some paranoid checks.
 */
function field_importance_recalc_instance_total($entity_type, $field_name, $bundle) {
  module_load_include('inc', 'field_importance', 'field_importance.fields');

  // After any score is updated recalc the total for this instance.
  $score = _field_importance_return_instance_scores($bundle);
  $instance_info = field_info_instance($entity_type, $field_name, $bundle);

  if (!$instance_info) {
    if (!field_read_field($field_name)) {
      // Something has gone wrong, recreate our total field.
      $field_data = array(
        'field_name' => $field_name,
        'type' => 'number_integer',
        'cadinality' => 1,
      );
      $field = field_create_field($field_data);
    }

    // If no instance is found for our total score field, create it.
    $field_instance = array(
      'field_name' => $field_name,
      'instance_field_importance_total' => array(
        'field_name' => $field_name,
        'label' => 'Total Field Score',
      ),
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'default_value' => array(
        'value' => array_sum($score),
      ),
    );

    field_create_instance($field_instance);
  }
  else {
    // Update default value to set instance total.
    $instance_info['default_value'][0]['value'] = array_sum($score);
    field_update_instance($instance_info);
  }
}

Here is an example of what our view looked like in the end using entity forms.

While very ad hoc I hope this helps someone.

Sandbox link.