动态添加词汇
Adding vocabulary dynamically
我是 Drupal 的新手,正在使用 Drupal 8,我没有使用过 Drupal 7 或 6,所以对它了解较少。
我正在处理一些 Drupal 内容类型的动态字段。
我有一种内容类型附有词汇表(select 术语列表)。我在那里使用改进的 multi select (https://www.drupal.org/project/improved_multi_select)。
现在我在模块中有一些代码可以根据传入的 API 数据动态创建词汇表。
我想,每当我的代码创建一个词汇表时,它会自动附加到我在内容类型一中使用的字段存储信息。
为此,您需要将目标包添加到存储设置,下面的代码将帮助您。
/**
* 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();
我是 Drupal 的新手,正在使用 Drupal 8,我没有使用过 Drupal 7 或 6,所以对它了解较少。
我正在处理一些 Drupal 内容类型的动态字段。
我有一种内容类型附有词汇表(select 术语列表)。我在那里使用改进的 multi select (https://www.drupal.org/project/improved_multi_select)。
现在我在模块中有一些代码可以根据传入的 API 数据动态创建词汇表。
我想,每当我的代码创建一个词汇表时,它会自动附加到我在内容类型一中使用的字段存储信息。
为此,您需要将目标包添加到存储设置,下面的代码将帮助您。
/**
* 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();