1

I'm using Drupal 8.

What I'm trying to do is:

  • Access the active node
  • From the node get the value of field_test and assign it to a variable
  • Pass the variable to the drupalSettings function and subsequently to a custom module 'mycustommodule' that triggers an alert

In my content type, I created a field_test field, which is the field I reference in my code. The block is placed on a page of this content type.

This is the JavaScript code I am using.

mycustomblock.libraries.yml

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

custom.js

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.mycustomblock = {
    attach: function (context, settings) {
      var testMe = drupalSettings.mycustomblock.test;
      alert(testMe);

  }
};
})(jQuery, Drupal, drupalSettings);

The error I get from the JavaScript console is this.

Drupal is undefined

The error message is referring to this line.

Drupal underlined in code

Why is the instance of Drupal in the closing parenthesis throwing this error?

5

You will have to add the core library core/drupal to your library dependencies. This assures, that the Drupal core JavaScript is loaded before your custom module's JavaScript will be executed.

So your mycustomblock.libraries.yml should look like:

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
  • With the code shown from the OP, it is impossible to get any error, simply because the JavaScript code is not even attached to the page. – kiamlaluno Dec 30 '17 at 6:21
  • @kiamlaluno: Which you already stated in his previous question. I agree that the question's code is incomplete and non-functional. The fact that an error message was posted led me to assume he fixed the inclusion of the library. So my answer was limited to the missing core library (as suggested by the question's title). – Mario Steinitz Dec 30 '17 at 6:31
  • I had set the other question as duplicate of this one. Now I removed the part answered from the other question, and called them two different questions. Differently, this question would not make much sense, since the OP would report an error message impossible to get with the shown code. Plus, somebody could have answered repeating what already said to the OP. – kiamlaluno Dec 30 '17 at 6:38
  • Was just about to add an edit to the answer regarding the wrong inclusion. Seems you already did an according clean-up as well. Thanks for your hard work as moderator to keeping the quality of Drupal Answers up. – Mario Steinitz Dec 30 '17 at 6:43

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.