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 code I am using.
mycustomblock.libraries.yml
custom:
version: 1.x
js:
js/custom.js: {}
dependencies:
- core/jquery
- core/drupalSettings
MyCustomBlock.php
<?php
/**
* @file
*
*/
namespace Drupal\mycustomblock\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Creates a 'Foobar' Block
*
* @Block(
* id = "block_mycustomblock",
* admin_label = @Translation("MyCustomBlock"),
* category = @Translation("Blocks")
* )
*/
class MyCustomBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
// get the variable from field_test
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$test = $node->field_test->value;
$variables['#attached']['library'][] = 'mycustomblock/custom';
$build['#attached']['drupalSettings']['mycustomblock']['test'] = $test;
}
}
custom.js
(function ($, Drupal, drupalSettings) {
var testMe = Drupal.settings.mycustomblock.test;
alert(testMe);
)(jQuery, drupalSettings);
How can I tell if the JavaScript file is being loaded from the block? I checked in the inspector, and do not see it being loaded when the page with the block on it loads.
Furthermore, how can I properly access the field value and pass it to JavaScript?