Using Drupal 8 Entity Field Values In Javascript

Submitted by Brian on August 22, 2016 - 10:52am
Uising Drupal Behaviors to retrieve variables

With modern javascript frameworks and client-side page processing, the ability to pass your Drupal variables to JS opens up many opportunities. In my case, I needed to create a content type that allowed the author to fill out values that would the be used in a dynamic chart for display. I decided on using the ChartJS V2 framework to achieve this, so I needed to get the values on the 'currently viewed' node, and provide access to my JS function.

There are a few places you can do this, but it made sense for me to create a module for this function

First, I need a function that can add my JS library (for my use case, I used page_attachments_alter:

 function module_page_attachments_alter(array &$page) {
    $page['#attached']['library'][] = 'module_name/main';

Next I create the module_name.libraries.yml file to point to my JS files (and declare any dependencies)

 module_name/main:
  version: 1.x
  js:
    js/Chart.js: {}
    js/main.js: {}
  dependencies:
    - core/jquery

Now that the JS file is loading, I can go back to my function and load the node and add my field variables I want to pass with Drupal Behaviors.

 //Load the node
$node = \Drupal::routeMatch()->getParameter('node');

//only load the node if page is of content type: article
if (is_object($node) && $node != null && $node->getType() == 'article') {
    $node->id();

// only get the field value, save them as variables
    $field1= $node->field_field1->value;
    $field2 = $node->field_field2->value;
    $field3 = $node->field_field3->value;

// Pass the field values to JS

    $page['#attached']['drupalSettings']['module_name']['main']['field1'] =  $field1;
    $page['#attached']['drupalSettings']['module_name']['main']['field2'] =  $field2;
    $page['#attached']['drupalSettings']['module_name']['pokemon']['field3'] =  $field3;

Now, in my main.js file, add the behaviors

(function($, Drupal, drupalSettings) {
  Drupal.behaviors.main = {
    attach: function(context, settings) {

field1 = drupalSettings.my_module.main.field1;
field2 = drupalSettings.my_module.main.field2;
field3 = drupalSettings.my_module.main.field3;

})(jQuery, Drupal, drupalSettings);

If you run console.log after this, you should see your values there!
console.log(field1);