Magento 2.x – How to create a frontend modal popup from scratch
A Modal Window helps with this by making the whole page darker and highlighting the modal window in the center.
You can perform the following steps to create it on the Magento way.
- Create a default.xml file inside the layout folder of your module and add the following code to it:
1234567<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:View/Layout:etc/page_configuration.xsd"><body><referenceContainer name="main"><block class="Offset101\ModalPopup\Block\Example" template="modal_example.phtml" /></referenceContainer></body></page> - Create the template modal_example.phtml file in templates folder and insert the following code to it:
123456<div id="modal-content"><?php echo $block->getContent(); ?></div><button id="example-modal-button" data-mage-init='{"example-modal": {"target": "#modal-content"}}'>Open modal</button> - Next step is to add a JS file to initialize and execute the component, to do so, we will need example-modal.js file in app/code/Offset101/ModalPopup/view/frontend/web/js/ directory:
123456789101112131415161718define(["jquery", "Magento_Ui/js/modal/modal"], function($){var ExampleModal = {initModal: function(config, element) {$target = $(config.target);$target.modal();$element = $(element);$element.click(function() {$target.modal('openModal');});}};return {'example-modal': ExampleModal.initModal};});
The example-modal.js file should be declared in the requirejs-config.js file because this config file is used by RequireJS. - So, create the requirejs-config.js file in app/code/Offset101/ModalPopup/view/frontend/ directory and add the following code to it:
1234567var config = {map: {'*': {'example-modal': 'Offset101_ModalPopup/js/example-modal'}}}; - Last step, is to create our example Block to provide all bussiness logic, so let’s create the Example.php file in app/code/Offset101/ModalPopup/Block/ directory, with the following content:
12345678910<?phpnamespace Offset101\ModalPopup\Block;class Example extends \Magento\Framework\View\Element\Template{public function getContent(){return 'Hello this is the content of the modal!';}}
And that’s it, we are able to test our new modal popup, but before that, remember to run:
12php bin/magento setup:upgradephp bin/magento cache:clean
Happy Coding!
Source: https://www.cloudways.com/blog/magento-2-modal-widget/