在 Drupal 8 块表单中添加字段链接

ker*_*zen 0 drupal-8

我想link在自定义块中有一个字段。这是我的代码:

public function blockForm($form, FormStateInterface $form_state)
{

    $form['key_1'] = [
        '#title' => $this->t('Key 1 label'),
        '#type' => 'textfield',
        '#default_value' => '',
        '#required' => false,
    ];

    $form['key_2'] = [
        '#title' => $this->t('key 2 link'),
        '#type' => 'link',
    ];

    return $form;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我进入 admin/structure/block/manage/myblock 时,我可以看到我的key 1字段。在key 2不渲染。如果我更改任何其他(文本字段、文本区域、文件管理)的类型,我的字段将正确呈现。默认链接模块已启用。

链接字段类型只能在节点形式中使用吗?我能理解为什么。

bai*_*kho 6

看看Link类。您需要指定#url属性:

$form['key_2'] = [
  '#title' => $this->t('key 2 link'),
  '#type' => 'link',
  '#url' => \Drupal\Core\Url::fromRoute('some.route.name'),
];
Run Code Online (Sandbox Code Playgroud)