编程语言
首页 > 编程语言> > php-Drupal 8:如何自定义表单小部件以显示实体字段值而不是实体标题?

php-Drupal 8:如何自定义表单小部件以显示实体字段值而不是实体标题?

作者:互联网

我正在通过开发自定义表单窗口小部件模块迈出第一步,以了解Drupal 8的工作原理.我的目标是显示参考节点的图像字段值,而不是在单选按钮列表(核心中可用)中显示其节点标题.这将使网站管理员在为节点选择背景图像时选择图片而不是文本.

这是使用Drupal 8内置的“复选框/单选按钮”小部件而无需自定义工作的情况下的外观:

Drupal 8's built-in "Check boxes/radio buttons" widget example

这是我希望我的自定义小部件出现(至少开始)的Photoshop样机:

Photoshop mockup of how I want my custom widget to appear

到目前为止,我已经能够创建一个扩展“复选框/单选按钮”小部件的启动模块,引用Examples for Developers模块并遍历核心.至少这帮助我至少了解了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.module:

<?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).我需要继承一个曾祖父母并重新开始吗?我猜我需要进一步探索依赖项注入吗?关于如何总体或详细进行任何想法?我会灵活回答,只要能帮助我克服这一难题即可.

解决方法:

您无需创建自定义窗口小部件.

编辑您的字段,并将“引用方法”从“默认”设置为“视图:按实体引用视图过滤”.然后,它将告诉您以下信息(如果尚未定义实体引用视图):

No eligible views were found. Create a view with an Entity Reference
display, or add such a display to an existing view.

因此,然后继续创建该实体引用视图(/ admin / structure / views),返回到您的字段并再次选择它,现在您应该可以选择该视图了.

创建实体参考视图时,可以定义要显示的实体字段(而不是实体标题或附加于实体标题-正是您想要的).因此,实际上您不需要为此功能编写任何代码,只需配置即可.

编辑:

正如问问者所指出的那样,这不是开箱即用的.我找到了一个启用所需功能的模块(实体参考视图的窗体小部件):

https://www.drupal.org/project/entity_reference_views_select

该模块似乎仅为实体参考视图启用选择和复选框小部件.

如果需要更复杂的配置,则实体浏览器:
https://www.drupal.org/project/entity_browser
看起来,它也在大力发展. (均未经我测试)

标签:drupal-8,module,widget,drupal,php
来源: https://codeday.me/bug/20191027/1941204.html