Year End Sale -2o% Off On All Products - Coupon: FMADEC2017

Top 5 Programming Questions and Answers Regarding Magento Popup Integration Part - 1

Popups are very useful for any website, especially for an eCommerce website. As it helps to convey an important message or any website related information to the users when they visit the website. Ecommerce website owners can tell about newly arrived products with their links in a popup window. In Magento programming for popup never easy, that is why developers face the various issues and they ask for help on different platforms. In this article, you will read 5 questions with answers regarding Magento pop-up extension integration and these answers are given by the community, not represent us. Let’s have a look at 5 questions and answers.

Question No. 1

A user designing Magento theme and getting the popup message that says “Checkout out as a new customer Creating an account…”. He wants to disable this popup with the help of HTML code.

Answer:

First of all, please create this file.

<vendor_name>/<theme_name>/Magento_Customer/layout.xml
<block class="Magento\Customer\Block\Account\AuthenticationPopup" name="authentication-popup" as="authentication-popup" template="account/authentication-popup.phtml">
                <arguments>
                    <argument name="jsLayout" xsi:type="array">
                        <item name="components" xsi:type="array">
                            <item name="authenticationPopup" xsi:type="array">
                                <item name="component" xsi:type="string">Magento_Customer/js/view/authentication-popup</item>
                                <item name="children" xsi:type="array">
                                    <item name="messages" xsi:type="array">
                                        <item name="component" xsi:type="string">Magento_Ui/js/view/messages</item>
                                        <item name="displayArea" xsi:type="string">messages</item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </argument>
                </arguments>
            </block>

With this code

<referenceBlock name="authentication-popup" remove="true"/>

Question No. 2

A user has added the date picker fields in Magento website, he has successfully added the required CSS and jQuery files. But don’t know here to add HTML file to Magento page. As he wants to redirect users to Google.com if their age is below 18.

Answer:

Please use the following code for validation.

<script>
function check_dob()
{
    var month = document.getElementById('month').value;
    var day = document.getElementById('day').value;
    var year = document.getElementById('year').value;
    var dbDate = year+'-'+month+'-'+day;
    var today = new Date();
    var birthDate = new Date(dbDate);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
    }

    if(age<=20)
    {
        alert("You are under "+age+" Year")
    }
}
</script>

Question No. 3

A user has created ajax based login/registration popup. But users are unable to register on his Magento website, however, login works fine. It gives users a message “Please make sure your passwords match” when to register on his website.  He used this config.xml code.

<?xml version="1.0"?>
<config>
<modules>
    <FastDivision_QuickLogin>
        <version>1.0.0</version>
    </FastDivision_QuickLogin>
</modules>
<frontend>
    <routers>
        <customer>
            <args>
                <modules>
                    <FastDivision_QuickLogin before="Mage_Customer">FastDivision_QuickLogin_Customer</FastDivision_QuickLogin>
                    <!--<FastDivision_QuickLogin before="Mage_Customer_Account">FastDivision_QuickLogin_Customer</FastDivision_QuickLogin>
                    <FastDivision_QuickLogin before="Mage_Customer_AccountController">FastDivision_QuickLogin_Customer</FastDivision_QuickLogin>-->
                </modules>
            </args>
        </customer>
    </routers>
</frontend>
</config>

And used this AccountController.php script

<?php
// Require the core controller file that you're planning to override
require_once('Mage/Customer/controllers/AccountController.php');

// The class name follows this format:
// YOURPACKAGE_YOUREXTENSION_COREMODULEFOLDER_CONTROLLERFILENAME
// We extend the original Mage_Customer_AccountController class to inherit unused actions and override specific actions
class FastDivision_QuickLogin_Customer_AccountController extends Mage_Customer_AccountController
{
// Code referenced from AccountController.php
public function loginPostAction()
{
    if(!$this->getRequest()->isXmlHttpRequest()) {
        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
    }

    $session = $this->_getSession();

    if($this->getRequest()->isXmlHttpRequest()) {
        // Report exceptions via JSON
        $ajaxExceptions = array();
    }

    if ($this->getRequest()->isPost()) {
        $login = $this->getRequest()->getPost('login');
        if (!empty($login['username']) && !empty($login['password'])) {
            try {
                $session->login($login['username'], $login['password']);
                if ($session->getCustomer()->getIsJustConfirmed()) {
                    $this->_welcomeCustomer($session->getCustomer(), true);
                }
            } catch (Mage_Core_Exception $e) {
                if($this->getRequest()->isXmlHttpRequest()) {
                    $messages = array_unique(explode("\n", $e->getMessage()));
                    foreach ($messages as $message) {
                        $ajaxExceptions['exceptions'][] = $message;
                    }
                } else {
                    switch ($e->getCode()) {
                        case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
                            $value = Mage::helper('customer')->getEmailConfirmationUrl($login['username']);
                            $message = Mage::helper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
                            break;
                        case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
                            $message = $e->getMessage();
                            break;
                        default:
                            $message = $e->getMessage();
                    }
                    $session->addError($message);
                }

                $session->setUsername($login['username']);
            } catch (Exception $e) {
                // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
            }
        } else {
            if($this->getRequest()->isXmlHttpRequest()) {
                $ajaxExceptions['exceptions'][] = 'Login and password are required.';
            } else {
                $session->addError($this->__('Login and password are required.'));
            }
        }
    }

    if($this->getRequest()->isXmlHttpRequest()) {
        // If errors
        if(count($ajaxExceptions)) {
            echo json_encode($ajaxExceptions);
        } else {
            // No Errors
            echo json_encode(array('success' => 'success'));
        }
    } else {
        // Redirect for non-ajax
        $this->_loginPostRedirect();
    }
}

// Create Account
public function createPostAction()
{
    if($this->getRequest()->isXmlHttpRequest()) {
        // Report exceptions via JSON
        $ajaxExceptions = array();
    }

    $session = $this->_getSession();
    if ($session->isLoggedIn()) {
        $this->_redirect('*/*/');
        return;
    }
    $session->setEscapeMessages(true); // prevent XSS injection in user input
    if ($this->getRequest()->isPost()) {
        $errors = array();

        if (!$customer = Mage::registry('current_customer')) {
            $customer = Mage::getModel('customer/customer')->setId(null);
        }

        /* @var $customerForm Mage_Customer_Model_Form */
        $customerForm = Mage::getModel('customer/form');
        $customerForm->setFormCode('customer_account_create')
            ->setEntity($customer);

        $customerData = $customerForm->extractData($this->getRequest());

        if ($this->getRequest()->getParam('is_subscribed', false)) {
            $customer->setIsSubscribed(1);
        }

        /**
         * Initialize customer group id
         */
        $customer->getGroupId();

        if ($this->getRequest()->getPost('create_address')) {
            /* @var $address Mage_Customer_Model_Address */
            $address = Mage::getModel('customer/address');
            /* @var $addressForm Mage_Customer_Model_Form */
            $addressForm = Mage::getModel('customer/form');
            $addressForm->setFormCode('customer_register_address')
                ->setEntity($address);

            $addressData    = $addressForm->extractData($this->getRequest(), 'address', false);
            $addressErrors  = $addressForm->validateData($addressData);
            if ($addressErrors === true) {
                $address->setId(null)
                    ->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
                    ->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
                $addressForm->compactData($addressData);
                $customer->addAddress($address);

                $addressErrors = $address->validate();
                if (is_array($addressErrors)) {
                    $errors = array_merge($errors, $addressErrors);
                }
            } else {
                $errors = array_merge($errors, $addressErrors);
            }
        }

        try {
            $customerErrors = $customerForm->validateData($customerData);
            if ($customerErrors !== true) {
                $errors = array_merge($customerErrors, $errors);
            } else {
                $customerForm->compactData($customerData);
                $customer->setPassword($this->getRequest()->getPost('password'));
                $customer->setConfirmation($this->getRequest()->getPost('confirmation'));
                $customerErrors = $customer->validate();
                if (is_array($customerErrors)) {
                    $errors = array_merge($customerErrors, $errors);
                }
            }

            $validationResult = count($errors) == 0;

            if (true === $validationResult) {
                $customer->save();

                Mage::dispatchEvent('customer_register_success',
                    array('account_controller' => $this, 'customer' => $customer)
                );

                if ($customer->isConfirmationRequired()) {
                    $customer->sendNewAccountEmail(
                        'confirmation',
                        $session->getBeforeAuthUrl(),
                        Mage::app()->getStore()->getId()
                    );
                    $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please <a href="%s">click here</a>.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));

                    if($this->getRequest()->isXmlHttpRequest()) {
                        echo json_encode(array('success' => $this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please <a href="%s">click here</a>.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail()))));
                    } else {
                        $this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
                    }

                    return;
                } else {
                    $session->setCustomerAsLoggedIn($customer);
                    $url = $this->_welcomeCustomer($customer);

                    if($this->getRequest()->isXmlHttpRequest()) {
                        echo json_encode(array('success' => 'success'));
                    } else {
                        $this->_redirectSuccess($url);
                    }

                    return;
                }
            } else {
                $session->setCustomerFormData($this->getRequest()->getPost());

                if(!$this->getRequest()->isXmlHttpRequest()) {
                    if (is_array($errors)) {
                        foreach ($errors as $errorMessage) {
                            $session->addError($errorMessage);
                        }
                    } else {
                        $session->addError($this->__('Invalid customer data'));
                    }
                } else {
                    if (is_array($errors)) {
                        foreach ($errors as $errorMessage) {
                            $ajaxExceptions['exceptions'][] = $errorMessage;
                        }
                    } else {
                        $ajaxExceptions['exceptions'][] = 'Invalid customer data';
                    }
                }
            }
        } catch (Mage_Core_Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost());
            if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
                $url = Mage::getUrl('customer/account/forgotpassword');
                $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url);
                $session->setEscapeMessages(false);
            } else {
                $message = $e->getMessage();
            }

            if(!$this->getRequest()->isXmlHttpRequest()) {
                $session->addError($message);
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $ajaxExceptions['exceptions'][] = $message;
                }
            }
        } catch (Exception $e) {
            if(!$this->getRequest()->isXmlHttpRequest()) {
                $session->setCustomerFormData($this->getRequest()->getPost())
                ->addException($e, $this->__('Cannot save the customer.'));
            } else {
                $ajaxExceptions['exceptions'][] = 'Cannot save the customer.';
            }
        }
    }

    if($this->getRequest()->isXmlHttpRequest()) {
        echo json_encode($ajaxExceptions);
    } else {
        $this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
    }
}
}

And this quick_login.phtml code

   <div id="login-modal" class="modal-window">
  <div id="login-modal-content">
    <div id="signup-box">
  <h1>Register</h1>
  <p><a href="#" id="already-registered-link">Already registered? Click here to sign in.</a></p>

  <form action="<?php echo Mage::getBaseUrl() ?>customer/account/createpost/" method="post" id="signup-form" class="site-form" onsubmit="return false">
    <ul class="form-list">
      <li class="fields">
          <div class="field first-field">
              <label for="firstname" class="required"><?php echo $this->__('First Name') ?><em>*</em></label>
              <div class="input-box">
                  <input type="text" name="firstname" id="firstname" class="input-text validate-email required-entry" />
              </div>
          </div>
          <div class="field">
              <label for="last_name" class="required"><?php echo $this->__('Last Name') ?><em>*</em></label>
              <div class="input-box">
                  <input type="text" name="lastname" id="lastname" class="input-text validate-email required-entry" />
              </div>
          </div>
          <div class="field">
              <label for="email_address" class="required"><?php echo $this->__('Email') ?><em>*</em></label>
              <div class="input-box">
                  <input type="text" name="email" id="email_address" class="input-text validate-email required-entry" />
              </div>
          </div>
          <div class="field">
              <label for="password" class="required"><?php echo $this->__('Password') ?><em>*</em></label>
              <div class="input-box">
                  <input type="password" name="password" id="password" title="<?php echo $this->__('Password') ?>" class="input-text required-entry validate-password" />
              </div>
          </div>
          <div class="field">
              <label for="confirmation" class="required"><?php echo $this->__('Confirm Password') ?><em>*</em></label>
              <div class="input-box">
                  <input type="password" name="confirmation" title="<?php echo $this->__('Confirm Password') ?>" id="confirmation" class="input-text required-entry validate-cpassword" />
              </div>
          </div>
      </li>
    </ul>

    <button type="submit" title="Submit" class="action-button"><span>Create Account</span></button>
  </form>
</div>
<div id="login-box">
  <h1>Login</h1>
  <p><?php echo $this->__('If you have an account with us, please log in.') ?></p>
  <p><a href="#" id="need-account-link">Need an account? Click here to register.</a></p>

  <form action="<?php echo Mage::getBaseUrl() ?>customer/account/loginPost/" method="post" id="login-form" class="site-form" onsubmit="return false">
    <ul class="form-list">
         <li class="field">
             <label for="email" class="required"><?php echo $this->__('Email') ?><em>*</em></label>
             <div class="input-box">
                 <input type="text" name="login[username]" value="<?php echo $this->htmlEscape($this->getUsername()) ?>" id="email" class="input-text" title="<?php echo $this->__('Email Address') ?>" />
             </div>
         </li>
         <li class="field">
             <label for="pass" class="required"><?php echo $this->__('Password') ?><em>*</em></label>
             <div class="input-box">
                 <input type="password" name="login[password]" class="input-text" id="pass" title="<?php echo $this->__('Password') ?>" />
             </div>
         </li>
     </ul>

      <button type="submit" class="action-button action-button-no-arrow" title="<?php echo $this->__('Login') ?>" name="send" id="send2"><span><?php echo $this->__('Login') ?></span></button>&nbsp;&nbsp;
      <a href="<?php echo $this->getForgotPasswordUrl() ?>" class="small"><?php echo $this->__('Forgot Your Password?') ?></a>
       </form>
    </div>
  </div>
  <a id="close_x" class="close" href="#"><i class="fa fa-close"></i></a>
  <script type="text/javascript">
  //<![CDATA[
  var dataForm = new VarienForm('login-form', true);
  //]]>
  </script>
</div>

Answer:

This message comes whenever user register or checkout in the storefront in Magento 1.9. To validate confirmed password in class “Mage_Customer_Model_Customer”  method validate () is changed.

Before

$confirmation = $this->getConfirmation();

And after

$confirmation = $this->getPasswordConfirmation();

You have to change the line to this to get resolved your issue.

$confirmation = $this->getConfirmation();

Question No. 4

A user wants to add the button to Magento edit cms/block page which displays a popup window containing values of input fields from when he clicks that button.

Answer:

For block, you can use Mage_Adminhtml_Block_Cms_Block_Edit and for the page, you can use Mage_Adminhtml_Block_Cms_Page_Edit. And you can set on click JS function to be called with this button and add this function in $this->_formScripts[].

Example of Mage_Adminhtml_Block_Cms_Page_Edit

public function __construct()
{
    ...
    $this->_addButton('quickview', array(
                'label'     => Mage::helper('adminhtml')->__('Quick Form View'),
                'onclick'   => 'quickview()',
                'class'     => 'info',
            ), -200);
    $this->_formScripts[] = "
            function quickview(){
                f1=document.forms['edit_form'];
                //to show specific element value
                var txt = document.getElementById('page_title').value;
                //to get All elements
                var txt = '';
                for (var i=0; i<f1.length; i++){
                    txt = txt + f1.elements[i].id + ' : ' + f1.elements[i].value + '\\n';
                }
                var popupDiv = document.createElement('div');
                var popupHtml = '<div id =\"popup\" style=\"position: absolute; width: 94%; padding: 10px; z-index: 10; left: 28px; background: none repeat scroll 0% 0% rgb(248, 248, 248); display: block; border: 1px solid rgb(204, 204, 204);\"></div>';
                popupHtml+='<div style=\"background: none repeat scroll 0px 0px rgb(0, 0, 0); left: 0px; min-height: 250%; min-width: 100%; opacity: 0.45; position: absolute; top: 0px; z-index: 9; display: block;\" ></div>';
                popupDiv.innerHTML = popupHtml;
                f1.appendChild(popupDiv);
                document.getElementById('popup').innerHTML = txt;
            }
        ";


}

Question No. 5

A user wants to add a static block for popup window in Magento and applied below code but didn’t work.

<?php
require_once('app/Mage.php');
umask(0);

$layout = Mage::app()
    ->getLayout();

$layout
    ->getUpdate()
    ->addHandle('default')
    ->load();

$layout
    ->generateXml()
    ->generateBlocks();

echo '<p>before</p>';

echo $layout
    ->createBlock('cms/block')
    ->setBlockId('delivery-info')
    ->toHtml();

echo '<p>after</p>';
?>

This code shows blank output and doesn’t show static block popup. He wants to display the popup that uses Magento theme.

Answer

You are using incorrect block id. Then that CMS is able to be shown. And if you want to display CSSS theme that is included in <default> tag then use this script.

Mage::getDesign()->setTheme('your theme');

echo $layout->getBlock('head')->toHtml();

When XML has generated than put the code after.

$layout
    ->generateXml()
    ->generateBlocks();

Download Magento Pop-Up Extension Developed by FMA

magento pop-up extension

Leave a Reply