2

I am new to Drupal and working with Drupal 8, I have not work in Drupal 7 or 6 so have less knowledge of it.

I am working on some dynamic fields of Drupal content type.

I have one content type attached with a vocabulary ( select list of terms ). I am using improved multi select (https://www.drupal.org/project/improved_multi_select) there.

Now I have some code in module which are creating vocabulary dynamically from some incoming API data.

I want, whenever my code create a vocabulary it automatically attached to field storage information that I am using in content type one.

Udit Rawat
  • 674
  • 8
  • 22
Kiran B
  • 23
  • 4

1 Answers1

1

You need to add target bundle to storage setting for this, Below code will help you.

/**
   * Attach vocabulary to field
   * @var $field_storage
   */
  $field_storage = \Drupal::entityManager()->getStorage('field_config')->loadByProperties(['field_name' => 'field_machine_key']);
  $field_storage = $field_storage['node.content_type_machine_key.field_machine_key'];
  $settings = $field_storage->getSetting('handler_settings');
  // $vocab_id will be your newly created vocabulary
  $settings['target_bundles'][$vocab_id] = $vocab_id;
  $field_storage->setSetting('handler_settings',$settings);
  $field_storage->save(); 

See Complete Code Here

Udit Rawat
  • 674
  • 8
  • 22
  • 1
    Works for me but I also add a default term to vocabulary to show it on the improved multiselect – Kiran B Dec 09 '17 at 21:55