Drupal → Добавить в основные настройки сайта свою опцию

22.01.2020

Пример добавления в основные настройки сайта поля для ввода телефона:

1. Альтерим форму system_site_information_settings:

// MODULENAME.module

/**
 * Implements hook_form_FORM_ID_alter(): system_site_information_settings.
 *
 * @see \Drupal\system\Form\SiteInformationForm
 */
function MODULENAME_form_system_site_information_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['site_information']['site_phone'] = [
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#default_value' => \Drupal::config('system.site')->get('phone'),
  ];

  $form['#submit'][] = 'MODULENAME_form_system_site_information_settings_submit';
}

/**
 * Custom submit callback for system_site_information_settings form.
 *
 * @see MODULENAME_form_system_site_information_settings_alter()
 */
function MODULENAME_form_system_site_information_settings_submit(array &$form, FormStateInterface $form_state) {
  \Drupal::configFactory()->getEditable('system.site')
    ->set('phone', $form_state->getValue('site_phone'))
    ->save();
}

2. Добавляем схему для новой конфигурации:

// MODULENAME.module

/**
 * Implements hook_config_schema_info_alter().
 */
function MODULENAME_config_schema_info_alter(array &$definitions) {
  $definitions['system.site']['mapping']['phone'] = [
    'type' => 'string',
    'label' => 'Site phone',
  ];
}

3. Ну и по желанию добавляем токен [site:phone]:

// MODULENAME.tokens.inc

/**
 * Implements hook_token_info().
 */
function MODULENAME_token_info() {
  $info['tokens']['site']['phone'] = [
    'name' => t('Site phone'),
    'description' => t('Site phone'),
  ];

  return $info;
}

/**
 * Implements hook_tokens().
 */
function MODULENAME_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'site') {
    foreach ($tokens as $name => $original) {
      if ($name == 'phone') {
        $replacements[$original] = \Drupal::config('system.site')->get('phone');
      }
    }
  }

  return $replacements;
}
Написанное актуально для
Drupal 8+
Похожие записи

Добавить комментарий