You are here

function paymentreference_field_validate in Payment 7

Implements hook_field_validate().

File

modules/paymentreference/paymentreference.module, line 205
Hook implementations and general functions.

Code

function paymentreference_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  global $user;
  if ($field['type'] == 'paymentreference') {
    foreach ($items as $delta => $item) {

      // Check if there is a value at all.
      if (empty($item['pid'])) {

        // Check if the value is required.
        if ($instance['required']) {
          $errors[$field['field_name']][$langcode][$delta][] = array(
            'error' => 'paymentreference_missing',
            'message' => t('Payment is required'),
          );
        }

        // There is no value to validate, so stop validation for this item.
        break;
      }

      // Check if this is an existing entity (which means it has an ID).
      $ids = entity_extract_ids($entity_type, $entity);
      if ($ids[0]) {

        // Check if the entity already has a value for this field and if it
        // equals the new value.
        $query = new EntityFieldQuery();
        $count = $query
          ->fieldCondition($field['field_name'], 'pid', $item['pid'])
          ->count()
          ->execute();
        if ($count) {

          // The value hasn't changed, so stop validation for this item.
          break;
        }
      }

      // Check if the selected payment is available for this user and this
      // reference.
      if (paymentreference_load_instance($item['pid'], $user->uid) === FALSE) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'paymentreference_invalid_pid',
          'message' => t('The selected payment does not exist or is not available.'),
        );
      }
    }
  }
}