Magento2 Open Popup With Content From Block

By vijayramiUpdated 15 February 2021
Magento2Magento2 LayoutMagento2 ExtensionsMagento2 popup
Magento2 Open Popup With Content From Block

 Magento2 have a in-build UI component to display pop-up from your phtml file.



static content

1. Static Content in Pop-up

In your .phtml file write below code:

<div id="your_popup_container" style="display:none">
    <div class="message-error error message">
    <p>Your content</p>
    </div>
</div>
    require(
    [
        'jquery',
        'Magento_Ui/js/modal/modal'
    ],
    function(
        $,
        modal
    ) {
        var options = {
            'type': 'popup',
            'title': 'your popup title',
            'modalClass': 'your_popup_custom_class',
            'responsive': true,
            'innerScroll': true
            'buttons': [{
                text: $.mage.__('Close'),
                class: 'back_button_class',
                click: function () {
                    this.closeModal();
                    // any javascript coode
                }
            }]
        };

        $(document).ready(function(){
            var popup = modal(options, $('#your_popup_container'));
            $('.your-click-handler').on('click', function(event){
                    $("#your_popup_container").modal("openModal");
            })
        });
    }
);

With this you can display static content in popup.
Now read below content, if you want to display dynamic content in popup modal.

2. Dynamic Content in Pop-up

Let's start by creating custom extension.

Find the complete module on Github

Create your extension folder inside app/code/Magelearn/PopupBlock

Add registration.php file in it:
<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\Component\ComponentRegistrar;
 
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_PopupBlock', __DIR__);
Add composer.json file in it:
{
    "name": "magelearn/popupblock",
    "description": "Magento 2 Display Popup with content defined from your custom block.",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\PopupBlock\\": ""
        }
    }
}
Add etc/module.xml file in it:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_PopupBlock" setup_version="1.0.0">
    </module>
</config>
Create your layout default.xml file inside view/frontend/layout/
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magelearn\PopupBlock\Block\ModalOverlay"
                   template="Magelearn_PopupBlock::modal_overlay.phtml"
                   name="modalOverlay"
                   as="modalOverlay"/>
        </referenceContainer>
    </body>
</page>

Create your template modal_overlay.phtml file inside view/frontend/templates/

You need to create your custom block from admin and need to pass block_id in line no. 1

<?php if ($content = $block->getContent('modal_overlay_block')) { ?>

<div id="modal-overlay" style="display:none;">
	<?php echo $content; ?>
</div>
<script type="text/x-magento-init">
	{
		"*": {
			"Magento_Ui/js/core/app": {
				"components": {
					"modal_overlay": {
						"component": "Magelearn_PopupBlock/js/modal_overlay"
					}
				}
			}
		}
	}
</script>
<?php } ?>
Create JS file modal_overlay.js inside view/frontend/web/js/
define([
    'uiComponent',
    'jquery',
    'Magento_Ui/js/modal/modal',
    'Magento_Customer/js/customer-data'
], function (Component, $, modal, storage) {
    'use strict';

    var cacheKey = 'modal-overlay';

    var getData = function () {
        return storage.get(cacheKey)();
    };

    var saveData = function (data) {
        storage.set(cacheKey, data);
    };

    if ($.isEmptyObject(getData())) { //Check to see if an object is empty
        var modal_overlay = {
            'modal_overlay': false
        };
        saveData(modal_overlay);
    }

    return Component.extend({

        initialize: function () {

            this._super();
            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: false,
                title: false,
                buttons: false
            };

            var modal_overlay_element = $('#modal-overlay');
            var popup = modal(options, modal_overlay_element);

            modal_overlay_element.css("display", "block");

            this.openModalOverlayModal();

        },

        openModalOverlayModal:function(){
            var modalContainer = $("#modal-overlay");

            if(this.getModalOverlay()) {
               return false;
            }
            this.setModalOverlay(true);
            modalContainer.modal('openModal');
        },

        setModalOverlay: function (data) {
            var obj = getData();
            obj.modal_overlay = data;
            saveData(obj);
        },

        getModalOverlay: function () {
            return getData().modal_overlay;
        }

    });
});
Create your block file ModalOverlay.php file inside Block/
<?php
namespace Magelearn\PopupBlock\Block;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class ModalOverlay extends Template
{

    private $blockRepository;

    public function __construct(
        BlockRepositoryInterface $blockRepository,
        Context $context,
        array $data = []
    ) {
        $this->blockRepository = $blockRepository;

        parent::__construct($context, $data);
    }

    public function getContent($identifier)
    {
        try {
            /** @var BlockInterface $block */
            $block = $this->blockRepository->getById($identifier);
            $content = $block->getContent();
        } catch (LocalizedException $e) {
            $content = false;
        }

        return $content;
    }
}

After adding this code. Run magento command and then check your home page.



Popup will be display as per content defined in your custom block.

Magento2 Open Popup With Content From Block | Vijay M. Rami