Pages

Monday 2 February 2015

Magento:: Scroll To Top functionality

Scroll To Top functionality in Magento
Open your header.phtml file and write below code..
<a title="Scroll To Top" class="scrollup" href="javascript:void(0);" style="display: none;">Scroll</a>
<script type="text/javascript">
jQuery(document).scroll(function(){
if (jQuery(this).scrollTop() > 100) {
jQuery('.scrollup').fadeIn();
} else {
jQuery('.scrollup').fadeOut();
}
});
jQuery('.scrollup').click(function(){
jQuery("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
</script>

Wednesday 21 January 2015

Magento:: Delete all orders

Run the below Sql Script to your database for delete all orders
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE `sales_flat_order`;
TRUNCATE `sales_flat_order_address`;
TRUNCATE `sales_flat_order_grid`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sales_flat_order_status_history`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_payment`;
TRUNCATE `sales_flat_quote_payment`;
TRUNCATE `sales_flat_shipment`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_grid`;
TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice_grid`;
TRUNCATE `sales_flat_invoice_item`;
TRUNCATE `sales_flat_creditmemo`;
TRUNCATE `sales_flat_creditmemo_comment`;
TRUNCATE `sales_flat_creditmemo_grid`;
TRUNCATE `sales_flat_creditmemo_item`;
TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;

ALTER TABLE `sales_flat_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=1;
ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;
SET FOREIGN_KEY_CHECKS=1;

Magento :: Mini Login Form in header section

Let’s open app/design/frontend/your_package/your_theme/layout/customer.xml 
and just add the following line after <customer_logged_out>
<reference name="header">
            <block type="customer/form_login" name="header_customer_form_mini_login"  template="customer/form/mini.login.phtml"/>
        </reference>
Like:
<customer_logged_out>
        <reference name="header">
            <block type="customer/form_login" name="header_customer_form_mini_login"  template="customer/form/mini.login.phtml"/>
        </reference>
        <!---<reference name="right">
            <block type="customer/form_login" name="customer_form_mini_login" before="-" template="customer/form/mini.login.phtml"/>
        </reference>-->
        <reference name="top.links">
            <action method="addLink" translate="label title" module="customer"><label>Log In</label><url helper="customer/getLoginUrl"/><title>Log In</title><prepare/><urlParams/><position>100</position></action>
        </reference>
        <remove name="reorder"></remove>
    </customer_logged_out>
Now open app/design/frontend/your_package/Your_theme/template/page/html/header.phtml and add the following lines where yoy want to display login button:
<div id="header-login" class="" style="position:relative;">
            <?php if (! Mage::getSingleton('customer/session')->isLoggedIn()): ?<?php echo $this->__('Login') ?>
            <?php echo $this->getChildHtml('header_customer_form_mini_login') ?>
            <?php else: ?>
          <a href="<?php echo Mage::helper('customer')->getLogoutUrl(); ?>" title="Log Out" class="login"><?php echo $this->__('Log Out') ?></a>
          <?php endif; ?>
        </div>
And, lastly, open app/design/frontend/your_package/your_theme/template/customer/form/mini.login.phtml and modify the file according the following file:
<style>
 #dropdown
 {
  position: absolute;
    border:1px solid #ccc;
    padding:20px;
  top: 20px;
  left: 0px;
  visibility: hidden;
    background:white;
    z-index:1111;
 }
 #header-login:hover #dropdown
 {
  visibility: visible;
 }
</style>
<div class="block block-login" id="dropdown">
    <div class="block-title">
        <strong><span><?php echo $this->__('Login') ?></span></strong>
    </div>
    <form action="<?php echo $this->getUrl('customer/account/loginPost'); ?>" method="post">
        <?php echo $this->getBlockHtml('formkey'); ?>
        <div class="block-content">
            <label for="mini-login"><?php echo $this->__('Email:') ?></label><input type="email" autocapitalize="off" autocorrect="off" spellcheck="false" name="login[username]" id="mini-login" class="input-text" />
            <label for="mini-password"><?php echo $this->__('Password:') ?></label><input type="password" name="login[password]" id="mini-password" class="input-text" />
            <div class="actions">
                <button type="submit" class="button"><span><span><?php echo $this->__('Login') ?></span></span></button>
            </div>
        </div>
    </form>
</div>
Note: In the customer.xml I am using core/template block instead of customer/form_login. The reason for this is that the latter sets the page title to ‘Customer login‘ on all pages it’s being displayed on.

As i am using different block, so now i can’t use methods of the customer/form_login block. Because we’re using $this->getUrl(‘customer/account/loginPost’) as a form action instead of $this->getPostActionUrl().

Tuesday 20 January 2015

Magento:: Social sharing buttons

  • Open app/design/frontend/YOUR_PACKAGE/YOUR_THEME/template/catalog/product/view.phtml
  • Find the place where you want to add your links/buttons and add the following:
<?php $productName = $_helper->productAttribute($_product, $_product->getName(), 'name'); ?>
<?php $productUrl = $_helper->productAttribute($_product, $_product->getProductUrl(), 'product_url'); ?>
<?php $productImage = $_product->getImageUrl() ?>
  • Add the following code below the variables we defined in the previous step:
// Google Plus
<a href="javascript:popWin('https://plus.google.com/share?url=<?php echo urlencode($productUrl); ?>', 'google', 'width=640,height=480,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes');" title="<?php echo $this->__('Share on Google Plus') ?>">Google Plus</a>
// Facebook
<a href="javascript:popWin('https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($productUrl); ?>&t=<?php echo urlencode($productName); ?>', 'facebook', 'width=640,height=480,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes');" title="<?php echo $this->__('Share on Facebook') ?>">Facebook</a>
// Twitter
<a href="javascript:popWin('http://twitter.com/home/?status=<?php echo urlencode($productName . ' (' . $productUrl . ')'); ?>', 'twitter', 'width=640,height=480,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes');" title="<?php echo $this->__('Tweet') ?>">Twitter</a>
// Pinterest
<a href="javascript:popWin('https://pinterest.com/pin/create/button/?url=<?php echo urlencode($productUrl); ?>&media=<?php echo urlencode($productImage); ?>&description=<?php echo urlencode($productName); ?>', 'pinterest', 'width=640,height=480,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes');" title="<?php echo $this->__('Pin it') ?>">Pinterest</a>
Adding OpenGraph meta tags to your Magento store is quite easy. Just add the following code below the last meta tag (should be a meta tag named “robots” if you are using a default Magento head file) in app/design/frontend/YOUR_PACKAGE/YOUR_THEME/template/page/html/head.phtml
<?php $product = Mage::registry('current_product');
if ($product): ?>
<meta property="og:title" content="<?php echo $product->getName(); ?>" />
<meta property="og:type" content="product" />
<meta property="og:url" content="<?php echo $this->helper('catalog/product')->getProductUrl($product); ?>" />
<meta property="og:image" content="<?php echo $this->helper('catalog/image')->init($product, 'image')->resize(300, 300); ?>" />
<meta property="og:description" content="<?php echo strip_tags($product->getShortDescription()); ?>" />
<meta property="og:site_name" content="<?php echo Mage::app()->getStore()->getName() ?>" />
<?php endif; ?>

Magento:: Add jQuery Class based on php variable

<?php
 if($sub_cat_count > 2){
 ?>
    <script>
        jQuery(document).ready(function(){
            //alert('hiiiiiii');
        jQuery("#product-listing").addClass("scroll");
        
        }); 
    </script>
<?php
    }
?>

Friday 16 January 2015

Magento:: Sort Admin Category List Alphabetically

There is a feature in Magento where the category list can be sorted based on how the administrator sees fit. The problem is that most stores will want to sort the category list alphabetically. With a large catalog, the list quickly becomes a hassle to navigate and becomes a frustrating time sink.
The solution detailed here extends a Magento core file to sort the category list. It will sort the categories for both the Category Edit and the Product Edit Category tab.

Example of Alphabetically Sorted Magento Categories

The Quick Solution:

The quick solution is to use the PHP method usort() on the array of categories in a Magento core file.
overriding the magento core file: create the file Tree.php as following directory
app/code/local/Mage/Adminhtml/Block/Catalog/Category/Tree.php
Tree.php file:
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright   Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */


/**
 * Categories tree block
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Catalog_Category_Tree extends Mage_Adminhtml_Block_Catalog_Category_Abstract
{

    protected $_withProductCount;

    public function __construct()
    {
        parent::__construct();
        $this->setTemplate('catalog/category/tree.phtml');
        $this->setUseAjax(true);
        $this->_withProductCount = true;
    }

    protected function _prepareLayout()
    {
        $addUrl = $this->getUrl("*/*/add", array(
            '_current'=>true,
            'id'=>null,
            '_query' => false
        ));

        $this->setChild('add_sub_button',
            $this->getLayout()->createBlock('adminhtml/widget_button')
                ->setData(array(
                    'label'     => Mage::helper('catalog')->__('Add Subcategory'),
                    'onclick'   => "addNew('".$addUrl."', false)",
                    'class'     => 'add',
                    'id'        => 'add_subcategory_button',
                    'style'     => $this->canAddSubCategory() ? '' : 'display: none;'
                ))
        );

        if ($this->canAddRootCategory()) {
            $this->setChild('add_root_button',
                $this->getLayout()->createBlock('adminhtml/widget_button')
                    ->setData(array(
                        'label'     => Mage::helper('catalog')->__('Add Root Category'),
                        'onclick'   => "addNew('".$addUrl."', true)",
                        'class'     => 'add',
                        'id'        => 'add_root_category_button'
                    ))
            );
        }

        $this->setChild('store_switcher',
            $this->getLayout()->createBlock('adminhtml/store_switcher')
                ->setSwitchUrl($this->getUrl('*/*/*', array('_current'=>true, '_query'=>false, 'store'=>null)))
                ->setTemplate('store/switcher/enhanced.phtml')
        );
        return parent::_prepareLayout();
    }

    protected function _getDefaultStoreId()
    {
        return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
    }

    public function getCategoryCollection()
    {
        $storeId = $this->getRequest()->getParam('store', $this->_getDefaultStoreId());
        $collection = $this->getData('category_collection');
        if (is_null($collection)) {
            $collection = Mage::getModel('catalog/category')->getCollection();

            /* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
            $collection->addAttributeToSelect('name')
                ->addAttributeToSelect('is_active')
                ->setProductStoreId($storeId)
                ->setLoadProductCount($this->_withProductCount)
                ->setStoreId($storeId);

            $this->setData('category_collection', $collection);
        }
        return $collection;
    }

    public function getAddRootButtonHtml()
    {
        return $this->getChildHtml('add_root_button');
    }

    public function getAddSubButtonHtml()
    {
        return $this->getChildHtml('add_sub_button');
    }

    public function getExpandButtonHtml()
    {
        return $this->getChildHtml('expand_button');
    }

    public function getCollapseButtonHtml()
    {
        return $this->getChildHtml('collapse_button');
    }

    public function getStoreSwitcherHtml()
    {
        return $this->getChildHtml('store_switcher');
    }

    public function getLoadTreeUrl($expanded=null)
    {
        $params = array('_current'=>true, 'id'=>null,'store'=>null);
        if (
            (is_null($expanded) && Mage::getSingleton('admin/session')->getIsTreeWasExpanded())
            || $expanded == true) {
            $params['expand_all'] = true;
        }
        return $this->getUrl('*/*/categoriesJson', $params);
    }

    public function getNodesUrl()
    {
        return $this->getUrl('*/catalog_category/jsonTree');
    }

    public function getSwitchTreeUrl()
    {
        return $this->getUrl("*/catalog_category/tree", array('_current'=>true, 'store'=>null, '_query'=>false, 'id'=>null, 'parent'=>null));
    }

    public function getIsWasExpanded()
    {
        return Mage::getSingleton('admin/session')->getIsTreeWasExpanded();
    }

    public function getMoveUrl()
    {
        return $this->getUrl('*/catalog_category/move', array('store'=>$this->getRequest()->getParam('store')));
    }

    public function getTree($parenNodeCategory=null)
    {
           $rootArray = $this->_getNodeJson($this->getRoot($parenNodeCategory));
        $tree = isset($rootArray['children']) ? $rootArray['children'] : array();
        return $tree;
    }

    public function getTreeJson($parenNodeCategory=null)
    {
        $rootArray = $this->_getNodeJson($this->getRoot($parenNodeCategory));
        $json = Mage::helper('core')->jsonEncode(isset($rootArray['children']) ? $rootArray['children'] : array());
        return $json;
    }

    /**
     * Get JSON of array of categories, that are breadcrumbs for specified category path
     *
     * @param string $path
     * @param string $javascriptVarName
     * @return string
     */
    public function getBreadcrumbsJavascript($path, $javascriptVarName)
    {
        if (empty($path)) {
            return '';
        }

        $categories = Mage::getResourceSingleton('catalog/category_tree')
            ->setStoreId($this->getStore()->getId())->loadBreadcrumbsArray($path);
        if (empty($categories)) {
            return '';
        }
        foreach ($categories as $key => $category) {
            $categories[$key] = $this->_getNodeJson($category);
        }
        return
            '<script type="text/javascript">'
            . $javascriptVarName . ' = ' . Mage::helper('core')->jsonEncode($categories) . ';'
            . ($this->canAddSubCategory() ? '$("add_subcategory_button").show();' : '$("add_subcategory_button").hide();')
            . '</script>';
    }

    /**
     * Get JSON of a tree node or an associative array
     *
     * @param Varien_Data_Tree_Node|array $node
     * @param int $level
     * @return string
     */
    protected function _getNodeJson($node, $level = 0)
    {
        // create a node from data array
        if (is_array($node)) {
            $node = new Varien_Data_Tree_Node($node, 'entity_id', new Varien_Data_Tree);
        }

        $item = array();
        $item['text'] = $this->buildNodeName($node);

        /* $rootForStores = Mage::getModel('core/store')
            ->getCollection()
            ->loadByCategoryIds(array($node->getEntityId())); */
        $rootForStores = in_array($node->getEntityId(), $this->getRootIds());

        $item['id']  = $node->getId();
        $item['store']  = (int) $this->getStore()->getId();
        $item['path'] = $node->getData('path');

        $item['cls'] = 'folder ' . ($node->getIsActive() ? 'active-category' : 'no-active-category');
        //$item['allowDrop'] = ($level<3) ? true : false;
        $allowMove = $this->_isCategoryMoveable($node);
        $item['allowDrop'] = $allowMove;
        // disallow drag if it's first level and category is root of a store
        $item['allowDrag'] = $allowMove && (($node->getLevel()==1 && $rootForStores) ? false : true);

        if ((int)$node->getChildrenCount()>0) {
            $item['children'] = array();
        }

        $isParent = $this->_isParentSelectedCategory($node);

        if ($node->hasChildren()) {
            $item['children'] = array();
            if (!($this->getUseAjax() && $node->getLevel() > 1 && !$isParent)) {
                foreach ($node->getChildren() as $child) {
                    $item['children'][] = $this->_getNodeJson($child, $level+1);
                }
            }
            // Sort the children category array
            usort($item['children'], array(get_class($this), 'compareChildText'));
        }

        if ($isParent || $node->getLevel() < 2) {
            $item['expanded'] = true;
        }

        return $item;
    }
    
    /**
     * Helper comparison function to return the category children array, sorted alphabetically
     * @param type $a
     * @param type $b
     * @return type 
     */
    static function compareChildText($a, $b)
    {
        return strnatcmp(strtolower($a['text']), strtolower($b['text']));
    }

    /**
     * Get category name
     *
     * @param Varien_Object $node
     * @return string
     */
    public function buildNodeName($node)
    {
        $result = $this->htmlEscape($node->getName());
        if ($this->_withProductCount) {
             $result .= ' (' . $node->getProductCount() . ')';
        }
        return $result;
    }

    protected function _isCategoryMoveable($node)
    {
        $options = new Varien_Object(array(
            'is_moveable' => true,
            'category' => $node
        ));

        Mage::dispatchEvent('adminhtml_catalog_category_tree_is_moveable',
            array('options'=>$options)
        );

        return $options->getIsMoveable();
    }

    protected function _isParentSelectedCategory($node)
    {
        if ($node && $this->getCategory()) {
            $pathIds = $this->getCategory()->getPathIds();
            if (in_array($node->getId(), $pathIds)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if page loaded by outside link to category edit
     *
     * @return boolean
     */
    public function isClearEdit()
    {
        return (bool) $this->getRequest()->getParam('clear');
    }

    /**
     * Check availability of adding root category
     *
     * @return boolean
     */
    public function canAddRootCategory()
    {
        $options = new Varien_Object(array('is_allow'=>true));
        Mage::dispatchEvent(
            'adminhtml_catalog_category_tree_can_add_root_category',
            array(
                'category' => $this->getCategory(),
                'options'   => $options,
                'store'    => $this->getStore()->getId()
            )
        );

        return $options->getIsAllow();
    }

    /**
     * Check availability of adding sub category
     *
     * @return boolean
     */
    public function canAddSubCategory()
    {
        $options = new Varien_Object(array('is_allow'=>true));
        Mage::dispatchEvent(
            'adminhtml_catalog_category_tree_can_add_sub_category',
            array(
                'category' => $this->getCategory(),
                'options'   => $options,
                'store'    => $this->getStore()->getId()
            )
        );

        return $options->getIsAllow();
    }
}
Refersh the cache and recompile:

Magento:: Changing default category products sort order

There are two options you can use via Magento administration.

1. Setting default Sort Order for category

When you go to Category page in Magento administration (Catalog/Manage Categories), you’ll see “Display Settings” tab. From there you can modify “Available Product Listing Sort By” and “Default Product Listing Sort By” values.
Let’s modify “Default Product Listing Sort By”. If you deselect “Use Config Settings” and if you select “Price” for “Default Product Listing Sort By”, on frontend for specified category you’ll see that all items are now sorted by price ascending (growing upward). If you have Magento CE 1.7 with Sample Data you can modify sorting by Price for, i.e. Bedroom category. Additionally you can deselect “Use All Available Attributes” for “Available Product Listing Sort By” and if you check only few of them (“Best Value” and “Price”), on frontend you’ll be able to sort only by selected options. Now click “Save Category” button.
You should see something like this:

2. Setting default Sort Order for Store / Website / Default Config

 When you go to System / Configuration / Catalog (left menu) / Frontend you’ll see “Product Listing Sort by” drop down menu. Now if you deselect “Use Default” you’ll select default sorting for specified view (Store/Website/Default). This will apply to all categories but notice that by override rule (fallback) this has lower priority than “Sort Order for category”.

Thursday 15 January 2015

Magento:: Add Datepicker to contact form

“Magento has a built in library for calendar functionalities. However the calendar library is available only on Admin pages like Customer Grid,Customer Account view page,Sales order Grid etc. We can extend the prototype Javascript library’s calendar functions to frontend.

 Step 1: Edit the page.xml file in your current theme in the directory
 app/design/frontend/default/yourthemename/layout/page.xml
 Around line 37(according to magento 1.9) add the below lines in between

<!-- Add custom js for calendar -->
                <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name></action>
                <action method="addItem"><type>js</type><name>calendar/calendar.js</name></action>
                <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name></action>
                <block type="core/html_calendar" name="head.calendar" as="calendar" template="page/js/calendar.phtml" />
The Above lines will include the calendar library functions in the page head of all front end pages.

Step 2: Next Step is to add the Date Field in Magento Form. For this example iam adding a date field called dob(date of birth) in the magento contact form. Iam calling the magento skin url as getSkinUrl().’images/calendar.gif'; ?> to include the calendar.gif image.
Note: You need to copy the image from base  and paste it in your current theme.
app/design/frontend/yourthemename/default/template/contacts/form.phtml
<li class="fields">
    <div class="field">
        <label for="dob"><?php echo Mage::helper('contacts')->__('DOB') ?></label>
        <div class="input-box">
            <input name="dob" id="_dob" title="<?php echo Mage::helper('contacts')->__('DOB'); ?>" value="" class="input-text" type="text" />
        </div>
    </div>
    <div class="field">
        <label for="calendar">&nbsp;</label>
        <div class="input-box">
            <img style="" title="Select Date" id="_dob_trig" class="v-middle" alt="" src="<?php echo $this->getSkinUrl().'images/calendar.gif' ?>"
        </div>
    </div>
</li>
Step 3: Next step would be to add some Javascript code in the contact form template file. The id of the date input field and calendar image should be the same. In our case the id is “_dob_trig” . The javascript code shown below should be added below the contact form coding.
<script type="text/javascript">
//<![CDATA[
Calendar.setup({
                inputField: "_dob",
                ifFormat: "%m/%e/%Y",
                showsTime: false,
                button: "_dob_trig",
                align: "B1",
                singleClick: true
                });
//]]>
</script>
Step 4: To get the date value in the contact form email add the following line in the emailtemplate app/locale/en_US/template/email/contact_form.html
Date Of Birth: {{var data.dob}}
Once the form is submitted all the form data will be emailed to the store admin.
Step 5: Now  if the calendar icon is clicked the date will be populated and the selected date will be populated in the textbox.

Magento:: Display Dropdown For Quantity Box

In the addtocart.phtml file find the following code(near line 34)
<input type="text" pattern="\d*" name="qty" id="qty" maxlength="12" value="<?php echo max($this->getProductDefaultQty() * 1, 1) ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
Replace with this code:
1-This code shows the “Available Qty for Product”.
<select class="input-text qty" name="qty" id="qty">
  <?php $i = 1 ?>
  <?php do { ?>
    <option value="<?php echo $i?>">
      <?php echo $i?>
      <?php $i++ ?>
    </option>
<?php } while ($i <= (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()) ?></select>
2- This code shows the “Maximum Qty Allowed in Shopping Cart”.
<select class="input-text qty" name="qty" id="qty">
    <?php $i = 1 ?>
    <?php do { ?>
        <option value="<?php echo $i ?>">
            <?php echo $i ?>
            <?php $i++ ?>
        </option>
    <?php } while ($i <= (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getMaxSaleQty()) ?>
</select>

Magento::Increase Admin session timeout

To increase the session time in admin Go to
 System => Configuration => Admin => Security => set Session Lifetime (seconds) : value as you want. ( like : 14000).

 Now  go to System => Configuration =>Web => Session Cookie Management => set Cookie Lifetime
 14000.

Magento:: Show Product Sold Quantity On Detail Page

1- If you want to show stock sold on the product page for the entire duration the product has been active, use the following code:
<?php
 $sku = nl2br($_product->getSku());
 $product = Mage::getResourceModel('reports/product_collection')
 ->addOrderedQty()
 ->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();

echo 'Already Bought '.(int)$product->ordered_qty; ?>
2- if you want to show Qty ordered today, use the following code:
<?php
$sku = nl2br($_product->getSku());
$to = $_product->getResource()->formatDate(time());
$from = $_product->getResource()->formatDate(time() - 60 * 60 * 24 * 1);
$product = Mage::getResourceModel('reports/product_collection')
->addOrderedQty($from, $to, true)
->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();
echo 'Quantity Ordered Today '.(int)$product->ordered_qty; ?>
3- If you want to have it so that it only shows quantity sold on the product page on items that are currently on sale.. use the following., There will also be an alert for customers when there is only 1 remaining in stock.Then use the following code.
<?php
$_finalPrice = $this->helper('tax')->getPrice($_product, $_product->getFinalPrice());
$_regularPrice = $this->helper('tax')->getPrice($_product, $_product->getPrice());
if ($_regularPrice != $_finalPrice):
$sku = nl2br($_product->getSku());
$to = $_product->getResource()->formatDate(time());
$from = $_product->getResource()->formatDate(time() - 60 * 60 * 24 * 1);
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addOrderedQty($from, $to, true)
->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();

$product = $_productCollection;
echo 'Already Bought Today '.(int)$product->ordered_qty;

endif;

if ((int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()==1): ?>

<p style="color:#990000; padding:5px 0; text-align:right;"><strong>ONLY 1 LEFT IN STOCK!</strong></p>

<?php endif; ?>

MAgento:: Get product id on list page

<?php $product_id= $_helper->productAttribute($_product, $_product->getId(), 'id');

Wednesday 14 January 2015

Magento:: Product Collection using Ids Or Sku

Following code load product useing ids.
$productIds = array(5, 22, 45, 75, 88);
$attributes = Mage::getSingleton('catalog/config')->getProductAttributes();
$_productCOllection = Mage::getModel('catalog/product')
                ->getCollection()              
                ->addAttributeToFilter('entity_id', array('in' => $productIds))
                ->addAttributeToSelect($attributes);// $attributes or '*'
or collection within a range
$_productCOllection = Mage::getModel('catalog/product')->getCollection()
   ->addAttributeToSelect('*')
   ->addAttributeToFilter('entity_id', array(
    'from' => $startPrOID,
    'to' => $EndPrOID
    ))
    ->load();
Following code load product useing SKUs.
$productSku = array('1111', '1112', '1113', 'HTC Touch Diamond', 'microsoftnatural');
$attributes = Mage::getSingleton('catalog/config')->getProductAttributes();
$collection = Mage::getModel('catalog/product')
                ->getCollection()              
                ->addAttributeToFilter('sku', array('in' => $productSku))
                ->addAttributeToSelect($attributes);

Magento::Bestselling products in Home Page

1. Create a new file for Block

Magento_root/app/code/local/Mage/Catalog/Block/Product/Bestseller.php
Bestseller.php
<?php
/**
 * Catalog Product Bestseller Block
 */
class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract
{
    public function getCollection()
    {
        $storeId = Mage::app()->getStore()->getId();
        $collection = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc');
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
        $collection->setPage(1, $this->getLimit());
        return $collection;
    }
}
2. Create a template file for the new block:
Magento_root/app/design/frontend/base/default/template/catalog/product/bestseller.phtml
bestseller.phtml
<?php
/**
 * Bestseller Products block template
 *
 * @see Mage_Catalog_Block_Product_Bestseller
 */
?>
<div class="block block-list block-viewed">
    <div class="block-title">
        <strong><span><?php echo $this->__($this->getHeader()) ?></span></strong>
    </div>
    <div class="block-content">
        <?php $products = $this->getCollection(); ?>
        <?php if (0 < $products->getSize()) { ?>
            <table class="bestseller-table">
                <tr>
                    <?php foreach ($products as $p) { ?>
                        <td style="padding: 15px 15px 0px 15px;">
                            <a href="<?php echo $p->getProductUrl() ?>" title="<?php echo $this->htmlEscape($p->getName()) ?>" class="product-image">
                                <img src="<?php echo $this->helper('catalog/image')->init($p, 'small_image')->resize(125) ?>" width="125" height="125" alt="<?php echo $this->htmlEscape($p->getName()) ?>" />
                            </a>
                            <h3 class="product-name">
                                <a href="<?php echo $p->getProductUrl() ?>" title="<?php echo $this->htmlEscape($p->getName())?>">
                                    <?php echo $this->htmlEscape($p->getName()) ?>
                                </a>
                            </h3>
                            <?php echo $this->getPriceHtml($p, true) ?>
                        </td>
                    <?php } ?>
                </tr>
                <tr>
                    <?php foreach ($products as $p) { ?>
                    <td style="padding: 0px 15px 15px;">
                        <?php if($p->isSaleable()): ?>
                            <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($p) ?>')">
                                <span><span><?php echo $this->__('Add to Cart') ?></span></span>
                            </button>
                        <?php else: ?>
                            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                        <?php endif; ?>
                    </td>
                    <?php } ?>
                </tr>
            </table>
        <?php } ?>
    </div>
</div>
3. Now you need to call the created block, to do that go to Backend > CMS > Pages > Edit Page ‘Home page’ and add the following lines of code:
{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml" header="Bestsellers" limit=4}}
Also you can add a new block via layout update:
<reference name="content">
        <block type="catalog/product_bestseller" name="bestseller" template="catalog/product/bestseller.phtml" before="-">
            <action method="setLimit"><limit>3</limit></action>
            <action method="setHeader"><header>Best Sellers</header></action>
        </block>
</reference>
For instance, try to add this block to the Category View page here: Backend > Catalog > Manage Categories > Click needed category in the category tree > `Custom Design` horizontal tab > ` Custom Layout Update` field Feel free to manipulate the result using the header and the limit variables.

Friday 9 January 2015

Magento:: Show product rating in custom page

I was looking for a solution to put the star rating element of a product in Magento on any given location. As most of you know, you can simply display the star rating element of a product (you know, the one with the five stars on a row) on a template like a product detail page or product list. But what if you have a product displayed elsewhere else and you just need to display the five stars without having access to the getReviewsSummaryHtml()-function?
You Can use the following code for display star rating in custom page.
getLayout()->createBlock('review/helper');
      echo $reviewHelper->getSummaryHtml($_product, 'short', false);
?>
Or The full product collection page with rating
<div class="product-listing">
<?php
$_productCollection = Mage::getModel('catalog/product')->getCollection();                              
//$_productCollection->addAttributeToFilter('feature','1'); //custom attribute is yes/no(1,0)
$_productCollection->addAttributeToFilter('status', 1); //enabled
$_productCollection->addAttributeToFilter('visibility', 4); //catalog, search
?>
<?php  
foreach ($_productCollection as $_product)
{
       $model = Mage::getModel('catalog/product');
       $product_id = $_product->getId();
       $_product = $model->load($product_id);
       //echo $_product->getPrice()."";
       //echo $_product->getName()."";
       $_image=Mage::getModel('catalog/product')->load($product_id);
       //echo Mage::helper('catalog/image')->init($_image, 'image')."";
       ?>
        <div class="feature-product">
            <div class="feature-product-image"><a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_image, 'image')->resize(200,200); ?>"></a></div>
            <div class="feature-product-price"><?php echo $_product->getPrice(); ?></div>
            <div class="feature-product-name"><?php echo $_product->getName(); ?></div>
           <?php $reviewHelper = $this->getLayout()->createBlock('review/helper');
                 echo $reviewHelper->getSummaryHtml($_product, 'short', false);
           ?>
        </div>
   <?php    
}                                       
  ?>
</div>

Thursday 8 January 2015

Magento: How to fix "The requested URL /index.php was not found on this server" error

If ever you're seeing an error like this when you go to your magento inner pages.



This might fix your problem. In your .htaccess file you probably have something like this :
 RewriteRule ^(.*)$ /index.php/$1 [L,QSA,PT]
Or
 RewriteRule .* /index.php [NS,L]
If that is so, just simply remove the leading "/" from the index.php then save it. Refresh the page. And voila! The issue should be fixed now.

Magento:: Change product image on hover in catalog page

To show different image on hover on magento product category page  you have to change the small code in the list.phtml file located at 

app->design->frontend->default->your theme->template->catalog->product->list.pthml 

and in this file around line 124 you will see something like this  // in magneto 1.9 line number could be different according to magneto version


<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
    <?php $_imgSize = 210; ?>
    <img id="product-collection-image-<?php echo $_product->getId(); ?>"
        src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
        alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
 </a>
just search for this and replace it with
<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
    <?php $_imgSize = 210; ?>
    <img id="product-collection-image-<?php echo $_product->getId(); ?>"
        src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->resize($_imgSize); ?>"
        alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"
        onmouseover="this.src='<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize($_imgSize) ?>';" onmouseout="this.src='<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize($_imgSize) ?>';"/>
</a>
Now in admin assign different image for thumbnail and small image. thumbnail image will show when you mouse over on product image.

Wednesday 7 January 2015

Magento:: Add custom attribute field in category

Note:- write down the code in head.phtml and give permission after run one time remove the code
<?php  require_once('app/Mage.php');
    Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
    $installer = new Mage_Sales_Model_Mysql4_Setup;
    $attribute = array(
    'type' => 'int',
    'label'=> 'Featured Category',
    'input' => 'select',
    'source' => 'eav/entity_attribute_source_boolean',
    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'visible' => true,
    'required' => false,
    'user_defined' => true,
    'default' => 0,
    'group' => "General Information"
    );
    $installer->addAttribute('catalog_category', 'featured_category', $attribute);
    $installer->endSetup();
?>

Mage_Eav_Model_Entity_Abstract setConnection() must be an instance of Zend_Db_Adapter_Abstract, string given

I got this error while I was installing a third party Magento module. Actually, the module was tested for higher Magento version than 1.4 and I had to install that module on Magento version 1.4.
Cause:
In older Magento versions, setConnection() function of Mage_Eav_Model_Entity_Abstract class expects the parameters only on Zend_Db_Adapter_Abstract type.
Whereas, in newer Magento version, setConnection() function of Mage_Eav_Model_Entity_Abstract class expects the parameters to be either Zend_Db_Adapter_Abstract or string type.
Solution:
Your line of code which resulted in this error might be like the one below:               
$this->setConnection('customer_read', 'customer_write');
You have to change it to:
$resource = Mage::getSingleton('core/resource');
$this->setConnection($resource->getConnection('customer_read'), $resource->getConnection('customer_write'));

Magento1.9 show minicart on mouse hover

Add the following jquery in
app/design/frontend/your_theme/default/template/checkout/cart/minicart.phtml
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery('.container').hover(function() {
        jQuery(this).children('#header-cart,.skip-cart').addClass("skip-active");
    }, function() {
        jQuery(this).children('#header-cart,.skip-cart').removeClass("skip-active");
    });        
});
</script>
minicart.phtml
<?php
    $_cartQty = $this->getSummaryCount();
    if(empty($_cartQty)) {
        $_cartQty = 0;
    }
?>
<div class="container">
<a href="#header-cart" class="skip-link skip-cart <?php if($_cartQty <= 0): ?> no-count<?php endif; ?>">
    <span class="icon"></span>
    <span class="label"><?php echo $this->__('Cart'); ?></span>
    <span class="count"><?php echo $_cartQty; ?></span>
</a>

<div id="header-cart" class="block block-cart skip-content">
    <?php echo $this->getChildHtml('minicart_content');?>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery('.container').hover(function() {
        jQuery(this).children('#header-cart,.skip-cart').addClass("skip-active");
    }, function() {
        jQuery(this).children('#header-cart,.skip-cart').removeClass("skip-active");
    });        
});
</script>

Magento:: Display Shopping Cart in Header

Go to app\design\frontend\Your_theme\default\template\page\html\header.phtml
Add the following code inside the header-container div to display total number of items and price in header .
<?php
  $count = $this->helper('checkout/cart')->getSummaryCount();  //get total items in cart
  $total = $this->helper('checkout/cart')->getQuote()->getGrandTotal(); //get total price
  if($count==0)
  {
    echo $this->__('Items: %s',$count);
  }
  if($count==1)
  {
    echo $this->__(' Item: %s',$count);
  }
  if($count>1)
  {
    echo $this->__(' Items: %s',$count);
  }
  echo $this->__(' Total: %s', $this->helper('core')->formatPrice($total, false));
?>

Magento:: How to get cart items total

<?php echo Mage::helper('checkout/cart')->getItemsCount();?> // work in all version

<span class="count">
<?php echo Mage::helper('checkout/cart')->getSummaryCount();?> //magento 1.9
</span>

Friday 2 January 2015

Magento:: Get Store Email Addresses

General Contact:
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_general/name'); 
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_general/email');
Sales Representative:
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_sales/name'); 
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_sales/email');
Customer Support:
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_support/name'); 
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_support/email');
Custom Email 1:
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_custom1/name'); 
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_custom1/email');
Custom Email 2:
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_custom2/name'); 
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_custom2/email');