2

I want to programmatically create a custom content (custom content created via the admin UI). Before the creation, I want to check the types of fields of my custom content.

My custom content contains a field "body" (type text), a field "description" (type text), an int field (type int), an attached file field (type fid ?).

I tested several ways; this is my last try.

// I get the entity object "my_custom_content"
$entity_object = NodeType::load("my_custom_content");
dpm($entity_object); //Work perfectly


$test = \Drupal::getContainer()->get("entity_field.manager")->getFieldDefinitions("my_custom_content",$entity_object->bundle())

The code returns an error:

The my_custom_content entity type does not exist.

With this $entity_object, how can I get the list of the fields of my custom content? I see the EntityFieldManager class, the FieldItemList class, but I still do not understand how to play with Drupal 8.

10

You're mixing up entity types/node (content) types/bundles. Common mistake :)

Especially since the UI naming is... very unfortunate.

What is called Content in the UI is actually the entity type node. And Content types are node types (you figured out that much), which are bundles of the node entity type.

getFieldDefinitions() expects an entity_type ID and a bundle. In your case, that is:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

Note that this will also return base field definitions like nid, vid, title, status and so on.

Tipp: Once you have a node object, you can get the same definition from that object and other useful information too:

$node = Node::create(['type' => 'my_custom_content']);
$node->getFieldDefinitions();
$node->getFieldDefinition('body');
$node->hasField('body');

So if you want to dynamically do something like this, it can simplify your code a lot if you first create the node with the information that's always enable and then work with the methods on your entity object.

Default recommendation when working with entities in 8.x: http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

  • The $node = ... block work perfectly, however, the line $definitions = \Drupal::ser... does't work. I get the erreur "my_custom_content" not found.. – user2137454 Nov 26 '15 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.