Skip to content

Instantly share code, notes, and snippets.

@rpayanm
Created July 12, 2019 20:24
Show Gist options
  • Save rpayanm/a751811547463611d91ee10b83930b3b to your computer and use it in GitHub Desktop.
Save rpayanm/a751811547463611d91ee10b83930b3b to your computer and use it in GitHub Desktop.
<?php
// node, block, block_content, user, view, fiel, taxonomy_term, menu, menu_link_content, migration, ...
$storage = 'block';
$service = \Drupal::service('entity_type.manager')->getStorage($storage);
// LOAD
// One entity
$entity = $service->load($id);
// More entities.
// We'll get all ids.
$ids = $service->getQuery()
->condition('theme', 'bartik')
->condition('region', 'header')
->execute();
// We'll get all complete entities.
$entities = $service->loadMultiple($ids);
// CREATE
// We can also create an entity.
$service = \Drupal::service('entity_type.manager')->getStorage('node');
$node = $service->create(array('type' => 'page', 'title' => 'About Us'));
$node->save();
// SAVE
$entity->title->value = 'Yes we can!';
$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([$id1, $id2]);
// TRANSLATION
$translation = $node->getTranslation('es');
// English title
print $node->title->value;
// Spanish title
print $translation->title->value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment