logo

パレット - カラフルに🎨

Palette — ビジュアルページビルダー、デザインの専門知識は不要です。

ライブデモ パレットをダウンロード

Scroll
24/04/2020, by maria

Menu

パートIV:Drupal 8の基本モジュール作成の実践ガイド
.infoからテストまで、基礎のみ

これまでのところかなりきれいですが、表示されるものをどのように変更できるでしょうか?もちろん、いくつかのフォームを使ってです。

簡単なユースケースについては、「サイト設定とラベル」を参照してください。

/src/Form/LoremIpsumForm.php

<?php

namespace Drupal\loremipsum\Form;

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

class LoremIpsumForm extends ConfigFormBase {

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

ConfigFormBaseを拡張する設定ファイルを開始します。LoremIpsumFormクラスは、routing.ymlファイルで指定されたクラスです。

次に、実際に設定フォームを構築するメソッドがあります:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Form constructor.
    $form = parent::buildForm($form, $form_state);
    // Default settings.
    $config = $this->config('loremipsum.settings');

$config変数は、現在の設定を保存する場所です。

次に、フォームフィールドを定義してフォームを返します:

    // Page title field.
    $form['page_title'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Lorem ipsum generator page title:'),
      '#default_value' => $config->get('loremipsum.page_title'),
      '#description' => $this->t('Give your lorem ipsum generator page a title.'),
    );
    // Source text field.
    $form['source_text'] = array(
      '#type' => 'textarea',
      '#title' => $this->t('Source text for lorem ipsum generation:'),
      '#default_value' => $config->get('loremipsum.source_text'),
      '#description' => $this->t('Write one sentence per line. Those sentences will be used to generate random text.'),
    );

    return $form;
  }

使用しない場合でも、validateForm()、submitForm()、getEditableConfigNames()メソッドを宣言する必要があります:

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('loremipsum.settings');
    $config->set('loremipsum.source_text', $form_state->getValue('source_text'));
    $config->set('loremipsum.page_title', $form_state->getValue('page_title'));
    $config->save();
    return parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'loremipsum.settings',
    ];
  }

}