Our Work

Add Popup to Product View Page in Magento 2

Updated today

In this article we will see how to add popup to Product view page.

  • Create a module.
  • Add Popup template to product view page.

1.Module

1.1 Create module

Create module which is  extended from Magento_Catalog module.Please refer this article for Module Creation.
https://ktree.com/create-magento-2-module-custom.html

1.2 Folder structure


1.3 List of created files other then default files

  1. app/code/KTree/Custom/view/frontend/layout/catalog_product_view.xml
  2. app/code/KTree/Custom/view/frontend/web/js/mymodal-component.js
  3. app/code/KTree/Custom/view/frontend/requirejs-config.js
  4. app/code/KTree/Custom/view/frontend/templates/catalog/product/view/post_requirements.phtml

2. Add Popup template to product view page

File: app/code/KTree/Custom/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page layout="2columns-right" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
   <referenceContainer name="product.info.form.content">
        <block name="product.info.post.requirements"
          template="KTree_Custom::catalog/product/view/post_requirements.phtml"
           after="product.info.addtocart" />
    </referenceContainer>
</body>
</page>

2.1.Add Popup custom js to Custom Module

File : app/code/KTree/Custom/view/frontend/web/js/mymodal-component.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, $('#myModal'));
            $("#popupButton").on('click',function(){
                $("#myModal").modal("openModal");
            });
        });

Add above js-component to product view page. There are 2 ways to add custom js file to custom module.

  • Using RequireJs-config Js file
  • Using template

Using RequireJs-config Js file

By using requirejs  configurations we can add  custom js  file to custom module

2.1.1 Paths

Paths is used when you want to relate your base url path with custom module path.Path have the same properties as the baseUrl.If the path is started from “/” or any url “http://” then it will not relate to the base url.

var config = {
    "baseUrl": "KTree/Custom",
    "paths": {
        "sample": "web/js"
    },
};
require( ["sample/sample1"],
    function(samplemodule) {
    }
);

Now, samplemodule is reffered to the file at path “KTree/Custom/web/js/sample1.js”.

2.1.2 deps 

If require js configurations depends upon some dependencies, i.e. you want to load some dependencies before your requires js called.

2.1.3 shim

It used when there are some scripts, to whome you want to declare globally, and those scripts not using define() to define values, if those scripts already used the define() then it will not work correctly.
In our example the final requirejs-config.js like below
FIle:app/code/KTree/Custom/view/frontend/requirejs-config.js

var config = {
    paths: {
         'mypopup': "KTree_Custom/js/mymodal-component"
      },
    shim: {
    'mypopup': {
        deps: ['jquery']
    }
  }
};

Here, we are loading mymodal-component js component to our custom module using requirejs configurations 
Initialize or call custom js using mage-init attribute

<button data-mage-init='{"mypopup": {}}' type="button" class="btn btn-primary btn-lg" id="popupButton" data-toggle="modal"
  data-target="#myModal"><?php
echo __('Post Requirement');
?></button>

2.2 Using phtml File

Add following script to app/code/KTree/Custom/view/frontend/templates/catalog/product/view/post_requirements.phtml template file

<script>
  require(['jquery', 'KTree_Custom/js/mymodal-component'],
      function ($) {
          return;
      }
  );
  </script>

Note: In our example we added custom js file using Phtml file,the script like below

File: app/code/KTree/Custom/view/frontend/templates/catalog/product/view/post_requirements.phtml

<button type="button" class="btn btn-primary btn-lg" id="popupButton" data-toggle="modal"
  data-target="#myModal"><?php echo __('Post Requirement')?></button>
  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog" style="display:none;">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title"><?php echo __('Post Requirement')?></h4>
        </div>
        <div class="modal-body">
          <form action="">
      <div class="form-group">
        <label for="name"><?php echo __('Name');?>:</label>
        <input type="email" class="form-control" id="name" placeholder="<?php echo __('Enter name')?>" name="name">
      </div>
      <div class="form-group">
        <label for="requirement"><?php echo __('Requirement') ?> :</label>
      <textarea class="form-control" rows="5" id="requirement"></textarea>
  </div>
      <button type="submit" class="btn btn-default"><?php echo __('Submit')?></button>
    </form>
        </div>
      </div>
    </div>
  </div>
<script>
  require(['jquery', 'KTree_Custom/js/mymodal-component'],
      function ($) {
          return;
      }
  );
  </script>
  • The full source code can be downloaded from this Github link Add popup to product view page
  • After completion above steps, please run the "php bin/magento setup:upgrade" command and "php bin/magento setup:static-content:deploy"
  • The final output like below

Looking for Magento Developer?

Please Contact us if you have any Magento Implementation requirements. Hire dedicated Magento developers or Magento Development services from KTree. KTree is Best offshore Magento E-commerce development company with extensive experience in E-commerce development and Magento Plugins.

Request For Quote