You are here

function domain_entity_entity_presave in Domain Access Entity 7

Implements hook_entity_presave().

File

./domain_entity.module, line 197
Defines field (e.g. domain_entity) for entities, and access query alter.

Code

function domain_entity_entity_presave($entity, $type) {

  // Check if it's an allowed entity types:
  $allowed_entity_types = domain_entity_allowed_entity_types();
  if (!in_array($type, array_keys($allowed_entity_types))) {
    return;
  }

  // Get domain_entity field type instances:
  if ($field_instance = domain_entity_entity_field_instance($type)) {
    $field_instance_name = $field_instance['name'];
  }
  else {
    return FALSE;
  }

  // Get current domain:
  $current_domain = domain_get_domain();
  $entity_info = entity_get_info($type);

  // Get default bundle value
  // e.g (all, current_domain, list(domain_id))
  $bundle_key = $entity_info['entity keys']['bundle'];
  if (isset($allowed_entity_types[$type][$entity->{$bundle_key}])) {
    $default_values = reset($allowed_entity_types[$type][$entity->{$bundle_key}]);
  }
  else {
    $default_values = array();
  }
  if (in_array(DOMAIN_ALL, $default_values)) {
    $values = array();
    $values[] = array(
      'domain_id' => DOMAIN_ENTITY_SEND_TO_ALL,
    );
  }
  elseif (in_array(DOMAIN_ACTIVE, $default_values)) {
    $values = array(
      0 => array(
        'domain_id' => $current_domain['domain_id'],
      ),
    );
  }
  else {
    $values = array();
    foreach ($default_values as $did) {
      $values[] = array(
        'domain_id' => $did,
      );
    }
  }

  // Ensure this entities have almost a default value.
  // Attach it to current domain if the entity is created,
  // by bypassing entity creation form,
  // do not let an unset domain entity saved,
  // (or the entity became inaccessible everywhere).
  if (!isset($entity->{$field_instance_name})) {

    // Populate field instance with the default bundle domain value,
    // if is not already set or unassigned.
    $entity->{$field_instance_name} = array(
      LANGUAGE_NONE => $values,
    );
  }
  else {

    // Populate field instance with the default bundle domain value,
    // if is not already set or unassigned.
    $value = $entity->{$field_instance_name};
    if (empty($value[LANGUAGE_NONE]) || !isset($value[LANGUAGE_NONE][0]['domain_id'])) {
      $entity->{$field_instance_name} = array(
        LANGUAGE_NONE => $values,
      );
    }
  }
  return $entity;
}