Drupal 8 Entity API & Manager
<?php
namespace Drupal\module_name\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class TestController extends ControllerBase {
protected $entityManager;
/**
* {@inheritdoc}
*/
public function __construct(EntityManagerInterface $entityManager) {
// Dependency injection
$this->entityManager = $entityManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
// Get the service through the service container using the key defined insode the yml
$container->get('entity.manager')
);
}
}// Get field value for single delta
$value = $entity->get('field_machine_name')->value;
// Get field valie for multiple delta - or Reference
$value = $entity->get('field_machine_name')->getValue();
// Set field value
$entity->set('field_machine_name', $value);// Access entity storage
$storage = Drupal::entityTypeManager()->getStorage('entity_name');
// Load entity
$entity = $storage->load($entity_id);
Example with node entity:
$node_storage = $this->entityManager->getStorage('node');
$node = $storage->load(98);
// Check entity type from Interface
$entity instanceof \Drupal\node\NodeInterface
// Get entity bundle
$entity->bundle()