You are here

function farm_livestock_birth_log_form_validate in farmOS 7

Validate handler for the birth log form.

Parameters

array $form: The form array.

array $form_state: The form state array.

1 string reference to 'farm_livestock_birth_log_form_validate'
farm_livestock_form_log_form_alter in modules/farm/farm_livestock/farm_livestock.module
Implements hook_form_FORM_ID_alter().

File

modules/farm/farm_livestock/farm_livestock.module, line 447

Code

function farm_livestock_birth_log_form_validate(array $form, array &$form_state) {

  // Get the log ID (if available).
  $log_id = 0;
  if (!empty($form_state['values']['log']->id)) {
    $log_id = $form_state['values']['log']->id;
  }

  // Get the referenced assets.
  $asset_ids = array();
  if (!empty($form_state['values']['field_farm_asset'][LANGUAGE_NONE])) {
    foreach ($form_state['values']['field_farm_asset'][LANGUAGE_NONE] as $asset_reference) {
      if (empty($asset_reference['target_id'])) {
        continue;
      }
      $asset_ids[] = $asset_reference['target_id'];
    }
  }

  // If there are assets, look up birth logs that reference them.
  if (!empty($asset_ids)) {

    // Perform an entity field query to find logs that reference the assets.
    $query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type', 'log')
      ->entityCondition('bundle', 'farm_birth')
      ->propertyCondition('id', $log_id, '!=')
      ->fieldCondition('field_farm_asset', 'target_id', $asset_ids);
    $result = $query
      ->execute();
    if (isset($result['log'])) {
      $log_ids = array_keys($result['log']);
      $logs = entity_load('log', $log_ids);
    }

    // If matching logs were found, set form error(s).
    if (!empty($logs)) {
      foreach ($logs as $log) {
        $log_label = entity_label('log', $log);
        $log_uri = entity_uri('log', $log);
        form_set_error('field_farm_asset', t('The existing birth log <a href="@log_path">%log_name</a> already references one or more of the children. More than one birth log cannot reference the same child.', array(
          '%child_name' => '',
          '@log_path' => url($log_uri['path']),
          '%log_name' => $log_label,
        )));
      }
    }
  }
}