Drupal 8 create field programmatically
Asked Answered
S

3

6

I created a custom module for Drupal 8 that allows the users to choose a Content type in order to add some fields programmatically. How I can create some fields (text type in this case) and attach they to a Content type with a custom module?

Some help?

Thanks.

Steelhead answered 13/12, 2015 at 14:29 Comment(0)
K
3

Checkout Field API for Drupal 8

It has several functions implemented and hook_entity_bundle_field_info might be what you need, here is an example of textfield from the docs of that hook

function hook_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = array();
    $fields['mymodule_text_more'] = BaseFieldDefinition::create('string')
      ->setLabel(t('More text'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedMoreText');
    return $fields;
  }
}

You might also need Field Storage, checkout hook_entity_field_storage_info

Kolyma answered 21/12, 2015 at 14:53 Comment(0)
I
3

You need to create FieldType, FieldWidget and FieldFormatter(If necessary), there are good examples in Core/Field/Plugin/Field.

There is a good example here https://www.drupal.org/node/2620964

Idea answered 27/1, 2016 at 13:46 Comment(0)
B
1

You can use this module to create fields programmatically for any entity type and multiple bundles at once from custom YAML or JSON files:

https://drupal.org/project/field_create

The simplest approach for your module is to add your fields in the hook_field_create_definitions(). Simply create this function:

function mymodule_field_create_definitions_alter(&$definitions) {}
Berserk answered 20/10, 2021 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.