首页 > 解决方案 > 如何在 Drupal 8 中的链接 uri 自动完成选择小部件中设置特定内容类型不可用的内容?

问题描述

当您想在 Drupal 8 中添加指向菜单的链接时,您可以输入 a并从字段小部件Menu link title的自动完成列表中选择一个选项 。Link

默认情况下,所有内容类型(文章、横幅、基本页面)的所有内容都在此自动完成选择列表中可用。

如何在自动完成选择字段小部件中设置内容类型BannerBasic page不可用的所有内容?我只想显示内容类型的内容(已检查发布)Article

以下是我一一尝试的尝试,但它不起作用。

function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
    if ($entity_type->id() == 'menu_link_content' && !empty($fields['link'])) {
       // Attempt 1
       $fields['link']->setTargetBundle('article');
       // Attempt 2
       $fields['link']->setSetting('handler_settings', ['target_bundles' => ['article' => 'article']]);
       // Attempt 3
       $fields['link']->setSetting('selection_settings', ['target_bundles' => ['article' => 'article']]);
       // Attempt 4
       $fields['link']->setSettings(['selection_settings' => ['target_bundles' => ['article' => 'article']]]);
       // Attempt 5
       $fields['link']->setSettings(['handler_settings' => ['target_bundles' => ['article' => 'article']]]);
    }
}

标签: phpautocompletedrupal-8select-options

解决方案


我想出了以下解决方案,但我不确定它是否是一种有效的方法。

创建自定义链接字段小部件。

/**
 * Some class description.
 *
 * @FieldWidget(
 *   id = "my_custom_link_widget",
 *   label = @Translation("My custom link widget"),
 *   field_types = {
 *     "link"
 *   }
 * )
*/
class MyCustomLinkWidget extends LinkWidget {

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);
    $content_types = [
      'banner',
      'basic_page',
    ];
    $node_types = \Drupal::entityQuery('node_type')
      ->condition('type', $content_types, 'NOT IN')
      ->execute();
    $element['uri']['#selection_settings']['target_bundles'] = $node_types;

    return $element;
  }

}

实施挂钩以将我的自定义链接小部件设置为链接输入字段。

function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'menu_link_content' && !empty($fields['link'])) {
    $fields['link']->setDisplayOptions('form', [
      'type' => 'my_custom_link_widget',
      'weight' => -2,
    ]);
  }
}

推荐阅读