こちらのサイトではDRUPAL10に関連する記事を掲載しています。
Drupalでは「モジュール」と呼ばれる、小さなソフトウェアを実装することで機能拡張を行います。本ウェビナーシリーズでは、Drupalのモジュール開発に関する基礎知識を解説します。Drupalのバックエンド周りについて体系的に学びたい方、自分でカスタムモジュールを作れるようになりたい方、アクイア認定デベロッパー試験を目指す方におすすめです。
Drupalを一通り操作したことがある方を対象としています。まだDrupalを触ったことが無い方は、初心者向けDrupalチュートリアル動画(日本語)を先に見ておくとより理解が深まります。
DrupalのForm APIとは
DrupalのFormは以下のようにさまざま

これらはFormAPIで実装されている
FormAPIとは

FormAPIのメリット

SQLインジェクション対策など実装者側が特に意識しなくても適切なHTMLコードを作成してくれる
フォーム実装の流れ


フォームクラスを用意する
モジュールのディレクトリの直下に以下のファイルを作成する

メソッドを実装する
<?php
namespace Drupal\test123form_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class Test123Form extends FormBase {
public function getFormId() {
return "my_form";
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['name'] = [
'#type' => 'textfield',
'#title' => '名前',
];
$form['submit'] = [
'#type' => 'submit',
'#value' => '送信',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->messenger()->addStatus('ご入力ありがとうございました!');
}
}
yamlファイルを設定する
INFOファイルを作成する
name: test123form module
type: module
description: 'FORM機能をテストするモジュール'
package: Custom
core_version_requirement: ^8.7.7 || ^9 || ^10
ルーティングを設定する
test123form_module.form:
path: '/testform'
defaults:
_form: '\Drupal\test123form_module\Form\Test123Form'
_title: 'Test form page'
requirements:
_permission: 'access content'
フォームの種類
種類

関係性

FormBaseが一般的に使用されるフォーム用のベースクラス。
ConfigFormBaseは設定画面用に拡張されたもの、ConfirmFormBaseは確認画面用に拡張されたもので、それぞれベースになるものはFormBaseである。
FormBase

ConfigFormBase

ConfirmFormBase

フォームクラスのメソッド
getFormId()
フォームに一意のIDを付与するために必要
※必ず一意になるように設定すること
buildForm()
HTMLを生成する

validateForm()
バリデーションチェックが必要な場合に使用する
※FormBaseを拡張するクラスはオプション

submitForm()

フォームのレンダリング
フォーム配列は、HTMLフォームを構築するための連想配列。
要素と属性を連想配列で指定する
- 属性は#をつける
- 要素は#をつけない

指定可能な属性の例

指定可能な属性の詳細についてはこちらを参照
指定可能な属性の例


フォームの取得と表示
フォームの変更
練習問題

この記事またはDrupalに関するご質問がございましたら、お気軽にお問い合わせください。