You are here

public function OrganigramsController::exportOrganigramItems in Organigrams 8.2

Outputs the items of an organigram in JSON.

Parameters

\Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary: The vocabulary to export the items from.

Return value

array A render array.

1 string reference to 'OrganigramsController::exportOrganigramItems'
organigrams.routing.yml in ./organigrams.routing.yml
organigrams.routing.yml

File

src/Controller/OrganigramsController.php, line 88

Class

OrganigramsController
Provides route responses for organigrams.module.

Namespace

Drupal\organigrams\Controller

Code

public function exportOrganigramItems(VocabularyInterface $taxonomy_vocabulary) {

  // Get all terms in this vocabulary.
  $terms = $this
    ->entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadTree($taxonomy_vocabulary
    ->id(), 0, NULL, TRUE);

  // Setup array for export data.
  $export_data = [];

  // Check if there are terms.
  if (!empty($terms)) {

    // Ignore these term fields.
    $ignore_fields = [
      'uuid',
      'revision_id',
      'langcode',
      'vid',
      'revision_created',
      'revision_user',
      'revision_log_message',
      'changed',
      'default_langcode',
      'revision_default',
      'revision_translation_affected',
    ];

    // Iterate through the terms.
    foreach ($terms as $term) {

      // Get field definitions.
      $fields = $term
        ->getFieldDefinitions();

      // Create array for the term data.
      $term_data = [];

      // Iterate through the fields.
      foreach ($fields as $field_name => $field) {

        // Continue if the field is in the ignore array.
        if (in_array($field_name, $ignore_fields)) {
          continue;
        }

        // Process the fields.
        switch ($field_name) {
          case 'tid':

            // Export tid as iid so the import works with D7 and D8 exports.
            $term_data['iid'] = $term
              ->get($field_name)->value;
            break;
          case 'parent':

            // The parent needs to be retrieved in a different way.
            $term_data['parent'] = $term->parent->target_id;
            break;
          default:

            // Remove field_o_ from the field name and store it with it's
            // value in the term_data array.
            $term_data[str_replace('field_o_', '', $field_name)] = $term
              ->get($field_name)->value;
        }
      }

      // Add the term data to the export array.
      $export_data[] = $term_data;
    }
  }

  // Textarea for the Json encoded organigram items.
  $form['organigrams_items_json'] = [
    '#type' => 'textarea',
    '#title' => $this
      ->t('Organigram items JSON'),
    '#description' => '',
    '#value' => Json::encode($export_data),
    '#rows' => 20,
  ];
  return $form;
}