2

My website bookslab.in is almost ready. I am selling the books online. Now i am stuck on this problem. I want to make the zipcode field on my product page as a "required" field before users add the products in the shopping cart by clicking on "add to cart" button. I want to make every users to check their zipcode first then add the products in the cart, because i am delivering the books in limited areas. I am proving the cod.phtml file as a code. Please suggest any solution in my provided code, if you want any code you can comment me.

cod.phtml

<?php
/***************************************
 *** Cash On Delivery ***
 ***************************************[![enter image description here][1]][1]/

$msgData = Mage::helper('netgo_cod')->getConfigData(); 
if($msgData['zip_status'] == 1){
?>
<div class="input-box">
    <div class="z-btn">
        <label>Zip Code : </label><input type="text" placeholder="Enter your pincode" value="" name="cod" class="product-custom-option" id="cod" size="29" style='color:black; font-size:12px' required>
        <button type="button" onclick="checkCOD();" name="zip-check" title="Check" class="button" id="zip-check"><span><span>Check</span></span></button>
    </div>
    <div id="cod_msg"></div>
</div>

<script>
    function checkCOD(){
        var cod = $('cod').value;
        if(cod == ''){
            $('cod_msg').update('<span class="cod-error"><?php echo $msgData['emp_msg']; ?></span>');
            return
        }else{
            $('cod_msg').update('<img src="<?php echo Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true ).'media/cod/img/ajax-loader-2.gif';?>">'); 
            new Ajax.Request('<?php echo Mage::getBaseUrl().'netgo/cod/check';?>', {
                method:'post',
                parameters: {zipcode: cod}, 
                onSuccess: function(transport) {
                    var response = transport.responseText || "no response text";
                    $('cod_msg').update(response);
                },
                onFailure: function() { alert('Something went wrong...'); }
            });
        }
    }
</script>
<?php } ?>

cod.phtml

<?php
/***************************************
 *** Cash On Delivery ***
 ***************************************
 *
 */

$msgData = Mage::helper('netgo_cod')->getConfigData(); 
if($msgData['zip_status'] == 1){
?>
<div class="input-box">
    <div class="z-btn">
        <label>Zip Code : </label><input type="text" placeholder="Enter your pincode" value="" name="cod" class="product-custom-option required-entry" id="cod" size="29" style='color:black; font-size:12px'>
        <button type="button" onclick="checkCOD();" name="zip-check" title="Check" class="button" id="zip-check"><span><span>Check</span></span></button>
    </div>
    <div id="cod_msg"></div>
</div>

<script>
    function checkCOD(){
             var zipcode;
        var cod = $('cod').value;
        if(cod == ''){
            $('cod_msg').update('<span class="cod-error"><?php echo $msgData['emp_msg']; ?></span>');
            return
        }else{
            $('cod_msg').update('<img src="<?php echo Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true ).'media/cod/img/ajax-loader-2.gif';?>">'); 
            new Ajax.Request('<?php echo Mage::getBaseUrl().'netgo/cod/check';?>', {
                method:'post',
                parameters: {zipcode: cod}, 
                onSuccess: function(transport) {
                    var response = transport.responseText || "no response text";
                    $('cod_msg').update(response);

                    if(response.search('Delivery of the book is not available on the above pincode')!=-1)
                                        {
                                          zipcode='checked';
                                        }
                                      else
                                      {
                                      zipcode='';
                                      }

                },
                onFailure: function() { alert('Something went wrong...'); }
            });
        }
    }
</script>
<?php } ?>

view.phtml

<?php
/**
 * Magento
 *
 *
 * @see Mage_Review_Block_Product_View
 */
?>
<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_product = $this->getProduct(); ?>
<script type="text/javascript">
    var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
</script>
<div id="messages_product_view"><?php echo $this->getMessagesBlock()->toHtml() ?></div>
<div class="product-view">
    <div class="product-essential">
        <form action="<?php echo $this->getSubmitUrl($_product, array('_secure' => $this->_isSecure())) ?>" method="post" id="product_addtocart_form"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
            <?php echo $this->getBlockHtml('formkey') ?>
            <div class="no-display">
                <input type="hidden" name="product" value="<?php echo $_product->getId() ?>" />
                <input type="hidden" name="related_product" id="related-products-field" value="" />
            </div>

            <div class="product-img-box">
                <div class="product-name">
                    <h1><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></h1>
                </div>
                <?php echo $this->getChildHtml('media') ?>
            </div>

            <div class="product-shop">
                <div class="product-name">
                    <span class="h1"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></span>
                </div>

                <div class="price-info">
                    <?php echo $this->getPriceHtml($_product); ?>
                    <?php echo $this->getChildHtml('bundle_prices') ?>
                    <?php echo $this->getTierPriceHtml() ?>
                </div>

                <div class="extra-info">
                    <?php echo $this->getReviewsSummaryHtml($_product, 'default', false)?>
                    <?php echo $this->getChildHtml('product_type_availability'); ?>
                </div>

                <?php echo $this->getChildHtml('alert_urls') ?>

                <?php if ($_product->getShortDescription()):?>
                    <div class="short-description">
                        <div class="std"><?php echo $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description') ?></div>
                    </div>
                <?php endif;?>




                <?php echo $this->getChildHtml('other');?>

                <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                    <?php echo $this->getChildChildHtml('container1', '', true, true) ?>
                <?php endif;?>

            </div>

            <div class="add-to-cart-wrapper">
                <?php echo $this->getChildHtml('product_type_data') ?>
                <?php echo $this->getChildHtml('extrahint') ?>

                <?php if (!$this->hasOptions()):?>
                    <div class="add-to-box">
                        <?php if($_product->isSaleable()): ?>
                            <?php echo $this->getChildHtml('addtocart') ?>
                            <?php if( $this->helper('wishlist')->isAllow() || $_compareUrl=$this->helper('catalog/product_compare')->getAddUrl($_product)): ?>
                                <span class="or"><?php echo $this->__('OR') ?></span>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php echo $this->getChildHtml('addto') ?>
                        <?php echo $this->getChildHtml('sharing') ?>
                    </div>
                    <?php echo $this->getChildHtml('extra_buttons') ?>
                <?php elseif (!$_product->isSaleable()): ?>
                    <div class="add-to-box">
                        <?php echo $this->getChildHtml('addto') ?>
                        <?php echo $this->getChildHtml('sharing') ?>
                    </div>
                <?php endif; ?>
            </div>

            <?php echo $this->getChildHtml('related_products') ?>

            <div class="clearer"></div>
            <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                <?php echo $this->getChildChildHtml('container2', '', true, true) ?>
            <?php endif;?>
        </form>
        <script type="text/javascript">
        //<![CDATA[
            var productAddToCartForm = new VarienForm('product_addtocart_form');
            productAddToCartForm.submit = function(button, url) {
                if (this.validator.validate()) {
                    var form = this.form;
                    var oldUrl = form.action;

                    if (url) {
                       form.action = url;
                    }
                    var e = null;
                    try {

                    if(zipcode=='checked')
                    {
                       this.form.submit();
                    }
                    else
                    {
                       alert('check zipcode');
                    }


                    } catch (e) {
                    }
                    this.form.action = oldUrl;
                    if (e) {
                        throw e;
                    }

                    if (button && button != 'undefined') {
                        button.disabled = true;
                    }
                }
            }.bind(productAddToCartForm);

            productAddToCartForm.submitLight = function(button, url){
                if(this.validator) {
                    var nv = Validation.methods;
                    delete Validation.methods['required-entry'];
                    delete Validation.methods['validate-one-required'];
                    delete Validation.methods['validate-one-required-by-name'];
                    // Remove custom datetime validators
                    for (var methodName in Validation.methods) {
                        if (methodName.match(/^validate-datetime-.*/i)) {
                            delete Validation.methods[methodName];
                        }
                    }

                    if (this.validator.validate()) {
                        if (url) {
                            this.form.action = url;
                        }
                        this.form.submit();
                    }
                    Object.extend(Validation.methods, nv);
                }
            }.bind(productAddToCartForm);
        //]]>
        </script>
    </div>

    <div class="product-collateral toggle-content tabs">
        <?php if ($detailedInfoGroup = $this->getChildGroup('detailed_info', 'getChildHtml')):?>
            <dl id="collateral-tabs" class="collateral-tabs">
                <?php foreach ($detailedInfoGroup as $alias => $html):?>
                    <dt class="tab"><span><?php echo $this->escapeHtml($this->getChildData($alias, 'title')) ?></span></dt>
                    <dd class="tab-container">
                        <div class="tab-content"><?php echo $html ?></div>
                    </dd>
                <?php endforeach;?>
            </dl>
        <?php endif; ?>
    </div>

    <?php echo $this->getChildHtml('upsell_products') ?>
    <?php echo $this->getChildHtml('product_additional_data') ?>

</div>
  • I don't understand what you want to achieve. Checking the ZIP and if it the wrong one give an error? What is your exact problem? What have you tried and doesn't work as expected? – Fabian Blechschmidt Oct 23 '16 at 0:01
  • Yeah the problem is: – Salman Dalal Oct 23 '16 at 3:31
  • When zipcode is invalid the message pop up "your zip code is invalid" after that when user clicks on add to cart button the product directly added in the shopping cart which is a bug. The zipcode is invalid and still product is added in the shopping cart. I want if zip code is valid then only product should be added in the shopping cart. – Salman Dalal Oct 23 '16 at 3:36
  • Any answer stacky's to this problem? – Salman Dalal Oct 23 '16 at 6:15
1

For that you have to check condition is zipcode is checked or not.

File : app/design/frontend/(your_package_name)/(your_theme_name)/template/catalog/product/ view.phtml

<script type="text/javascript">
    //<![CDATA[
        var productAddToCartForm = new VarienForm('product_addtocart_form');
        productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {
                var form = this.form;
                var oldUrl = form.action;

                if (url) {
                   form.action = url;
                }
                var e = null;
                try {
         // **************add this part**************
                    if(zipcode=='checked')
                    {
                       this.form.submit();
                    }else
                    {
                       alert('check zipcode');
                    }
         //**************till here*********************
                } catch (e) {
                }
                this.form.action = oldUrl;
                if (e) {
                    throw e;
                }

                if (button && button != 'undefined') {
                    button.disabled = true;
                }
            }
        }.bind(productAddToCartForm);

        productAddToCartForm.submitLight = function(button, url){
            if(this.validator) {
                var nv = Validation.methods;
                delete Validation.methods['required-entry'];
                delete Validation.methods['validate-one-required'];
                delete Validation.methods['validate-one-required-by-name'];
                if (this.validator.validate()) {
                    if (url) {
                        this.form.action = url;
                    }
                    this.form.submit();
                }
                Object.extend(Validation.methods, nv);
            }
        }.bind(productAddToCartForm);
    //]]>
    </script>

Add variable zipcode and set it as checked on success in your file cod.phtml

<?php
/***************************************
 *** Cash On Delivery ***
 ***************************************[![enter image description here][1]][1]/

$msgData = Mage::helper('netgo_cod')->getConfigData(); 
if($msgData['zip_status'] == 1){
?>
<div class="input-box">
    <div class="z-btn">
        <label>Zip Code : </label><input type="text" placeholder="Enter your pincode" value="" name="cod" class="product-custom-option" id="cod" size="29" style='color:black; font-size:12px' required>
        <button type="button" onclick="checkCOD();" name="zip-check" title="Check" class="button" id="zip-check"><span><span>Check</span></span></button>
    </div>
    <div id="cod_msg"></div>
</div>

<script>
    function checkCOD(){

      // **************add this part**************
        var zipcode;
     // ***************************************

        var cod = $('cod').value;
        if(cod == ''){
            $('cod_msg').update('<span class="cod-error"><?php echo $msgData['emp_msg']; ?></span>');
            return
        }else{
            $('cod_msg').update('<img src="<?php echo Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true ).'media/cod/img/ajax-loader-2.gif';?>">'); 
            new Ajax.Request('<?php echo Mage::getBaseUrl().'netgo/cod/check';?>', {
                method:'post',
                parameters: {zipcode: cod}, 
                onSuccess: function(transport) {
                    var response = transport.responseText || "no response text";
                    $('cod_msg').update(response);

         // **************add this part**************
                    if(response.search('Delivery of the book is not available on the above pincode')!=-1)
                    {
                       zipcode='checked';
                    }
                    else
                    {
                       zipcode='';
                    }

         //*****************************************

                },
                onFailure: function() { alert('Something went wrong...'); }
            });
        }
    }
</script>
<?php } ?>

Note :

It will allow add to cart only on success of zipcode. If you want to allow add to cart on any other condition then you have to add condition accordingly.

  • Thanks for your logic, but its not worked nothing happening. Is there any way that to change "add to cart" button to "view details" button when i search all books on my website. – Salman Dalal Oct 20 '16 at 15:35
  • @user1764289 yes replace add to cart button with view detail button and provide anchor to product detailed page. – Gopal Patel Oct 21 '16 at 5:16
  • Okzz i had done that, so now i had found one more bug, when users place invalid zipcode in the textfield & after that they click on add to cart button, so are successful to add the products in the shopping cart, which is not good, I need an exception for this bug. – Salman Dalal Oct 21 '16 at 12:54
  • @user1764289 Code updated. EDIT: if(response=='REPLACE WITH YOUR SUCCESS MESSAGE'){ zipcode='checked'; } – Gopal Patel Oct 21 '16 at 14:55
  • @user1764289 if this helful to you then mark it as answer and close the question. – Gopal Patel Oct 21 '16 at 14:57
2

add this in your class required-entry

<input type="text" class="product-custom-option required-entry" placeholder="Enter your pincode" value="" name="cod"  id="cod" size="29" style='color:black; font-size:12px'>
  • Thanks "user3046689" you rock! it works for me. But when message "This is a required field." comes the button "check" of zip code field comes down it looks very weird. So is there any code to change the position of message "This is a required field." – Salman Dalal Oct 20 '16 at 13:42
  • no you have to manage this from css according to your layout. If answer worked out for you pls accept it. – Priyank Oct 20 '16 at 13:44
  • Whenever i search all books on my website there is a add to cart button below each book, so when i click on add to cart button the product directly goes in shopping cart, so how to stop this, because user does not checked its zipcode & product is directly added in cart. – Salman Dalal Oct 20 '16 at 14:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.