You are here

function organigrams_create_term_fields in Organigrams 8

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

Create taxonomy fields.

Parameters

int $vid: Contains a vocabulary id.

2 calls to organigrams_create_term_fields()
OrganigramsImportD7Form::submitForm in src/Form/OrganigramsImportD7Form.php
Form submission handler.
organigrams_vocabulary_form_submit in ./organigrams.module
Custom submit function for the vocabulary add form.

File

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

Code

function organigrams_create_term_fields($vid) {

  // Set the config path to the taxonomy fields.
  $config_path = drupal_get_path('module', 'organigrams') . '/config/taxonomy_fields';

  // Get the field config files.
  $files = \Drupal::service('file_system')
    ->scanDirectory($config_path, '/^.*\\.yml$/i', [
    'key' => 'filename',
  ]);

  // Check if we have files and iterate through them.
  if (!empty($files)) {
    foreach ($files as $file) {

      // The field name is the file name.
      $field_name = $file->name;

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

      // If it doesn't exists, create it.
      if (!empty($field)) {
        continue;
      }

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

      // Skip if not found.
      if (empty($field_storage)) {
        continue;
      }

      // Get the file content which is yaml.
      $yaml = file_get_contents($file->uri);

      // Decode the yaml.
      $field_config = Yaml::decode($yaml);

      // 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 config.
      $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();
    }
  }
}