0
votes

I want to add an extra field in Drupal 8 content types with a custom module and I am not getting any hook to do.

Below is the hook I am using but that is not helping me with the result I want :

function nodeclass_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;
  }
}
1
No one is here to answer this question ?? - Rimpy Kakeyalia
That's probably not enough, you will need hook_entity_field_storage_info too. - golddragon007
Also you can watch this too: drupal.stackexchange.com/questions/220175/… and the documentation says you need hook_entity_field_storage_info or you need to overwrite an existing field base. You don't do any of the two. - golddragon007

1 Answers

0
votes

Inside your module folder, create the below folders modules/my_module/config/install/

Then create the below files inside your module folder.

my_module/config/install/field.field.node.article.field_text_more.yml

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_text_more
    - node.type.article
id: node.article.field_text_more
field_name: field_text_more
entity_type: node
bundle: article
label: 'More text'
description: ''
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string

my_module/config/install/field.storage.node.field_text_more.yml

langcode: en
status: true
dependencies:
  module:
    - node
id: node.field_text_more
field_name: field_text_more
entity_type: node
type: string
settings:
  max_length: 255
  is_ascii: false
  case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

Then re-install your module, it will add the new field "More text" into "Article" content type.

Note: Change file name and update the line "bundle: article" in field.field.node.article.field_text_more.yml if you wish to add fields to any other content type.