Drupal 8 create field programmatically

Alex Pezzini picture Alex Pezzini · Dec 13, 2015 · Viewed 8.5k times · Source

I created a custom module for Drupal 8 that allow the users to choose a Content type in order 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.

Answer

otarza picture otarza · Dec 21, 2015

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