Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 create field programmatically

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.

like image 920
Alex Pezzini Avatar asked Dec 13 '15 14:12

Alex Pezzini


1 Answers

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

like image 142
otarza Avatar answered Sep 20 '22 03:09

otarza