简体   繁体   中英

Drupal 8 create field programmatically

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.

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

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

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) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM