将JS添加到在我的模块中创建的字段小部件 - Drupal 8



交叉发布到 drupal.stackexchange.com

我正在创建一个自定义字段,最终显示在自定义段落中。 我需要为小部件视图上传一个 JS 文件,但似乎无法让它工作。 任何人都可以看到我做错了什么或需要做不同的事情吗?

我可以将字段添加到段落

中,将段落添加到文档中并查看字段,但我没有看到附加 JS 的证据(该文件未在浏览器中下载且未激活)。

任何帮助或建议不胜感激。

文件: src/Plugin/Field/FieldWidget/get_libguides_listings_widget.php:

<?php
namespace Drupalget_libguides_listingsPluginFieldFieldWidget;
use DrupalCoreFieldFieldItemListInterface;
use DrupalCoreFieldWidgetBase;
use DrupalCoreFormFormStateInterface;
class get_libguides_listings_widget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(
               FieldItemListInterface $items,
               $delta, array $element, array &$form,
               FormStateInterface $form_state) {
    $element['Subject_IDs'] = [
      '#type'=>'textfield',
      '#title'=>$this->t('Subject IDs to Display'),
      '#description'=>$this->t('BLAH'),
      '#default_value'
           =>isset($items->getValue()[$delta]['Subject_IDs'])
          ?$items->getValue()[$delta]['Subject_IDs']
          :'',
      '#states'=>[
        'visible' => [
          [':input[name$="default_value_input[field_libguides_listing][0][SearchBy]"]'
                =>['value'=>'subject']],
          'or',
          [':input[name$="default_value_input[field_libguides_listing][0][SearchBy]"]'
                =>['value'=>'both']],
        ],
      ],
    ];
    $element['Subject_IDs']['#attached'][] 
          = 'get_libguides_listings/get_searchby';
    return $element;
  }
}

文件: get_libguides_listings.libraries.yml:

get_searchby:
  js:
    js/get_searchby.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

文件: JS/get_searchby.js

/**
 * @file
 */
(function(){
  alert('hello there');
  (function ($, Drupal)
  {
    Drupal.behaviors.get_searchby = {
      attach: function (context, settings)
      {
        alert('hello');
      }
    };
  }(jQuery, Drupal));
}());

原来我忘记了"库"键$element['Subject_IDs']['#attached']['library'][] = ...

最新更新