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

问题描述

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

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


节点访问.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'因此链接任务不会出现在“文章”节点上。但我希望它在提交表单时是动态的

形式

标签: drupaldrupal-modulesdrupal-forms

解决方案


第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();

文件夹下的配置config/schema称为modulename.schema.yml

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(),并检查每个配置行的值是真还是假。如果该行为 false,则表示复选框为空,这意味着您可以返回 AccessResult::allowed()。


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


推荐阅读