如何通过表单提交在特定节点(内容)类型上添加链接任务(选项卡)?

How to add links task (tabs) on specific node (content) type through form submission?

我是 Drupal 新手。
我创建了一个自定义模块并使其在节点类型上具有 link 任务(如 View/Edit/Delete 选项卡)。它工作正常并出现在每个节点类型上,但现在我想在我 select 并通过表单提交的特定节点类型上排除它。请告诉我如何实现这一目标。
mymodule.routing.yml:

mymodule.routname:
  path: '/node/{node}/custom-path'
  defaults:
   ...
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\NodeAcess::access'


NodeAcess.php:

public function access(AccountInterface $account, $node) {
    $node = Node::load($node);
    $node_type = $node->bundle();
    $currentUser = \Drupal::currentUser();
    if ($currentUser->hasPermission('Bypass content access control') && $node_type != 'article') {
      $result = AccessResult::allowed();
    }
    else {
      $result = AccessResult::forbidden();
    }


    return $result;
  }


在上面的函数中,我添加了&& $node_type != 'article',这样link任务就不会出现在'Article'节点上。但是我希望它在提交表单时是动态的

Form

第 1 步

在您的情况下,我会为模块创建一个配置表单 (src/Form/ModuleNameConfigForm.php),并且我会在 buildForm() 方法中像这样在复选框渲染元素中列出所有节点包:

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple();

上面的代码会将所有节点加载到 $nodes 数组中,然后您可以对其进行迭代。 (请尝试对 entity_type.manager 服务使用依赖注入。)

// Load the configuration of the form.
$configSettings = \Drupal::configFactory()->get('modulename.settings');

if (!empty($nodes)) {
  foreach ($nodes as $key => $node) {
    $options[$key] = $node->bundle();
  }
}

$form['disabled_node_links'] = [
    '#type' => 'checkboxes',
    '#default_value' => !empty($configSettings->get('disabled_node_links')) ? array_keys($configSettings->get('disabled_node_links'), TRUE) : [],
    '#options' => $options,
  ];

好,现在我们要把数据保存到submitForm()方法下的配置中。为此:

$configSettings = \Drupal::configFactory()->get('modulename.settings');
$configSettings
  ->set('disabled_node_links', $form_state->getValue('disabled_node_links'))
  ->save();

名为 modulename.schema.ymlconfig/schema 文件夹下的配置:

modulename.settings:
  type: config_object
  label: 'ModuleName Settings'
  mapping:
    disabled_node_links:
      type: sequence
      label: 'Disabled links on nodes'
      sequence:
        type: boolean

config/install 文件夹下的默认值仅包含 1 行 modulename.settings.yml 中没有值:

disabled_node_links:

第 2 步

为您可以在 Drupal 中访问它的配置表单创建一个路由(您还应该为它创建一个权限。)

然后,在您的 NodeAccess.php 中,我将加载配置,使用 array_keys() 获取它的键,并检查配置行的值是真还是假。如果该行为假,则表示复选框留空,这意味着您可以 return AccessResult::allowed()。


希望对您有所帮助,我没有时间创建整个模块,但我希望这会以一种您可以自己弄清楚要做什么的方式为您提供指导。另请查看 drupal.org 如何创建配置表单。