Drupal 8的编程方式创建字段

6
我为Drupal 8创建了一个自定义模块,允许用户选择内容类型以便编程添加一些字段。我该如何使用自定义模块创建一些字段(在这种情况下是文本类型),并将它们附加到内容类型中?
需要帮助吗?
谢谢。
3个回答

3

请查看Drupal 8的Field API,它实现了几个函数,hook_entity_bundle_field_info可能是你需要的,以下是该钩子文档中textfield的示例:

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;
  }
}

你可能还需要使用字段储存,可以查看hook_entity_field_storage_info


3
你需要创建FieldType、FieldWidget和FieldFormatter(如果需要),Core/Field/Plugin/Field中有很好的示例。
这里有一个很好的示例https://www.drupal.org/node/2620964

1

您可以使用此模块从自定义的YAML或JSON文件中为任何实体类型和多个包创建字段:

https://drupal.org/project/field_create

对于您的模块来说,最简单的方法是在hook_field_create_definitions()中添加字段。只需创建此函数:

function mymodule_field_create_definitions_alter(&$definitions) {}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接