如何添加在Drupal 8新的自定义字段“网站信息”表

问题描述 投票:2回答:1

我想添加在Drupal8一个新的自定义字段“网站信息来源”的形式。我已经尝试了许多答案,但没有得到妥善解决。有什么办法可以添加自定义字段。请建议。 Thanx提前。

php drupal-8
1个回答
2
投票

考虑模块名称是MyModule的。

一个mymodule.services.yml文件的例子

在您的mymodule.services.yml注册事件用户

services:
  bssa.route_subscriber:
    class: Drupal\bssa\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

类:下面给出“Drupal的\ MyModule的\路由\ RouteSubscriber”根据这个类来创建一个PHP文件。

扩展RouteSubscriber实施新的领域形式mymodule中/ src目录/路由/ 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目录/表格/ 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中/配置/模式/ 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密钥”。

© www.soinside.com 2019 - 2024. All rights reserved.