Saturday, 4 November 2017

How to Rewrite / Override block in magento

How to Rewrite / Override block in magento

Here we are Overriding / Rewriting magento block of Mage_Catalog_Block_Product_View with custom module named Chand_Software.

(1) Create module file in app/etc/modules/Chand_Software.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Chand_Software>
            <active>true</active>
            <codePool>local</codePool>
        </Chand_Software>
    </modules>
</config>

(2) Create module config file in app/code/local/Chand/Software/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Chand_Software>
            <version>1.0.0</version>
        </Chand_Software>
    </modules>
    <global>
        <blocks>
            <catalog>  // This is the block identifier which we want rewrite
                <rewrite>
                    <product_view>Chand_Software_Block_Product_View</product_view>
                </rewrite>
            </catalog>
        </blocks>
    </global>
</config>

(3) Now Create block file of our custom module in app/code/local/Chand/Software/Block/Product/View.php

class Chand_Software_Block_Product_View extends Mage_Catalog_Block_Product_View
{
    /**
     * Put your logic here
     *
     */
}

How to add css in only product type simple in magento

How to add css in only product type simple in magento

First to create local.xml file at this path app/design/frontend/yourpackage/default/layout/local.xml and paste below code in local.xml

<?xml version="1.0"?>

<layout version="0.1.0">

    <PRODUCT_TYPE_simple>
   
            <reference name="head">
   
                <action method="addCss"><stylesheet>css/your_simple.css</stylesheet></action>
   
            </reference>
   
    </PRODUCT_TYPE_simple>

</layout>

Handle of different product types :

<PRODUCT_TYPE_simple>
<PRODUCT_TYPE_configurable>
<PRODUCT_TYPE_grouped>
<PRODUCT_TYPE_virtual>
<PRODUCT_TYPE_downloadable>
<PRODUCT_TYPE_bundle>

How to make timer that not reset when page refresh javascript

<form name="counter">
    <input type="text" size="8" name="jimmy" id="counter">
</form>

<script type="text/javascript">
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

var cnt = 60;
function counter(){
    if(getCookie("cnt") > 0){
  cnt = getCookie("cnt");
 }
 cnt -= 1;
 document.cookie = "cnt="+ cnt;
 jQuery("#counter").val(getCookie("cnt"));

 if(cnt>0){
  setTimeout(counter,1000);
 }

}

counter();
</script>

How to add css and js file in head section opencart


Include Css file code:

$this->document->addStyle('catalog/view/theme/themename/stylesheet/product.css');


Include Js file code:

$this->document->addScript('catalog/view/theme/themename/js/product.js');

How to append GET parameters in url PHP

First make one function like below

$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$param = GET;

function filter_url($url,$param){

    $parsed = parse_url($url);
    $query = str_replace("&amp;","&",$parsed['query']);
    parse_str($query,$params);
    unset($params[$param]);
    $new_query = http_build_query($params);
    $newUrl = $parsed['scheme']."://".$parsed['host'].$parsed['path'];
    if($new_query){
        $newUrl .= "?".$new_query;
    }
    return $newUrl;

}

How do i reverse parse_url in PHP


$parsed = parse_url($url);

You can reverse back parse url like below

$newUrl = $parsed['scheme']."://".$parsed['host'].$parsed['path'];
$new_query = http_build_query($params);
if($new_query){
    $newUrl .= "?".$new_query;
}

Friday, 10 February 2017

How to add css and js file in head section opencart


How to add css and js file in head section opencart

Include Css file code:

$this->document->addStyle('catalog/view/theme/themename/stylesheet/product.css');


Include Js file code:

$this->document->addScript('catalog/view/theme/themename/js/product.js');

Saturday, 28 January 2017

How to make counter not reset on page refresh javascript


How to make counter not reset on page refresh javascript

<form name="counter">
    <input type="text" size="8" name="chandresh" id="counter">
</form>

<script type="text/javascript">
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

var cnt = 60;
function counter(){
    if(getCookie("cnt") > 0){
cnt = getCookie("cnt");
}
cnt -= 1;
document.cookie = "cnt="+ cnt;
jQuery("#counter").val(getCookie("cnt"));

if(cnt>0){
setTimeout(counter,1000);
}

}

counter();
</script>

Monday, 12 December 2016

How to add sku column in sales order grid magento admin


How to add sku column in sales order grid magento admin

Note: For not to override magento core functionality, You can create your own module and use the below code in Grid.php

Open app\code\core\Mage\Adminhtml\Block\Sales\Order\Grid.php

Replace the below function

protected function _prepareCollection()
{
    $collection = Mage::getResourceModel($this->_getCollectionClass());
    $collection->getSelect()->joinLeft(
            'sales_flat_order_item',
            '`sales_flat_order_item`.order_id=`main_table`.entity_id',
            array('skus'  => new Zend_Db_Expr('group_concat(`sales_flat_order_item`.sku SEPARATOR ",")'))
    );
    $collection->getSelect()->group('entity_id');
   
    $this->setCollection($collection);
    return parent::_prepareCollection();
}

Now put the below code in _prepareColumns() function

$this->addColumn('sku', array(
    'header' => Mage::helper('sales')->__('SKU'),
    'index' => 'skus',
    'type' => 'text',
    'width' => '100px',
    'filter'    => false,
));

Friday, 9 December 2016

Swap variable values in php


Swap variable values in php

<?php
$a = 40;
$b = 50;

$temp = $a;
$a = $b;
$b = $temp;

echo $a;
echo $b;

OR

Swap values without third variable

$a = 40;
$b = 50;

$a = $a+$b;
$b = $a - $b;
$a = $a - $b;

echo $a;
echo $b;

?>

Star pattern programs with for loop in php


Star pattern programs with for loop in php

Script for following pattern

*
**
***
****
*****
******
*******
********

<?php
for($i=1;$i<=8;$i++){
echo str_repeat('*',$i);
echo "<br/>";
}

OR

for($i=1;$i<=8;$i++){

   for($j=1;$j<$i;$j++){
echo '*';
   }
   echo '<br/>';
}

?>


Script for following pattern

****
****
****
****
****
****

<?php
for ($i=1;$i<=6;$i++){
for($j=1;$j<5;$j++){
echo '*';
}
echo '<br/>';
}
?>


Script for following pattern

*****
****
***
**
*

<?php
for($i=6;$i>0;$i--){
for($j=1;$j<$i;$j++){
echo '*';
}
echo '<br/>';
}
?>

Script for Triangle of Stars in PHP

        *
       **
      ***
     ****
    *****
   ******

<?php
$l = 1;
for($i=8;$i>1;$i--){

for($j=1;$j<$i;$j++){
echo '&nbsp;';
}


for($k=1;$k<$l;$k++){
echo '*';
}
$l++;
echo '<br/>';

}

OR

$l = 1;
for($i=8;$i>1;$i--){

echo str_repeat('&nbsp;',$i);
echo str_repeat('*',$l++);
echo '<br/>';
}

?>

Wednesday, 30 November 2016

How to enable paypal payment standard in magento 1.9.2.1


How to enable paypal payment standard in magento 1.9.2.1

In magento 1.9.2.1 Paypal Payment Standard method not exist. If you want use paypal, you have to select Website Payments Standard (Includes Express Checkout). Here i have used small trick to reuse the old method.

Run the following query in your database and check in admin panel in payment method section

update core_config_data set value = '1' where path = 'payment/paypal_standard/active';

Monday, 14 November 2016

Radio button validation in javascript check or uncheck


Radio button validation in javascript check or uncheck

<form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">

    <div class="text-input">
        <label>Gender: </label>
        <input class="form-control" type="radio" name="gender" id="male" value="male" />
        <label for="male">Male</label>
        <input class="form-control" type="radio" name="gender" id="female" value="female" />
        <label for="female">Female</label>
    </div>
    <div class="text-input" align="center">
        <input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
    </div>

</form>

<script type="text/javascript">
function radioValidation(){

var gender = document.getElementsByName('gender');
var genValue = false;

for(var i=0; i<gender.length;i++){
if(gender[i].checked == true){
genValue = true;
}
}
if(!genValue){
alert("Please Choose the gender");
return false;
}

}
</script>

Wednesday, 9 November 2016

PayPal gateway has rejected request. Currency is not supported paypal Express error magento



PayPal gateway has rejected request. Currency is not supported paypal Express error magento

Generally People face this type error becoz of Paypal does not support requested currency. For Example : If you are trying to checkout with Indian Rupee , You would get this type of error due to paypal does not support Indian Rupee. In this condition you have to switch the your base currency to paypal supported currency. But with this solution your store price will be changed. so that here i came with small hack.

I have used small trick to rid this error. It is not good solution but sometime it is useful.

Go to app\code\core\Mage\Paypal\Model\Express\Checkout.php. Find the public function start and find below code

$this->_api->setAmount($this->_quote->getBaseGrandTotal())
            ->setCurrencyCode($this->_quote->getBaseCurrencyCode())
            ->setInvNum($this->_quote->getReservedOrderId())
            ->setReturnUrl($returnUrl)
            ->setCancelUrl($cancelUrl)
            ->setSolutionType($solutionType)
            ->setPaymentAction($this->_config->paymentAction);

Just replace the below code

$this->_api->setAmount($this->_quote->getBaseGrandTotal())
            ->setCurrencyCode('USD')
            ->setInvNum($this->_quote->getReservedOrderId())
            ->setReturnUrl($returnUrl)
            ->setCancelUrl($cancelUrl)
            ->setSolutionType($solutionType)
            ->setPaymentAction($this->_config->paymentAction);

With this trick now you will go to paypal without any error. But you have to convert the price from Base Currency to USD.

Note: This solution is only for Paypal Express Users.

That's it. Enjoy Chandresh Rana's Coding...

How to make custom mini shopping cart in header magento

How to make custom mini shopping cart in header magento

Kindly Copy the below code and paste it into your header.phtml file.

<div class="shopping_cart active">
<?php $cart = Mage::getModel('checkout/cart')->getQuote(); ?>
    <?php $cnt = Mage::helper('checkout/cart')->getSummaryCount(); ?>
    <div class="icon">
        <i class="shopping-bag-icon v-middle"></i>
        <span class="count-number"><?php if($cnt > 0){echo $cnt;}else{echo "0";} ?></span>
    </div>
    <span class="block-cart hidden-xs hidden-sm">
        <b class="hidden-xs hidden-sm m-l-sm">MY BAG</b>
        <p>item(s)</p>
    </span>
    <?php if($cnt > 0): ?>
        <div class="cart_block cart-block exclusive">
            <div class="block_content">
                <p class="cart-subtitle">Recently added item(s)</p>
                <div class="cart_block_list">
                    <div class="products">
                        <?php foreach ($cart->getAllVisibleItems() as $item): ?>
                                <?php $_product = Mage::getModel('catalog/product')->load($item->getProduct()->getId()); ?>
                                <div class="product-item-list">
                                    <a href="<?php echo $_product->getProductUrl() ?>" class="cart-images">
                                        <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize(72, 99); ?>" class="img-responsive"></a>
                                    <div class="cart-info">
                                        <div class="product-name">
                                            <a href="<?php echo $_product->getProductUrl() ?>" class="cart_block_product_name"><?php echo $_product->getName(); ?></a>
                                        </div>
                                        <span><?php echo $item->getQty(); ?>  x </span>
                                        <span class="price"><?php echo Mage::helper('core')->currency($_product->getFinalPrice(), 2); ?> </span>
                                    </div>
                                    <span class="remove_link">
                                           <a href="<?php echo $this->getUrl('checkout/cart/delete',array('id'=>$item->getId(),Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => $this->helper('core/url')->getEncodedUrl())); ?>" rel="nofollow" title="remove this product from my cart"><i class="delet-item"></i>
                                            </a>
                                     </span>
                                </div>
                        <?php endforeach; ?>      
                    </div>
                </div>
            </div>
           
            <div class="clearfix"></div>
            <div class="buttons  m-t-sm">
                <div class="row">
                    <div class="col-xs-6 p-r-xs">
                        <button onclick="setLocation('<?php echo $this->getUrl('checkout/cart'); ?>')" type="button" title="View Bag" class="btn btn-theme btn-block"><span>VIEW BAG</span> </button>
                    </div>
                    <div class="col-xs-6 p-l-xs">
                        <button onclick="setLocation('<?php echo $this->getUrl('onepagecheckout'); ?>')" class="btn brown-btn  btn-block" title="Checkout" type="button"><span>CHECKOUT</span> </button>
                    </div>  
                </div>  
            </div>

        </div>

    <?php endif; ?>
</div>

Tuesday, 8 November 2016

How to set validation on checkout with minimum qty purchase magento



How to set validation on checkout with minimum qty magento

Put below code in your module/any module config.xml file after <models> block
<global>
    <events>
        <controller_action_predispatch_checkout_onepage_index>
            <observers>
                <spirit_cms_validate_checkout>
                    <class>Setblue_Banner_Model_Observer</class>
                    <method>validateCheckout</method>
                </spirit_cms_validate_checkout>
            </observers>
        </controller_action_predispatch_checkout_onepage_index>
    </events>
</global>

Next we need to create observer file to read this code. Create Observer.php in /yourmodule/Model/Observer.php and put the below code :

public function validateCheckout($observer)
{
    // Ensure we only observe once. $oObserver
    if( Mage::registry( 'restrict_checkout_flag' ) )
    {
        return $this;
    }
    else
    {
        $oQuote = Mage::getSingleton( 'checkout/cart' )->getQuote();
        $oCartItems = $oQuote->getAllItems();
        $iTotalAmount = $oQuote->getGrandTotal();
        $iGroupId = $oQuote->getCustomerGroupId();
        $iTotalQty = 0;
        foreach( $oCartItems as $oCartItem )
        {
            $iTotalQty = $iTotalQty + $oCartItem->getQty();
        }
        if($iGroupId == '2'){
            if( $iTotalQty < 15 )
            {
                $oSession = Mage::getSingleton( 'checkout/session' );
                $oSession->addError( 'Please add at least 15 items to your cart.' );
                Mage::app()->getResponse()->setRedirect( Mage::getUrl( 'checkout/cart' ) );
            }
            Mage::register( 'restrict_checkout_flag', 1, TRUE );
        }
     
    }
}

Monday, 7 November 2016

How to Remove "What is PayPal?" from PayPal payment method on checkout magento



How to Remove "What is PayPal?" from PayPal payment method on checkout magento

In magento by default paypal payment method provide Paypal logo and and "What is Paypal?" text with title. Here i will given you exact file where you remove logo and "What is Paypal?" text.

Just open /app/design/frontend/base/default/template/paypal/payment/mark.phtml file. In this file you can easily find paypal logo and "What is paypal?" text.. Just remove it or comment it out.



Thats it enjoy chandresh rana coding.... :)

How to get the joomla base url


Here is the joomla base url/site url

<?php echo JURI::base(); ?>

Monday, 17 October 2016

Register Customer approve by admin for wholesale user group magento


Register Customer approve by admin for wholesale user group magento

To Enable the Require Emails Confirmation, Go to system->configuration->Customer configuration open Create New Account Options section


Open register.phtml and put the below line before the submit button for assign wholesale group.

<input type="hidden" name="group_id" id="group_id" value="2" />

Now open \app\code\core\Mage\Customer\controllers\AccountController.php

Change $message variable like below in loginPostAction() function

$message = $this->_getHelper('customer')->__('This account is not approved. You will receive an email with confirmation once your account is approved by admin.');

Change in createPostAction() function

Find $errUrl = $this->_getUrl('*/*/login', array('_secure' => true));

and replace as below

    if($this->getRequest()->getPost('group_id') == 2){
        $errUrl = $this->_getUrl('*/*/create?register=wholesale', array('_secure' => true));
    }else{
        $errUrl = $this->_getUrl('*/*/login', array('_secure' => true));
    }

Now Replace _successProcessRegistration() function as below  
   
    protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
    {
        $session = $this->_getSession();
/* Code By Chand */
        if ($customer->isConfirmationRequired() && $this->getRequest()->getPost('group_id') == 2) {
            /** @var $app Mage_Core_Model_App */
            $app = $this->_getApp();
            /** @var $store  Mage_Core_Model_Store*/
            $store = $app->getStore();
            $customer->sendNewAccountEmail(
                'confirmation',
                $session->getBeforeAuthUrl(),
                $store->getId()
            );
            $customerHelper = $this->_getHelper('customer');
            $session->addSuccess($this->__('Thank you for registering with us. Your account is under moderation and will be approved by admin soon.',
/* End Code By Chand */  
                $customerHelper->getEmailConfirmationUrl($customer->getEmail())));
            $url = $this->_getUrl('*/*/index', array('_secure' => true));
        } else {
            $session->setCustomerAsLoggedIn($customer);
            $url = $this->_welcomeCustomer($customer);
        }
        $this->_redirectSuccess($url);
        return $this;
    }

In _getCustomer() function replace line $customer->getGroupId(); as below

if($this->getRequest()->getPost('group_id')){
       $customer->setGroupId($this->getRequest()->getPost('group_id'));
}else{
$customer->getGroupId();
}


Now open \app\code\core\Mage\Customer\Model\Customer.php and replace isConfirmationRequired() function as below

    public function isConfirmationRequired()
    {
        if ($this->canSkipConfirmation()) {
            return false;
        }
/* Code By Chand */
        if (self::$_isConfirmationRequired === null && $this->getGroupId() == 2) {
            $storeId = $this->getStoreId() ? $this->getStoreId() : null;
            self::$_isConfirmationRequired = (bool)Mage::getStoreConfig(self::XML_PATH_IS_CONFIRM, $storeId);
        }
/* End Code By Chand */
        return self::$_isConfirmationRequired;
    }


Go to magento admin panel open transactional Emails in system. Open New account confirmation key template and paste below code:

    {{template config_path="design/email/header"}}
    {{inlinecss file="email-inline.css"}}
   
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td>
                <table cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td class="action-content">
                            <h1>{{htmlescape var=$customer.name}},</h1>
                            <p>Thank you for registering with us. Your account is under moderation and will be approved by admin soon.</p>
                            <p class="highlighted-text">
                                Use the following values when prompted to log in:<br/>
                                <strong>Email:</strong> {{var customer.email}}<br/>
                                <strong>Password:</strong> {{htmlescape var=$customer.password}}
                            </p>
                            <p>
                                If you have any questions, please feel free to contact us at
                                <a href="mailto:{{var store_email}}">{{var store_email}}</a>
                                {{depend store_phone}} or by phone at <a href="tel:{{var phone}}">{{var store_phone}}</a>{{/depend}}.
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
   
    {{template config_path="design/email/footer"}}


Open New account confirmed template and paste below code:

    {{template config_path="design/email/header"}}
    {{inlinecss file="email-inline.css"}}
   
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td class="action-content">
                <h1>{{htmlescape var=$customer.name}},</h1>
                <p>Congratulations. Your account has been approved. Now you can access our wholesale catalog price.</p>
                <p>To log in when visiting our site just click <a href="{{store url="customer/account/"}}">Login</a> or <a href="{{store url="customer/account/"}}">My Account</a> at the top of every page, and then enter your email address and password.</p>
                <p>When you log in to your account, you will be able to do the following:</p>
                <ul>
                    <li>Proceed through checkout faster when making a purchase</li>
                    <li>Check the status of orders</li>
                    <li>View past orders</li>
                    <li>Make changes to your account information</li>
                    <li>Change your password</li>
                    <li>Store alternative addresses (for shipping to multiple family members and friends!)</li>
                </ul>
                <p>
                    If you have any questions, please feel free to contact us at
                    <a href="mailto:{{var store_email}}">{{var store_email}}</a>
                    {{depend store_phone}} or by phone at <a href="tel:{{var phone}}">{{var store_phone}}</a>{{/depend}}.
                </p>
            </td>
        </tr>
    </table>
   
    {{template config_path="design/email/footer"}}

Assigned both template from Customer configuration in magento admin panel.


Thursday, 29 September 2016

Sales report shows wrong invoiced amount in magento


Sales report shows wrong invoiced amount in magento

Most of people have this issue.

The solution is that refresh the lifetime statistic instead of the daily statistic refresh.

Moreover refer the below picture for more information about the current report.