简体   繁体   English

Drupal 8 以编程方式创建字段

[英]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.我为 Drupal 8 创建了一个自定义模块,允许用户选择内容类型,以便以编程方式添加一些字段。 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 Drupal 8的Checkout Field API

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 它有几个实现的函数, hook_entity_bundle_field_info可能是你需要的,这里是一个来自该钩子的文档的文本字段的例子

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 您可能还需要字段存储,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. 您需要创建FieldType,FieldWidget和FieldFormatter(如果需要),Core / Field / Plugin / Field中有很好的例子。

There is a good example here https://www.drupal.org/node/2620964 这里有一个很好的例子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您可以使用此模块从自定义 YAML 或 JSON 文件以编程方式为任何实体类型和多个捆绑包一次创建字段: https : //drupal.org/project/field_create

The simplest approach for your module is to add your fields in the hook_field_create_definitions().您的模块最简单的方法是在 hook_field_create_definitions() 中添加您的字段。 Simply create this function:只需创建此函数:

function mymodule_field_create_definitions_alter(&$definitions) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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