I am building a module to insert a custom field in all bundles of the node. I have encountered many difficulties, any help they can give me, I would appreciate it very much.
The custom field I am creating is used to save a tocken automatically or manually. - field_custom_tocken -
If a new bundle is created, the field_custom_tocken field must be added automatically to the new bundle. To generate the token it is necessary the id of the entity (nid), or that the tockent is inserted by the user.
I have used Drupal Console, create the field type, the widget and the formatter. This does not generate the field, the drawback is that you have to manually add the field to the bundle. drupal generate: plugin: field
In this documentation the field is created and added to a specific bundle, I use part of this documentation. field.storage.node.field_brand_information.yml
I have this:
this creates the field. modules/custom/custom_tocken/config/install/field.storage.node.field_custom_tocken.yml
# field.storage.node.field_custom_tocken.yml
langcode: en
status: true
dependencies:
enforced:
module:
- custom_tocken
module:
- node
- text
id: node.field_custom_tocken
field_name: field_custom_tocken
entity_type: node
type: string
settings: { }
module: core
locked: true
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false
This should create the custom field in the existing bundles, when the module is installed, but it does not work :(
/**
* Implements hook_install().
*/
function ide_d8_url_shortener_install() {
$entity_type = 'node';
$bundle = '';
$field['field_name'] = 'field_custom_tocken';
$field['label'] = 'Tocken';
$field['entity_type']= 'node';
$field['type'] = 'string';
$field['settings'] = array();
$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type);
$arr_bundles = [];
foreach($bundles as $key => $value) {
$bundle = $key;
$fields = \Drupal::entityManager()->getFieldDefinitions($entity_type, $bundle);
if ( !isset($fields['field_short_url']) ) {
entity_get_form_display($entity_type, $bundle, 'default')
->setComponent($field['field_name'], $field )
->save();
entity_get_display($entity_type, $bundle, 'default')
->setComponent($field['field_name'], $field)
->save();
}
}
}
Any help you can give me I would appreciate it.