[英]How to add a new custom field to "Site Infomation" Form in Drupal8
我想在 Drupal8 的“站點信息”表單中添加一個新的自定義字段。 我嘗試了很多答案,但沒有得到正確的解決方案。 有什么方法可以添加自定義字段。 請建議。 提前謝謝。
考慮模塊名稱是 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 密鑰”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.