Working with Entities in Drupal is unified and all CRUD operations are also the same for all entities. In this article, we will figure out how to work with entities in custom code.
Let's look at simple examples first.
Create node programmatically
use \Drupal\node\Entity\Node; $node = Node::create([ 'type' => 'article', 'title' => 'Druplicon test', ]); $node->save();
In order to create a node, you need to add all the required fields, by default it is only the Title field. You can also access the node object after its creation:
$node = Node::create([ 'type' => 'article', 'title' => 'Druplicon test', ]); $node->field_text->value = 'Simple text'; $node->save();
The create() method is in the Node.php class, if an entity type has its own create() method, then it is best to use it. Although there are universal ways to create an entity.
$node_entity_type = \Drupal::entityTypeManager()->getDefinition('node'); $node = new Node([ $node_entity_type->getKey('bundle') => 'movie', $node_entity_type->getKey('label') => 'Foo', 'field_release_date' => '1/1/2015', ]); $node->save();
In the end, using the save() method, we save the entity.
Update node (entity) programmatically
$nid = 234; $node_storage = \Drupal::entityTypeManager()->getStorage('node'); $node = $node_storage->load($nid); $node->title = 'New title'; $node->field_text = 'text'; $node->save();
In detail about editing entity fields, we considered in a previous article:
Delete node (entity) programmatically
If you want to delete one node, then this can be done using the delete() method:
$nid = 123; $node = node_load($nid); $node->delete();
Create multiple nodes (entities) programmatically
When you need to load many nodes, it will be costly to do this one note, because each node has fields and to load data from the database, you will need to perform many SQL queries. It will be much faster to load all the nodes in one go:
$nids = db_select('node_field_data', 'n') ->fields('n', ['nid']) ->condition('title', $my_title) // The node_access tag will check access rights. ->addTag('node_access') ->execute() ->fetchCol(); $nodes = Node::loadMultiple($nids);
Delete multiple nodes (entities) programmatically
$result = \Drupal::entityQuery("node") ->condition('created', strtotime('-30 days'), '<=') ->execute(); $storage_handler = \Drupal::entityTypeManager()->getStorage("node"); $entities = $storage_handler->loadMultiple($result); $storage_handler->delete($entities);