0

I have a custom block in which I read a session value and display the result as the selected value of a select form element. Since the value can change based on the users selection, I'm setting cache max-age to 0.

return [
  '#type'     => 'inline_template',
  '#template' => $markup,
  '#context'  => [],
  '#cache'    => ['max-age' => 0],
];

I also have a jQuery change event defined on the same select form element to submit the selected value via ajax and change the session value.

The problem is that setting the cache max-age to 0 breaks the jQuery event. When I reload the page the jQuery event does not fire. Only after reloading again does the jQuery event start working again. If I don't set the cache max-age to 0 the jQuery event fires everytime but the content of the block does not update to reflect the new session value.

jQuery:

jQuery("select.user-location").on('change', function() {
    event.preventDefault();
    selectedLocationID = jQuery(this).val();
    console.log(selectedLocationID);
    jQuery.ajax({               
        url:"/ajax/setselectedlocationid",
        method:"POST",
        async:true,             
        data:{"selectedLocationID":selectedLocationID},
        dataType: "json",
        showLoader: true,
        success: function(data){
            console.log(data);
        }
    });     
});
  • How is the jquery written? – Kevin Jul 13 '18 at 22:50
  • @Kevin , I've edited the post to include the jQuery code – Todd Wilson Jul 14 '18 at 13:46
  • Yeah - you’ll likely need to create it as a Drupal bevahior and bind it to the block. Otherwise this only happens once. – Kevin Jul 14 '18 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.