首页 > 解决方案 > 未定义的函数'field_widget_instance

问题描述

在 Drupal 9 迁移自定义模块中出现错误

function sun_link_field_process($element, $form_state, $complete_form) {
  $instance = field_widget_instance($element, $form_state);
  $settings = $instance['settings'];

标签: drupal-8drupal-modules

解决方案


这是 Drupal 7 字段 API,它只需要转换为 D9.x。还要注意,它现在非常不同,需要在一个类中并使用注释来正确定义。

几天前,我看到一个叫“samtech”的人询问了这个完全相同的功能。

function sun_link_field_process($element, $form_state, $complete_form) {
  $instance = **field_widget_instance**($element, $form_state);
  $settings = $instance['settings'];
  $attributes = isset($element['#value']['attributes']) ? $element['#value']['attributes'] : $settings['attributes'];
  $element['attributes']['link_classes'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom link classes'),
    '#description' => t('A space delimited list of custom classes to be applied to the link.'),
    '#default_value' => isset($attributes['link_classes']) ? $attributes['link_classes'] : '',
    '#field_prefix' => 'class="',
    '#field_suffix' => '"',
  );
  return $element;
}

假设这是完整功能,只需查看/core/modules/image/src/Plugin/Field/FieldWidget/ImageWidget.php以了解如何在 D9 中的表单小部件元素上应用“流程”。但请注意,您的函数完全存在表明该字段的其余部分也没有正确定义?

  /**
   * Form API callback: Processes an image_image field element.
   *
   * Expands the image_image type to include the alt and title fields.
   *
   * This method is assigned as a #process callback in formElement() method.
   */
  public static function process($element, FormStateInterface $form_state, $form) {

推荐阅读