You are here

function organigrams_create_term_fields in Organigrams 8.2

Same name and namespace in other branches
  1. 8 organigrams.module \organigrams_create_term_fields()

Create taxonomy fields.

Parameters

int $vid: Contains a vocabulary id.

3 calls to organigrams_create_term_fields()
OrganigramsImportD7Form::submitForm in src/Form/OrganigramsImportD7Form.php
Form submission handler.
organigrams_update_8001 in ./organigrams.install
Update taxonomy term fields.
organigrams_vocabulary_form_submit in ./organigrams.module
Custom submit function for the vocabulary add form.

File

./organigrams.module, line 127
Extends Taxonomy to create organigrams.

Code

function organigrams_create_term_fields($vid) {

  // Set the config path to the field configs.
  $config_path = drupal_get_path('module', 'organigrams') . '/config';

  // Get the sources for the config files.
  $field_storage_source = new FileStorage($config_path . '/optional');
  $field_config_source = new FileStorage($config_path . '/taxonomy_fields');

  // Get all fields.
  $field_config_list = $field_config_source
    ->listAll();

  // Check if we have fields and iterate through them.
  if (!empty($field_config_list)) {
    foreach ($field_config_list as $field_name) {

      // Try to load the field config.
      $field = FieldConfig::loadByName('taxonomy_term', $vid, $field_name);

      // Stop if it already exists.
      if (!empty($field)) {
        continue;
      }

      // Get the field storage.
      $field_storage = FieldStorageConfig::loadByName('taxonomy_term', $field_name);

      // Create it if not found.
      if (empty($field_storage)) {
        $field_storage_config = $field_storage_source
          ->read('field.storage.taxonomy_term.' . $field_name);
        if (empty($field_storage_config)) {
          continue;
        }
        $field_storage = FieldStorageConfig::create($field_storage_config);
        $field_storage
          ->save();
      }

      // Get the field config.
      $field_config = $field_config_source
        ->read($field_name);

      // Add the field storage and vocabulary id to the field config.
      $field_config['field_storage'] = $field_storage;
      $field_config['bundle'] = $vid;

      // Create and save the field.
      $field = FieldConfig::create($field_config);
      $field
        ->save();

      // Get the display repository.
      $display_repository = \Drupal::service('entity_display.repository');

      // Assign widget settings for the default form mode to display our fields.
      $display_repository
        ->getFormDisplay('taxonomy_term', $vid)
        ->setComponent($field_name, [
        'type' => $field_config['widget_type'],
        'weight' => $field_config['weight'],
      ])
        ->save();
    }
  }
}