フィールドフォーマッターの作成
フィールドフォーマッターモジュールは、最終ユーザーが表示できるようにフィールドデータをフォーマットします。フィールドフォーマッターはプラグインとして定義されるため、新しいフィールドフォーマッターの作成を始める前にプラグインAPIを確認することをお勧めします。
フィールドフォーマッタークラス
ファイル: /modules/random/src/Plugin/Field/FieldFormatter/RandomDefaultFormatter.php
<?php
namespace Drupal\random\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Plugin implementation of the 'Random_default' formatter.
*
* @FieldFormatter(
* id = "Random_default",
* label = @Translation("Random text"),
* field_types = {
* "Random"
* }
* )
*/
class RandomDefaultFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = $this->t('Displays the random string.');
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
foreach ($items as $delta => $item) {
// Render each element as markup.
$element[$delta] = ['#markup' => $item->value];
}
return $element;
}
}
フォーマッターの設定
フォーマッターにカスタム表示設定が必要な場合は、次の3つの手順を実行する必要があります:
- PluginSettingsBase::defaultSettings()をオーバーライドしてデフォルト値を設定します
- 作成した設定の設定スキーマを作成します
- ユーザーが設定を変更できるようにフォームを作成します
ステップ1:デフォルト値を設定するためにPluginSettingsBase::defaultSettings()をオーバーライドします
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
// Declare a setting named 'text_length', with
// a default value of 'short'
'text_length' => 'short',
] + parent::defaultSettings();
}
ステップ2:作成した設定の設定スキーマを作成します
設定スキーマは次のファイルにあります:
[MODULE ROOT]/config/schema/[MODULE_NAME].schema.yml
このファイルでは、defaultSettings()で作成した設定データのタイプを記述します:
ステップ1は、文字列値を格納する「text_length」という名前の設定を作成しました。これのスキーマは次のようになります:
field.formatter.settings.[FORMATTER ID]:
type: mapping
label: 'FORMATTER NAME text length'
mapping:
text_length:
type: string
label: 'Text Length'
ステップ3:ユーザーが設定を変更できるようにフォームを作成します
ユーザーが設定値を変更できるようにするフォームは、FormatterBase::settingsForm().をオーバーライドして作成されます。
PHPファイルの先頭にフォーム状態の名前空間を追加することを忘れないでください。
use Drupal\Core\Form\FormStateInterface;
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form['text_length'] = [
'#title' => $this->t('Text length'),
'#type' => 'select',
'#options' => [
'short' => $this->t('Short'),
'long' => $this->t('Long'),
],
'#default_value' => $this->getSetting('text_length'),
];
return $form;
}
設定フォームでの#ajaxの使用
設定フォームで#ajaxを使用することは簡単ではありません。settingsForm()で作成されたフォームフラグメントはフォームのルートではなく、深くネストされているためです。以下の例では、フォームには2つの設定があります:display_type(「label」または「entity」のいずれか)とentity_display_mode(「full」または「teaser」)。エンティティ表示モードは、display_typeが「entity」に設定されている場合にのみ表示されます。
public function settingsForm(array $form, FormStateInterface $form_state) {
$form['display_type'] = [
'#title' => $this->t('Display Type'),
'#type' => 'select',
'#options' => [
'label' => $this->t('Label'),
'entity' => $this->t('Entity'),
],
'#default_value' => $this->getSetting('display_type'),
'#ajax' => [
'wrapper' => 'private_message_thread_member_formatter_settings_wrapper',
'callback' => [$this, 'ajaxCallback'],
],
];
$form['entity_display_mode'] = [
'#prefix' => '<div id="private_message_thread_member_formatter_settings_wrapper">',
'#suffix' => '</div>',
];
// First, retrieve the field name for the current field]
$field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName();
// Next, set the key for the setting for which a value is to be retrieved
$setting_key = 'display_type';
// Try to retrieve a value from the form state. This will not exist on initial page load
if($value = $form_state->getValue(['fields', $field_name, 'settings_edit_form', 'settings', $setting_key])) {
$display_type = $value;
}
// On initial page load, retrieve the default setting
else {
$display_type = $this->getSetting('display_type');
}
if($display_type == 'entity') {
$form['entity_display_mode']['#type'] = 'select';
$form['entity_display_mode']['#title'] = $this->t('View mode');
$form['entity_display_mode']['#options'] = [
'full' => $this->t('Full'),
'teaser' => $this->t('Teaser'),
];
$form['entity_display_mode']['#default_value'] = $this->getSetting('entity_display_mode');
}
else {
// Force the element to render (so that the AJAX wrapper is rendered) even
// When no value is selected
$form['entity_display_mode']['#markup'] = '';
}
return $form;
}
次に、ajaxコールバックを作成し、対応するフォーム要素を返します:
public function ajaxCallback(array $form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName();
$element_to_return = 'entity_display_mode';
return $form['fields'][$field_name]['plugin']['settings_edit_form']['settings'][$element_to_return];
}
フィールドフォーマッターへの依存関係の注入
フィールドフォーマッターで依存関係の注入を使用するには、3つの手順が必要です:
- ContainerFactoryPluginInterfaceインターフェースを実装します
- ContainerFactoryPluginInterface::create()を実装します
- FormatterBase::__construct()をオーバーライドします
1) ContainerFactoryPluginInterfaceインターフェースの実装
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
class MyFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
2) ContainerFactoryPluginInterface::create()の実装
この例では、entity.managerサービスをフォーマッターに注入します
use Symfony\Component\DependencyInjection\ContainerInterface;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
// Add any services you want to inject here
$container->get('entity.manager')
);
}
3) FormatterBase::__construct()のオーバーライド
FormatterBaseで__construct()をオーバーライドし、必ずparent::__construct()を呼び出してから、サービスをクラスのプロパティに保存します
use Drupal\Core\Field\FieldDefinitionInterface;
/**
* The entity manager service
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Construct a MyFormatter object.
*
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* Defines an interface for entity field definitions.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings.
* @param \Drupal\Core\Entity\EntityManagerInterface $entityManager
* Entity manager service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityManagerInterface $entityManager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->entityManager = $entityManager;
}
これで、フォーマッタークラスのどこでも$this->entityManagerとしてエンティティマネージャーを使用できます。