1

The passing of the array works only one time. After an ajax call the new array is not passed to drupalSetting only the 1st array will displayed multiple times in the console. I tried it with a static test array, with a dynamic array, with json_encode() and such other things.

My PHP script:

$form['#attached']['drupalSettings']['variable'] = $vars;

devel:

Array (
    [0] => Array (
            [0] => val1
            [1] => val2
            [2] => val3
        )
    [1] => Array (
            [0] => val1
            [1] => val2
            [2] => val3
        )
....
)

My jQuery script:

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

            var loadVar = function(event, request, settings) {              
                var varArr = drupalSettings.variable;
                console.log(varArr);
            };

            $( document ).ready(loadVar);
            $( document ).ajaxComplete(loadVar);
        }
    };
})(jQuery, Drupal, drupalSettings);

console:

Object { 0: {…}, 1: […] }

I think the main issue is that the drupalSettings.variable don't get the new array from the form after the ajax call.The attached values in the form are changed correctly.

1

I searched on the wrong position, after i found: http://www.thecarneyeffect.co.uk/drupal-8-ajax I got the solution here https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21SettingsCommand.php/class/SettingsCommand/8.2.x

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\SettingsCommand;

function ajaxCallback(array &$form, FormStateInterface $form_state) {

    $form_state->setRebuild();

    $myValue = $form_state->getValue('myValue');

    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new SettingsCommand([
       'variable' => $myValue,
    ], TRUE));

  return $ajax_response;
}   
  • Yes, this is the code when the settings are the only data you want to return. Otherwise you didn't search in the wrong place, you can attach settings to $form. But it has to be in that part of the render array you return in the ajax response. – 4k4 Jan 7 '18 at 9:33
  • That's it! Both scripts are needed to output and manipulate the drupalSettings.variable. And for sure you can extend the callback for some other parts. I searched very long and after I posted here I found the solution with many luck! Hope this will helped someone else! – Bruno Jan 8 '18 at 0:15

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.