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

时间:2019-07-08 02:45:08

标签: drupal drupal-modules drupal-forms

我是Drupal的新手。
我创建了一个自定义模块,并使其在节点类型上具有链接任务(例如“查看/编辑/删除”选项卡)。它可以正常工作并出现在每种节点类型上,但现在我想将其排除在我通过表单选择并提交的特定节点上。请告诉我如何实现这一目标。
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',因此链接任务不会出现在“ Article”节点上。但是我希望它在提交表单时能够动态地显示

Form

1 个答案:

答案 0 :(得分:0)

步骤1

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

$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的{​​{1}}文件夹下的配置:

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 文件夹下的默认值仅包含1行,而config/install中没有值:

modulename.settings.yml

STEP 2

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

然后,在您的NodeAccess.php中,我将加载配置,并用disabled_node_links: 获取其键,并检查每个配置行的值是true还是false。如果该行为false,则表示该复选框为空,这意味着您可以返回AccessResult :: allowed()。


希望有帮助,我没有时间来创建整个模块,但是我希望这会以一种可以指导自己的方式来指导您。还要查看drupal.org上如何创建配置表单。

相关问题