1

Cross-posting to stackoverflow.com

I am creating a custom field to eventually be displayed in a custom paragraph. I need to upload a JS file for the widget view, but can't seem to get it to work. Can anyone see what I am doing wrong or need to do differently?

I can add the field to the paragraph, add the paragraph to a document and see the fields, but I see no evidence of the JS being attached (the file is not downloaded in the browser and does not activate).

Any help or suggestions are appreciated.

file: src/Plugin/Field/FieldWidget/get_libguides_listings_widget.php:

<?php

namespace Drupal\get_libguides_listings\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

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;
  }
}

file: get_libguides_listings.libraries.yml:

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

file: js/get_searchby.js

/**
 * @file
 */
(function(){
  alert('hello there');

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

1 Answer 1

3

You forgot the library key:

$element['Subject_IDs']['#attached']['library'][] = 'get_libguides_listings/get_searchby';
2
  • 1
    We’ve all been there @KevinFinkenbinder ;)
    – Clive
    Jan 24, 2019 at 17:13
  • guilty as charged ^^
    – dickwan
    Oct 16, 2021 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.