Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

Работа с формами конфигурации

01/05/2020, by maria

Использовать $config в контексте формы

Вы можете использовать формы конфигурации, чтобы выяснить, как $config может получить данные, введенные пользователем, и изменить данные в файле {module}.settings.yml. Вот код для объявления объекта $config в форме, которую вы можете найти в PHP-файле настроек формы.

Класс Drupal Core ConfigFactory - это способ чтения и записи данных конфигурации, и он используется для создания экземпляра объекта Config на основе содержимого указанного файла конфигурации. Новый объект Config может затем использоваться для выполнения операций CRUD с этими данными.

Config

Пример определения формы (находится в example/src/Form/exampleSettingsForm.php):

namespace Drupal\example\Form;

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

/**
 * Configure example settings for this site.
 */
class ExampleSettingsForm extends ConfigFormBase {

  /** 
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'example.settings';

  /** 
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'example_admin_settings';
  }

  /** 
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      static::SETTINGS,
    ];
  }

  /** 
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config(static::SETTINGS);

    $form['example_thing'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Things'),
      '#default_value' => $config->get('example_thing'),
    ];  

    $form['other_things'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Other things'),
      '#default_value' => $config->get('other_things'),
    ];  

    return parent::buildForm($form, $form_state);
  }

  /** 
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration.
    $this->configFactory->getEditable(static::SETTINGS)
      // Set the submitted configuration setting.
      ->set('example_thing', $form_state->getValue('example_thing'))
      // You can set multiple configurations at once by making
      // multiple calls to set().
      ->set('other_things', $form_state->getValue('other_things'))
      ->save();

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

}

Файл маршрутизации (example.routing.yml):

example.settings:
  path: '/admin/config/example/settings'
  defaults:
    _form: '\Drupal\example\Form\ExampleSettingsForm'
    _title: 'example'
  requirements:
    _permission: 'administer site configuration'

Используя объект Config, вы можете упростить ваши данные, собранные из формы. Имея указанный выше код в файле настроек формы, вы сможете хранить данные формы в {module}.settings.yml.

Любой класс, который расширяет ConfigFormBase, должен реализовывать метод getEditableConfigNames и возвращать массив имен полей конфигурации, которые он редактирует.

Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.