我正在通过开发自定义表单小部件模块来迈出了解 Drupal 8 在幕后如何工作的第一步。我的目标是显示引用节点的图像字段值,而不是单选按钮列表中的节点标题(在核心中可用)。这将允许网站管理员在为节点选择背景图像时选择图片而不是文本。
以下是我的表单在没有自定义工作的情况下的外观,使用 Drupal 8 的内置“复选框/单选按钮”小部件:
这是我希望自定义小部件如何显示(至少开始时)的 Photoshop 模型:
到目前为止,我已经能够创建一个扩展“复选框/单选按钮”小部件的启动模块,引用开发人员示例 https://www.drupal.org/project/examples模块和遍历核心。这至少帮助我更好地理解了 Drupal 8 的模块结构。
模块结构:
modules
custom
back_image_widget
back_image_widget.info.yml
back_image_widget.module
src
Plugin
Field
Field Widget
BackImageWidget.php
back_image_widget.info.yml:
name: Background Image Entity Widget
type: module
description: Used to list Background Image entities as images instead of text labels in the Text Message content type form.
package: Custom
core: 8.x
back_image_widget.模块:
<?php
/**
* @file
* Used to list Background Image entities as images instead of text labels in the Text Message content type form.
*/
BackImageWidget.php:
<?php
/**
* @file
* Contains \Drupal\back_image_widget\Plugin\Field\FieldWidget.
*/
namespace Drupal\back_image_widget\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsButtonsWidget;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'field_back_image' widget.
*
* @FieldWidget(
* id = "field_back_image",
* module = "back_image_widget",
* label = @Translation("Background Image Entity"),
* field_types = {
* "entity_reference"
* },
* multiple_values = FALSE
* )
*/
class BackImageWidget extends OptionsButtonsWidget {
//Here we go!
}
这样,我就可以安装模块,选择新的小部件,并拥有核心提供的所有预期功能来启动。
从这里开始,我很难从父类中识别出需要更改的最佳部分,以便我可以用其他实体值替换标题。最有用的功能似乎受到了保护。结果选项返回受保护的标题(没有其他可用信息,例如要使用的节点 ID)。我需要继承曾祖父母并重新开始吗?我猜我需要进一步探索依赖注入?关于如何进行一般性或细节性的任何想法?我对答案很灵活,只要它能帮助我克服这个困境。