You are here

function farm_flags_action in farmOS 7

Action function for farm_flags_action.

Assigns a log to one or more people.

Parameters

$entity: The entity object.

array $context: Array with parameters for this action.

File

modules/farm/farm_flags/farm_flags.module, line 229
Farm flags module.

Code

function farm_flags_action($entity, $context = array()) {

  // If the operation is invalid, bail.
  if (!in_array($context['operation'], array(
    'append',
    'replace',
  ))) {
    drupal_set_message(t('Invalid operation.'));
    return;
  }

  // If the operation is 'append', and there are no flags, bail.
  if ($context['operation'] == 'append' && empty($context['flags'])) {
    return;
  }

  // Create an entity wrapper object.
  $entity_wrapper = entity_metadata_wrapper($context['entity_type'], $entity);

  // If the flags field doesn't exist, bail.
  if (!isset($entity_wrapper->field_farm_flags)) {
    return;
  }

  // Keep track of flags that are already assigned.
  $existing_flags = array();

  // If we are appending, load existing flags.
  if ($context['operation'] == 'append' && !empty($entity_wrapper->field_farm_flags)) {
    foreach ($entity_wrapper->field_farm_flags
      ->getIterator() as $delta => $flag) {
      $existing_flags[] = $flag
        ->value();
    }
  }
  elseif ($context['operation'] == 'replace') {
    $entity_wrapper->field_farm_flags = array();
  }

  // Assume that we are not going to save the entity.
  $save = FALSE;

  // Iterate through the flags.
  foreach ($context['flags'] as $flag) {

    // If the flag is already referenced in the entity, skip it.
    if (in_array($flag, $existing_flags)) {
      continue;
    }

    // Add the flag to the array of existing flags so we don't accidentally
    // add the same one more than once. Shouldn't happen, but be defensive.
    $existing_flags[] = $flag;

    // Add the flag to the entity's flags field.
    $entity_wrapper->field_farm_flags[] = $flag;

    // We will save the entity.
    $save = TRUE;
  }

  // If we should save the entity, then save it.
  if ($save) {
    $entity_wrapper
      ->save();
  }
}