I want to Add a new custom field to "Site Infomation" Form in Drupal8. I have tried many answers but didnt get the proper solution. Is there any way to add custom field. Please suggest. Thanx in advance.
Consider module name is mymodule.
Example of a mymodule.services.yml file
Register an Event Subscriber in your mymodule.services.yml
services:
bssa.route_subscriber:
class: Drupal\bssa\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
class : "Drupal\\mymodule\\Routing\\RouteSubscriber" According to this class create a php file as given below.
Extend the RouteSubscriber to implement the new field form as 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');
}
}
Now create a new form in mymodule/src/Form/ExtendedSiteInformation.php to add the custom field
<?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);
}
}
Now create a config variable to hold the value of the new field inside 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'
After follow the above steps clear the cache and you will see a new field "Site API Key" in the "Site Information" Form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.