Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

Работа с Entity API

09/05/2020, by maria

Охватывает методы API общего объекта

  • Entity::create()
  • Entity::load()
  • Entity::save()
  • Entity::id()
  • Entity::bundle()
  • Entity::isNew()
  • Entity::label()

Более конкретные API будут рассмотрены в определенных главах.

Проверьте

// Make sure that an object is an entity.
if ($entity instanceof \Drupal\Core\Entity\EntityInterface) {
}

// Make sure it's a content entity.
if ($entity instanceof \Drupal\Core\Entity\ContentEntityInterface) {
}
// or:
if ($entity->getEntityType()->getGroup() == 'content') {
}

// Get the entity type or the entity type ID.
$entity->getEntityType();
$entity->getEntityTypeId();

// Make sure it's a node.
if ($entity instanceof \Drupal\node\NodeInterface) {
}

Получить информацию от entity/ Entity methods

Доступно несколько общих методов для получения информации от объекта, таких как идентификатор, пакет, идентификатор ревизии и так далее. См. Документацию на EntityInterface для деталей.

// Get the ID.
$entity->id();

// Get the bundle.
$entity->bundle();

// Check if the entity is new.
$entity->isNew();

// Get the label of an entity. Replacement for entity_label().
$entity->label();

// Get the URL object for an entity.
$entity->toUrl();

// Get internal path, path alias if exists, for an entity.
$entity->toUrl()->toString();

// Create a duplicate that can be saved as a new entity.
$duplicate = $entity->createDuplicate();

Создание сущности

// You can use the static create() method if you know the entity class.
$node = Node::create([
  'type' => 'article',
  'title' => 'The node title',
]);

// Use the entity type manager (recommended).
$node = \Drupal::entityTypeManager()->getStorage('node')->create(['type' => 'article', 'title' => 'Another node']);

// Or use the procedural wrapper (deprecated).
$node = entity_create('node', [
  'title' => 'My node',
  'body' => 'The body content. This just works like this due to the new Entity Field
          API. It will be assigned as the value of the first field item in the
          default language.',
]);

Настройки по умолчанию из аннотации типа поля добавляются только для отсутствующих ключей верхнего уровня; глубокое слияние не выполняется.

Избегайте использования статического метода Entity::create() в объектно-ориентированном коде. Вместо этого используйте внедрение зависимостей, чтобы внедрить менеджер типов сущностей и создать сущность с помощью $this->entityTypeManager->getStorage($entity_type)->create(). Это гарантирует, что код правильно отделен и может быть проверен модулем.

Для обнаружения в среде IDE вы также можете назначить интерфейс хранения сущностей свойству. Например, $this->nodeStorage = $this->entityTypeManager->getStorage('node'); Чтобы создать сущность, вы можете использовать $this->nodeStorage->create().

Загрузка

// Use the static method
$node = Node::load(1);

// Deprecated.  Dynamic entity type, entity_load() now loads a single entity, the 7.x entity_load() has been renamed to entity_load_multiple().
$entity = entity_load($entity_type, $id);

// Using the storage controller (recommended).
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load(1);

// Load multiple entities, also exists as entity_load_multiple().
$entities = \Drupal::entityTypeManager()->getStorage($entity_type)->loadMultiple([1, 2, 3]);

// Load entities by their property values.
$entities = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'article']);

Чтобы обновить объект, загрузите его, а затем сохраните с изменениями.

Избегайте использования статического метода Entity::load() в объектно-ориентированном коде. Вместо этого используйте внедрение зависимостей, чтобы внедрить менеджер типов сущностей и загрузить сущность с помощью $this->entityTypeManager->getStorage($entity_type)->load($entity_id). Это гарантирует, что код правильно отделен и может быть проверен модулем.

Сохранение сущности

// To save an entity.
$entity->save();

Это работает как для новых, так и для существующих сущностей, сама сущность отслеживает, является ли она новой или нет. По умолчанию для сущностей контента это зависит от того, имеет ли он идентификатор или нет. Чтобы сохранить объект с идентификатором в качестве нового объекта (например, при импорте чего-либо), можно применить флаг isNew.

// The following will attempt to insert a new node with the ID 5, this will fail if that node already exists.
$node->nid->value = 5;
$node->enforceIsNew(TRUE);
$node->save();

Удаление сущности

// Delete a single entity.
$entity = \Drupal::entityTypeManager()->getStorage('node')->load(1);
$entity->delete();

// Delete multiple entities at once.
\Drupal::entityTypeManager()->getStorage($entity_type)->delete([$id1 => $entity1, $id2 => $entity2]);

Контроль доступа

Метод acces () можно использовать для проверки того, кто что может делать с сущностью. Метод поддерживает различные операции, стандартные операции - просмотр, обновление, удаление и создание, создание - несколько особенное, см. Ниже.

Проверки доступа передаются контроллеру доступа. (TODO: Добавить ссылку)

// Check view access of an entity.
// This defaults to check access for the currently logged in user.
if ($entity->access('view')) {

}

// Check if a given user can delete an entity.
if ($entity->access('delete', $account)) {

}

При проверке создания доступа обычно еще нет сущности. Создание одного только для того, чтобы проверить, сможет ли кто-то создать его, является дорогостоящей операцией. Поэтому создание доступа для них должно быть проверено непосредственно на контроллере доступа.

\Drupal::entityTypeManager()->getAccessControlHandler('node')->createAccess('article');

Если сущность уже существует, $entity->access('create') также работает, что просто перенаправляет метод createAccess(), так же, как другие операции пересылают метод access() на контроллере доступа.

ПРИМЕЧАНИЕ. В некоторых онлайн-руководствах используется \Drupal::entityManager(), но в версии 8.x он устарел и будет удален в версии 9.x. Таким образом, вы можете использовать \Drupal::entityTypeManager() вместо \Drupal::entityManager().

Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.