Skip to content

Instantly share code, notes, and snippets.

@DanLaufer
Last active February 23, 2019 18:14
Show Gist options
  • Save DanLaufer/bcbbaa7ecdacb59eccb3fe4c67c1c9ac to your computer and use it in GitHub Desktop.
Save DanLaufer/bcbbaa7ecdacb59eccb3fe4c67c1c9ac to your computer and use it in GitHub Desktop.
Drupal 8 - Entity API CRUD
// CREATE
// Procedural Wrapper
$node = entity_create('node', array(
'title' => 'Make blogs great again',
'body' => 'This is where the body content goes. You could load text from a seperate file here too if you didn\'t want to have it all inline and have to worry about things like character escaping.',
));
// Static Create method
$node = Node::create(array('title' => 'First!'));
$node->save();
// EntityTypeManager
$node = \Drupal::entityTypeManager()->getStorage('node')->create(array('type' => 'page', 'title' => 'About Us'));
$node->save();
// READ
// Access value of node fields
$node = \Drupal::entityTypeManager()->getStorage("node")->load(22);
$body_text = $node->body->value;
$body_text = $node->get('body')->value;
$body_array = $node->body->getValue();
// --or for taxonomy reference-- (more than one returned)
$field_tags = $node->field_tags->getValue();
// --or get FIELD from entity reference--
$second_tag = $node->field_tags[1]->entity->name->value;
$author_name = $node->uid->entity->name->value;
// --retried reverenced entities ALREADY loaded for you--
$tags = $node->field_tags->referencedEntities();
//Translated Node field
$translation = $node->getTranslation('es');
// English title
print $node->title->value;
// Spanish title
print $translation->title->value;
// UPDATE
$entity = \Drupal::entityTypeManager()->getStorage("node")->load(22);
$entity->title->value = 'Yes we can!';
// Update the multivalue tags field term id
// Use $entity->field_tags->getValue() to see the field's data structure.
$entity->field_tags[0]->target_id = 3;
$entity->save();
// DELETE
// Delete a single entity.
$entity = \Drupal::entityTypeManager()->getStorage('node')->load(22);
$entity->delete();
// Delete multiple entities at once.
\Drupal::entityTypeManager()->getStorage($entity_type)->delete(array($id1 => $entity1, $id2 => $entity2));
// hook_entity_load
function hook_entity_load(array $entities, $entity_type_id) {
foreach ($entities as $entity) {
$entity->foo = mymodule_add_something($entity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment