我想在Drupal8的“站点信息”表单中添加一个新的自定义字段。我尝试了很多答案,但没有得到正确的解决方案。有什么办法可以添加自定义字段。请提出建议。谢谢。
答案 0 :(得分:2)
考虑模块名称为mymodule。
mymodule.services.yml文件的示例
在mymodule.services.yml中注册事件订阅者
services:
bssa.route_subscriber:
class: Drupal\bssa\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
class:“ Drupal \ mymodule \ Routing \ RouteSubscriber”根据此类创建如下所示的php文件。
扩展RouteSubscriber以将新字段形式实现为 mymodule / src / Routing / RouteSubscriber.php
<?php
namespace Drupal\mymodule\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('system.site_information_settings'))
$route->setDefault('_form', 'Drupal\mymodule\Form\ExtendedSiteInformationForm');
}
}
现在在mymodule / src / Form / ExtendedSiteInformation.php中创建一个新表单以添加自定义字段
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\system\Form\SiteInformationForm;
class ExtendedSiteInformationForm extends SiteInformationForm {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$site_config = $this->config('system.site');
$form = parent::buildForm($form, $form_state);
$form['site_information']['siteapikey'] = [
'#type' => 'textfield',
'#title' => t('Site API Key'),
'#default_value' => $site_config->get('siteapikey') ?: 'No API Key yet',
'#description' => t("Custom field to set the API Key"),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('system.site')
->set('siteapikey', $form_state->getValue('siteapikey'))
->save();
parent::submitForm($form, $form_state);
}
}
现在创建一个配置变量,以保存mymodule / config / schema / mymodule.schema.yml中新字段的值
# We want to extend the system.site configuration
system.site:
mapping:
# Our field name is 'siteapikey'
siteapikey:
type: label
label: 'Site API Keys'
按照上述步骤操作后,清除缓存,您将在“站点信息”表单中看到一个新字段“站点API密钥”。