Drupal 8 - Create, save and load an entity

By xngo on March 10, 2019

Overview

In this tutorial, I will show how to create, save and load an entity in Drupal 8.

There is different ways to manipulate the entity. It is either using the entity manager or using the static methods. Using the entity manager is the recommended way as it uses the full potential of Object Oriented programming. The static methods exist due to historic reason and make the transition from Drupal 7 to Drupal 8 easier. For more details, see https://www.drupal.org/project/drupal/issues/2945539.

Obviously, the code examples below will use entity manager. It is assumed that you know how to create a module. If not, see Create a module in Drupal 8.

Create a page for your module

Create an URL for your test page by adding the following routing information in ./modules/tradesteps/tradesteps.routing.yml

tradesteps.entity_api:
  path: '/use_entity_api'
  defaults:
    _controller: 'Drupal\tradesteps\Controller\UseEntityAPI::usage'
    _title: 'Use of Entity API'
  requirements:
    _permission: 'access content'

Create, save, load entity

Below show the codes to create, save and load an entity, specifically an article. Add the code below in ./modules/tradesteps/src/Form/UseEntityAPI.php.

<?php
 
// Note: The namespace path doesn't contain 'src' because
//  by default, Drupal will fetch all source code files from 'src' directory.
namespace Drupal\tradesteps\Controller;
 
use Drupal\Core\Controller\ControllerBase;
 
class UseEntityAPI extends ControllerBase{
    public function usage() {
 
        // Create a entity object.
        $entity = \Drupal::entityTypeManager()
                            ->getStorage('node')
                            ->create([
                                'type' => 'article', 
                                'title' => 'My title',
                                'body' => 'This is the body. Use machine name field.'
                                ]);
 
        // Update entity field.
        //      $entity->get('title')->getValue(): Return an array of values.
        //      $entity->get('title')->getString(): Return a value.
        $new_value=$entity->get('title')->getString() . ", updated on " . date('D, d M Y H:i:s');
        $entity->get('title')->setValue($new_value);
        $entity->get('body')->setValue(array(
                                        'summary' => "This is a summary",
                                        'value' => "This is the very long body....",
                                        'format' => 'basic_html',
                                        ));
 
        // Save the entity object. It will commit to database.
        $entity->save();
        $saved_entity_id = $entity->id();
 
        // Load entity object.
        $loaded_entity = \Drupal::entityTypeManager()->getStorage('node')->load($saved_entity_id);
 
        // Get info about entity: Good for debugging.
        $entity_info = print_r($loaded_entity->toArray(), true);
 
        // Prepare to display data.
        $loaded_id = $loaded_entity->id();
        $loaded_title = $loaded_entity->getTitle();
        $loaded_type = $loaded_entity->getType();
        //$loaded_field_value = $loaded_entity->get('field_FIELDNAME')->getString();
 
        $html = 'Info of created ['.$loaded_type.']: [node id = '. $loaded_id. '] : ['. $loaded_title.']';
        $html .= '<pre>'. $entity_info. '</pre>';
 
        return array(
            '#type' => 'markup',
            '#markup' => t($html),
        );
 
    }
 
}

Test page

  1. Clear your cache.
  2. Open http://your-domain.com/use_entity_api
  3. Every page refresh will create new article.

Screenshot test page showing create, save and load an entity

Github

  • https://github.com/xuanngo2001/drupal-entity-create-save-load

Reference

  • https://api.drupal.org/api/drupal/core%21core.api.php/group/form_api/8.2.x
  • All possible elements(#): https://api.drupal.org/api/drupal/elements/8.7.x
  • https://www.drupal.org/docs/8/api/entity-api/working-with-the-entity-api
  • https://www.drupal.org/project/drupal/issues/2945539
  • D7 elements in big table: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.