You are here

public function EntityDrupalWrapper::set in Entity API 7

Overridden to support setting the entity by either the object or the id.

Overrides EntityMetadataWrapper::set

File

includes/entity.wrapper.inc, line 761
Provides wrappers allowing easy usage of the entity metadata.

Class

EntityDrupalWrapper
Provides a wrapper for entities registrered in hook_entity_info().

Code

public function set($value) {
  if (!$this
    ->validate($value)) {
    throw new EntityMetadataWrapperException(t('Invalid data value given. Be sure it matches the required data type and format. Value at !location: !value.', array(
      // An exception's message is output through check_plain().
      '!value' => is_array($value) || is_object($value) ? var_export($value, TRUE) : $value,
      '!location' => $this
        ->debugIdentifierLocation(),
    )));
  }
  if ($this->info['type'] == 'entity' && $value === $this) {

    // Nothing to do.
    return $this;
  }
  $previous_id = $this->id;
  $previous_type = $this->type;

  // Set value, so we get the identifier and pass it to the normal setter.
  $this
    ->clear();
  $this
    ->setEntity($value);

  // Generally, we have to update the parent only if the entity reference
  // has changed. In case of a generic entity reference, we pass the entity
  // wrapped. Else we just pass the id of the entity to the setter callback.
  if ($this->info['type'] == 'entity' && ($previous_id != $this->id || $previous_type != $this->type)) {

    // We need to clone the wrapper we pass through as value, so it does not
    // get cleared when the current wrapper instance gets cleared.
    $this
      ->updateParent(clone $this);
  }
  elseif ($this->id === FALSE && !$this->data) {
    $this
      ->updateParent(NULL);
  }
  elseif ($previous_id !== $this->id) {
    $this
      ->updateParent($this->id);
  }
  return $this;
}