0

I've modal popup in my Moodle filter, but some variables should be defined in my php script and I can't set it right in JS. example "MyVariable":

define(['jquery', 'core/modal_factory'], function($, ModalFactory) {
  var trigger = $('#create-modal');
  ModalFactory.create({
    title: 'test title',
    body: '<p>test body content</p><a href="#" id="a-element">Click me</a>',
    footer: 'test footer content',
  }, trigger)
  .done(function(modal) {
    // Do what you want with your new modal.
    var MyVariable;  // I need to set this variable value from my php script
  });
});

Now I can use this way and add some html tags with variable value right in code:

<input type="hidden" value="5" id="get-variable" />
or
<div data-value="5" style="display:none" id="get-variable"></div>

and take the value by

$("#get-variable").val() or $("#get-variable").attr("data-value")

but maybe it is possible to send variable to my modal JS more correctly?

1 Answer 1

1

To send variables to the modal, just pass them in the create method, through the parameter "templateContext":

define(['jquery', 'core/modal_factory'], function($, ModalFactory) {
   var trigger = $('#create-modal');

   var myVariable

   ModalFactory.create({
      title: 'test title',
      body: '<p>test body content</p><a href="#" id="a-element">Click me</a>',
      footer: 'test footer content',
      templateContext : myVariable
   }, trigger)
   .done(function(modal) {
      // Do what you want with your modal
   });
});

If you're using mustache templates, and want to pass the variables after the modal has been mounted, you can use templates.render as a parameter of the setBody method (or setFooter, or setHead):

define(['jquery', 'core/modal_factory'], function($, ModalFactory) {
   var trigger = $('#create-modal');

   var myVariable

   ModalFactory.create({
      title: 'test title',
      body: '<p>test body content</p><a href="#" id="a-element">Click me</a>',
      footer: 'test footer content'
   }, trigger)
   .done(function(modal) {
      modal.setBody(templates.render('your_mustache_file', myVariable))
   });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.