You are here

function mvf_field_validate in Measured Value Field 7

Implements hook_field_validate().

File

./mvf.module, line 405
Define a field type of measured value.

Code

function mvf_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($field['settings']['meta_info'] as $subfield => $meta_info) {
    $mocked_field = mvf_field_mockup($field, $subfield);
    $mocked_instance = mvf_instance_mockup($field, $instance, $subfield);
    $function = $mocked_field['module'] . '_field_validate';
    if (function_exists($function)) {
      $function($entity_type, $entity, $mocked_field, $mocked_instance, $langcode, $items, $errors);
    }
  }

  // Validating min and max values on our own.
  foreach ($items as $delta => $item) {

    // If any reasonable value has been submitted.
    if (!module_invoke('mvf', 'field_is_empty', $item, $field)) {
      $item_unit = units_unit_load($item[mvf_subfield_to_column('unit')]);
      $item_value = $item[mvf_subfield_to_column('value')];

      // Checking for minimal value condition.
      if (!module_invoke('mvf', 'field_is_empty', $instance['settings']['mvf']['min'], $field)) {
        $min = $instance['settings']['mvf']['min'];
        $min_unit = units_unit_load($min[mvf_subfield_to_column('unit')]);
        $min_value = units_convert($min[mvf_subfield_to_column('value')], $min_unit->machine_name, $item_unit->machine_name);
        if ($item_value < $min_value) {
          $errors[$field['field_name']][$langcode][$delta][] = array(
            'error' => 'mvf_min',
            'message' => t('%name: the value may be no less than %min_value %min_unit.', array(
              '%name' => $instance['label'],
              '%min_value' => $min[mvf_subfield_to_column('value')],
              '%min_unit' => entity_label('units_unit', $min_unit),
            )),
          );
        }
      }

      // Checking for maximum value condition.
      if (!module_invoke('mvf', 'field_is_empty', $instance['settings']['mvf']['max'], $field)) {
        $max = $instance['settings']['mvf']['max'];
        $max_unit = units_unit_load($max[mvf_subfield_to_column('unit')]);
        $max_value = units_convert($max[mvf_subfield_to_column('value')], $max_unit->machine_name, $item_unit->machine_name);
        if ($item_value > $max_value) {
          $errors[$field['field_name']][$langcode][$delta][] = array(
            'error' => 'mvf_max',
            'message' => t('%name: the value may be no greater than %max_value %max_unit.', array(
              '%name' => $instance['label'],
              '%max_value' => $max[mvf_subfield_to_column('value')],
              '%max_unit' => entity_label('units_unit', $max_unit),
            )),
          );
        }
      }
    }
  }
}