I have form. On form submit I would like to call JS function by passing it's value form PHP.

I know we can do on Submit onClick event of form. But I have different requirement.

I need to pass some variables from PHP to JS function/file & process them

   public function submitForm(array &$form, FormStateInterface $form_state) {
      // Call JS Function from PHP

I'm integrating GA Events. So need to pass variables.

  • Your code doesn't make sense - do you want to do a redirect, or do you want to do JS? If you want to do both, the JS would go on the 'welcome' page you have redirected to, not on the page you are redirecting from. – Jaypan Apr 9 '18 at 2:48
  • @Jaypan I updated the question. I will get some values in PHP then I need to pass it to JS file or Function. So can process it's value – Mighty Apr 9 '18 at 2:51
  • The simple answer is that you cannot call a JS function from a submit handler. Can you update the question and tell us what you are trying to do? Right now, you are telling us how you are trying to do something, but you haven't explained what that something is. – Jaypan Apr 9 '18 at 2:53
  • @Jaypan. I'm intergrating GA Events. Some of the events I'm able to add via JS. But some requires on PHP Side. Not able to find perfect library via Composer module. – Mighty Apr 9 '18 at 2:58
  • That's not really enough to understand what you are trying to do. But you can pass variables from php to JS using drupalSettings: drupal.org/node/2274843 – Jaypan Apr 9 '18 at 3:02

In your module call hook_page_attachments_alter(&$build), inside the function call:

$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

and you can access it directly from your js like below

Where 'bar' is some calculated value.

Then cuddly-slider.js will be able to access

drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

Reference: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

| improve this answer | |
  • 2
    Drupal 8 doesn't have drupal_add_js any more – Clive Apr 9 '18 at 10:53
  • I modified my code for Drupal 8. – Karthi Apr 9 '18 at 11:06

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