Drupal 8 Entity Manipulation

Drupal 8 has done a great overhaul in terms of entity management. Lets have a look on how can be access and set data for fields in entities.
All entities implement Drupal\Core\Entity\EntityInterface 

Access Entity Title:

<?php
drupal_set_message
($entity->label());
?>

Access Entity Id (Nid for Node and Uid for users).

<?php
drupal_set_message
($entity->id());
?>

To access a field value from an entity. There are multiple ways

<?php
 drupal_set_message
('Some text value: ' . $entity->field_article_some_text->value);
 
drupal_set_message('Some text value - Second Way ' . $entity->get('field_article_some_text')->value);
 
$entity_arr = $entity->toArray(); // Converts to array.
 
drupal_set_message('Some text value - Third Way:  ' . $entity_arr['field_article_some_text'][0]['value']);
 
?>

Check if field is present or not in the entity

<?php
 drupal_set_message
('Is Present: ' . $entity->hasField('field_article_some_text')); // Returns 1 if found, null otherwise
?>

Set the value of a field in an entity

<?php
 $entity
->field_article_some_text->value  'Some New Text Value';
 
$entity->set('field_article_some_text''Some New Text Value'); // Another Way
 
$entity->setTitle('The new Title');
 
$entity->set("body", 'New body text');
 
$entity->body->value = 'body text';
 
$entity->body->format = 'full_html';
?>

Saving an entity

<?php
$entity_save
();
?>

Loading an entity - Lets say a node:

<?php
$node
= \Drupal\node\Entity\Node::load($nid);
$user = \Drupal\user\Entity\User::load($uid);
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid); // Generic method
?>

Create a new node programmatically

<?php
 
// Create node object with data.
 
$node = \Drupal\node\Entity\Node::create([
   
'type'        => 'article',
   
'title'       => 'Druplicon test',
   
'field_article_some_text' => [
     
'value' =>'Some text also here',
    ],
  ]);
 
$node->save();
?>

Links
https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21...
http://realize.be/topics/drupal-8-field-api-series
http://www.drupal8.ovh/en/tutoriels/65/update-a-node-entity-programmatic...
http://www.drupal8.ovh/en/tutoriels/14/create-a-node-programmatically-dr...
http://realityloop.com/blog/2015/10/08/programmatically-attach-files-nod...
http://www.drupal8.ovh/en/tags/drupal-8
https://www.chapterthree.com/blog/drupal-8-theming-setting-theme-debugging

Technologies: