フィールドウィジェットの作成
フィールドウィジェットは、フォーム内でフィールドをレンダリングするために使用されます。フィールドウィジェットはプラグインとして定義されるため、新しいフィールドタイプの作成を始める前にプラグインAPIを確認することをお勧めします。
Drupal 8でフィールドウィジェットを作成するには、FieldWidgetアノテーションを持つクラスが必要です。
配置場所フィールドウィジェットクラスは /[MODULE_NAME]/src/Plugin/Field/FieldWidgetにある必要があります。例:/foo/src/Plugin/Field/FieldWidget/BarWidget.php。
名前空間このクラスの名前空間は [MODULE_NAME]\Plugin\Field\FieldWidgetである必要があります。例:\Drupal\foo\Plugin\Field\FieldWidget。
アノテーションクラス上のアノテーションには、一意のID、ラベル、およびこのウィジェットが処理できるフィールドタイプIDの配列を含める必要があります。
/**
* A widget bar.
*
* @FieldWidget(
* id = "bar",
* label = @Translation("Bar widget"),
* field_types = {
* "baz",
* "string"
* }
* )
*/
クラスはWidgetInterfaceインターフェースを実装する必要があります。また、インターフェースの一般的な実装のためにWidgetBaseクラスを拡張できます。実装に必要な唯一のメソッドは::formElement()で、これはウィジェットを表す実際のフォーム要素を返す必要があります。
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
//...
class BarWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = [];
// Build the element render array.
return $element;
}
}
ウィジェットの設定
ウィジェットに追加の設定が必要な場合は、次の3つの手順を実行する必要があります:
- PluginSettingsBase::defaultSettings()をオーバーライドしてデフォルト値を設定します
- 作成した設定の設定スキーマを作成します
- ユーザーが設定を変更できるようにフォームを作成します
ステップ1:デフォルト値を設定するためにPluginSettingsBase::defaultSettings()をオーバーライドします
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
// Create the custom setting 'size', and
// assign a default value of 60
'size' => 60,
] + parent::defaultSettings();
}
ステップ2:作成した設定の設定スキーマを作成します
設定スキーマは次のファイルにあります:
/[MODULE_NAME]/config/schema/[MODULE_NAME].schema.yml
このファイルでは、defaultSettings()で入力した設定データのタイプを記述します:
ステップ1は、整数値を格納する「size」という名前の設定を作成しました。これのスキーマは次のようになります:
field.widget.settings.[WIDGET ID]:
type: mapping
label: 'WIDGET NAME widget settings'
mapping:
size:
type: integer
label: 'Size'
ステップ3:ユーザーが設定を変更できるようにフォームを作成します
ユーザーが設定値を変更できるようにするフォームは、WidgetBase::settingsForm()をオーバーライドして作成されます。
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['size'] = [
'#type' => 'number',
'#title' => $this->t('Size of textfield'),
'#default_value' => $this->getSetting('size'),
'#required' => TRUE,
'#min' => 1,
];
return $element;
}
次のように、ウィジェットの概要に選択した設定を一覧表示することもできます:
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = $this->t('Textfield size: @size', array('@size' => $this->getSetting('size')));
return $summary;
}
クラスのgetSetting()メソッドを使用して、ウィジェットで使用する設定を取得できます:
class BarWidget extends WidgetBase implements WidgetInterface {
class BarWidget extends WidgetBase implements WidgetInterface {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['value'] = $element + [
'#type' => 'textfield',
'#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
'#size' => $this->getSetting('size'),
];
return $element;
}
}
ウィジェットの例
Examplesモジュールのfield_exampleモジュールのTextWidget:
namespace Drupal\field_example\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'field_example_text' widget.
*
* @FieldWidget(
* id = "field_example_text",
* module = "field_example",
* label = @Translation("RGB value as #ffffff"),
* field_types = {
* "field_example_rgb"
* }
* )
*/
class TextWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';
$element += [
'#type' => 'textfield',
'#default_value' => $value,
'#size' => 7,
'#maxlength' => 7,
'#element_validate' => [
[static::class, 'validate'],
],
];
return ['value' => $element];
}
/**
* Validate the color text field.
*/
public static function validate($element, FormStateInterface $form_state) {
$value = $element['#value'];
if (strlen($value) == 0) {
$form_state->setValueForElement($element, '');
return;
}
if (!preg_match('/^#([a-f0-9]{6})$/iD', strtolower($value))) {
$form_state->setError($element, t("Color must be a 6-digit hexadecimal value, suitable for CSS."));
}
}
}