Score:1

How do I programmatically create an entity type from the install yml file?

au flag

I'm currently writing a module. In an update, I need to programmatically create a new entity type.

I have already created a suitable yml for installation. Like this one, except it is not a Node Type entity, but a custom entity type entity.

For the sake of consistency, I'd like to use the yml directly in my updateN hook. Is there anyway I can simply use the config yml to create this new entity type?

Score:3
cn flag

The linked file

core/profiles/standard/config/install/node.type.article.yml

langcode: en
status: true
dependencies: {  }
name: Article
type: article
description: 'Use <em>articles</em> for time-sensitive content like news, press releases or blog posts.'
help: ''
new_revision: true
preview_mode: 1
display_submitted: true

is a content type and you can create it in code:

use Symfony\Component\Yaml\Yaml;
use Drupal\node\Entity\NodeType;

  $values = Yaml::parseFile('core/profiles/standard/config/install/node.type.article.yml');
  $bundle = NodeType::create($values);
  $bundle->save();

For a custom entity you find the label and the machine name of the bundle config entity in the entity class (Node.php in your example):

* @ContentEntityType(
*   id = "node",
*   bundle_label = @Translation("Content type"),
*   bundle_entity_type = "node_type",

The machine name is also the first part of the yml file name, replacing _ with .

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.