Thursday, March 19, 2020

how to send variable from .php file to .js file?(Drupal Behaviours)




You should use drupal_add_js() in your module,there is no need to output the variable in your .tpl.php:

Drupal 7

Step:-1

<?php
$testvar="Hello from alex!";
$variables['testvar'] = $testvar; 
...

drupal_add_js(array('YOURMODULE' => array('testvar' => $testvar)), array('type' => 'setting'));

And in your JavaScript, you can the access the value in Drupal.settings.YOURMODULE.testvar:

alert(Drupal.settings.YOURMODULE.testvar);

Step:-2 In your MODULENAME.module file use the following code.

$testVariable = 'mytest';

drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting'));

drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');

And in MODULENAME.js use the following one.

(function($) {
  Drupal.behaviors.MODULENAME = {
    attach: function (context, settings) {
      alert(settings.MODULENAME.testvar);
    }
  };

})(jQuery);

 Drupal 8

Step 1:- We have to do the same work as we had to do to make jQuery available: we have to declare a dependency on it.

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


Step 2:- In your case. You need use hook_preprocess_node() to add array myfield.

function YOUR_MODULE_preprocess_node($vars) {
  $testvar="Hello from alex!";
  $vars['#attached']['drupalSettings']['myField'] = $testvar;
 $vars['#attached']['drupalSettings']['my_rand'] = rand(2,9999999);
}

and file js/custom.js you need code.

(function($, Drupal, drupalSettings) {
  Drupal.behaviors.yourbehavior = {
    attach: function (context, settings) {
       var myField = drupalSettings.myField.
        alert(myField);

console.log(drupalSettings.my_rand);
    }
  };
})(jQuery, Drupal, drupalSettings);

Step 3:- How do I pass $variables['is_front'] from template_preprocess_page() to a jquery script in Drupal8?

See the step 1

function mytheme_preprocess_page(&$variables) {
   $variables['#attached'] = [
        'drupalSettings' => [
          'myLibrary' => [
            'is_front' => $variables['is_front'],
          ],
        ],
    ];
}

and file js/custom.js you need code.

Drupal.behaviors.myBehaviour = {
    attach: function (context, settings) {

      console.log(settings.myLibrary.is_front);

    }
  };

Step 4:- 

/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$page) {
  $page['#attached']['drupalSettings']['myname'] = 'himanshu';
}

(function ($, Drupal, drupalSettings) {
  /**
   * @namespace
   */
  Drupal.behaviors.mymoduleAccessData = {
    attach: function (context) {
      var data = drupalSettings.myname;
    }
  };
})(jQuery, Drupal, drupalSettings);

Step 5:- Block 
  
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);


In this way, you can pass your PHP variable to JavaScript, and use it.

Step 6:- Call by function?

(function ($, Drupal, drupalSettings) {
    'use strict';
    Drupal.behaviors.myBehavior = {
      attach: function () {
        once('myBehavior', 'html').forEach(function (element) {
            myFunction(element);
        })
      }
    };
})(jQuery, Drupal, drupalSettings);

function  myFunction(data) {
    alert('hi');
    console.log('only call one time')
}
output


No comments:

Post a Comment

If you have any problem please let me know.