You are here

public function EntityExampleBasicController::save in Examples for Developers 7

Saves the custom fields using drupal_write_record().

Overrides EntityExampleBasicControllerInterface::save

File

entity_example/entity_example.module, line 556
Implements the basic functionality required to create and display an entity.

Class

EntityExampleBasicController
EntityExampleBasicController extends DrupalDefaultEntityController.

Code

public function save($entity) {

  // If our entity has no basic_id, then we need to give it a
  // time of creation.
  if (empty($entity->basic_id)) {
    $entity->created = time();
  }

  // Invoke hook_entity_presave().
  module_invoke_all('entity_presave', $entity, 'entity_example_basic');

  // The 'primary_keys' argument determines whether this will be an insert
  // or an update. So if the entity already has an ID, we'll specify
  // basic_id as the key.
  $primary_keys = $entity->basic_id ? 'basic_id' : array();

  // Write out the entity record.
  drupal_write_record('entity_example_basic', $entity, $primary_keys);

  // We're going to invoke either hook_entity_update() or
  // hook_entity_insert(), depending on whether or not this is a
  // new entity. We'll just store the name of hook_entity_insert()
  // and change it if we need to.
  $invocation = 'entity_insert';

  // Now we need to either insert or update the fields which are
  // attached to this entity. We use the same primary_keys logic
  // to determine whether to update or insert, and which hook we
  // need to invoke.
  if (empty($primary_keys)) {
    field_attach_insert('entity_example_basic', $entity);
  }
  else {
    field_attach_update('entity_example_basic', $entity);
    $invocation = 'entity_update';
  }

  // Invoke either hook_entity_update() or hook_entity_insert().
  module_invoke_all($invocation, $entity, 'entity_example_basic');
  return $entity;
}