Magento 2.1 Modal Widget – How to Create and Call

magento-2.1modal-popup

I want to create custom modal popup widget and call on my .phtml file. How can I do that?

What will be the whole procedure for creating modal and accessing it from the .phtml file?

Best Answer

You should create a module first, then after create a requirejs-config.js file at app/code/Vendor/YourModule/view/frontend/requirejs-config.js

var config = {
    paths: {            
         'myjs': "Vendor_YourModule/js/myfile"
      },   
    shim: {
    'myjs': {
        deps: ['jquery']
    }
  }
} 

You need to create myfile.js in app/code/Vendor/YourModule/view/frontend/web/js/myfile.js

    require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {
            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                buttons: [{
                    text: $.mage.__('Continue'),
                    class: 'mymodal1',
                    click: function () {
                        this.closeModal();
                    }
                }]
            };

            var popup = modal(options, $('#popup-modal'));
            $("#click-me").on('click',function(){
                $("#popup-modal").modal("openModal");
            });
        }
    );

Then your phtml file should look like:

<div data-mage-init='{"myjs": {}}'>
    <a href="#" id="click-me">Click Me</a>
</div>


<div id="popup-modal" >
    yes I am the modal.
</div>