Drupal 8 自定义模块 - 如何在管理区域创建一个字段,然后将该输入拉到我的模块中使用?

Drupal 8 Custom module - how to create a field in the admin area, and then pull that input in my module to use?

我是 Drupal 8 的新手,来自 WP 世界,所以很难掌握事情的窍门。我创建了一个自定义模块并有一个页面输出文本。我卡住的地方是能够在管理区域创建一个字段,提取保存的信息,然后在我正在输出的内容中使用它。

一直在按照教程进行操作,但非常卡住。任何人都可以为我提供路线图或有用的文章来实现这一目标吗?

假设您的模块名称是“custom”,然后按照以下步骤创建管理表单并在管理页面上提取保存的信息。

创建文件夹名称“custom”。

在 "custom" 文件夹中创建“custom.info.yml”文件。

name: custom
description: Show admin saved data through custom module.
type: module
# core: 8.x
configure: admin/config/services/custom

为访问管理表单的人员创建权限。
对于权限,在 "custom" 文件夹中创建“custom.permissions.yml”文件。

'administer custom':
  'title': 'Administer Customform'
  'description': 'Configure how Custom Form is used on the site.'
  restrict access: true

然后为自定义管理表单路径及其内容创建路由。

在 "custom" 文件夹中创建“custom.routing.yml”文件。

custom.config:
  path: '/admin/config/custom/config'
  defaults:
    _form: '\Drupal\custom\Form\CustomConfigForm'
    _title: 'Custom Configuration'
  requirements:
    _permission: 'administer custom'

现在创建一个菜单并在菜单路径中分配此路径 ("custom.config") 并在自定义文件夹中创建一个表单,表单位置为 src/Form/CustomConfigForm.php

对于菜单,在 "custom" 文件夹中创建一个“custom.links.menu.yml”文件。

custom.config:
  title: 'Custom '
  description: 'Custom Admin Configuration'
  parent: system.admin_config
  route_name: custom.config
  weight: 100

对于管理表单,在自定义文件夹中创建 CustomConfigForm.php 文件,文件位置为 src/Form/CustomConfigForm.php

<?php

namespace Drupal\custom\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class CustomConfigForm extends ConfigFormBase {

    public function getFormId() {
        return 'custom_config_form';
    }


    public function buildForm(array $form, FormStateInterface $form_state) {

    $config = $this->config('custom.settings');  // store data in custom.settings


    $form = parent::buildForm($form, $form_state);

    $form['custom_types'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Content Types'),
      '#description' => t('Configure where the custom button should appear.'),
      '#options' => node_type_get_names(),
      '#default_value' => $config->get('custom_types', array()),
    );

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('custom.settings');
    $config->set('custom_types', $form_state->getValue('custom_types')); 
    $config->save(); // save data in custom.settings

    return parent::submitForm($form, $form_state);

  }

  public function getEditableConfigNames() {
    return ['custom.settings'];
  }

}

现在当您保存管理表单时,然后在您获取 "custom.module" 文件中保存的数据后使用此代码。

在自定义文件夹中创建 "custom.module" 文件。

$config =  \Drupal::config('custom.settings');  // get saved settings
$types = $config->get('custom_types', array()); // fetch particular saved data "custom_types"
print $types;

现在启用这个模块。
您的管理表单路径是 YOUR_SITE_NAME/admin/config/custom/config

同样在 Drupal 8 中有时会出现缓存问题,因此如果出现任何问题,请在保存表单后清除缓存。