Friday, September 27, 2013

Magento print select query for products

To print select query : app\code\core\mage\catalog\model\resources\collection\abstract.php

Monday, September 23, 2013

Magento - Sort by Date Added

copying app/code/core/Mage/Catalog/Block/Product/List.php into app/code/local and adding some sorting code at the end of its _getProductCollection() method:


 / sort by created_at date or entity_id
if(!isset($_GET['order'])) {
    $this->_productCollection->getSelect()->reset( Zend_Db_Select::ORDER );
    $this->_productCollection->getSelect()->order('e.entity_id desc');
}
return $this->_productCollection;

Friday, September 13, 2013

To show the Name of Brands in magento

<div class="brand">
<?php
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')->setEntityTypeFilter($product->getResource()->getTypeId())->addFieldToFilter('attribute_code', 'manufacturer');
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$manufacturers = $attribute->getSource()->getAllOptions(false);
?>
<ul id="manufacturer_list"><?php foreach ($manufacturers as $manufacturer): ?>
<li><a href="catalogsearch/advanced/result/?manufacturer[]=<?php echo $manufacturer['value'] ?>"><?php echo $manufacturer['label'] ?></a>
</li>
<?php endforeach; ?>   </ul>
</div>

Product Sold quantity display in your view page in magento.

<?php
$sku = nl2br($_product->getSku());
$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToFilter('sku', $sku)
    ->setOrder('ordered_qty', 'desc')
    ->getFirstItem();
$product = $_productCollection;

echo 'Already sold '.(int)$product->ordered_qty;
?>

Showing the Best Seller Product by code..

Step 1: Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it

class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
public function __construct(){
parent::__construct();
$storeId = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'price', 'small_image'))
->setStoreId($storeId)
->addStoreFilter($storeId)
->setOrder('ordered_qty', 'desc'); // most best sellers on top
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products );

$products->setPageSize(3)->setCurPage(1);
$this->setProductCollection($products);
}
}



Step 2: Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it

<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
<h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
<?php if ($i%1!==0): ?>
<tr>
<?php endif ?>
<td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
<?php contentBlock('top') ?>
<div id="cont_<?php echo $i;?>">
<h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
<a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
</a>
<div class="a-center">
<?php if($_product->getRatingSummary()): ?>
<?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
<?php endif; ?>
<?php echo $this->getPriceHtml($_product, true) ?>
<?php if($_product->isSaleable()): ?>
<button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
<div class="clear"></div>
<?php else: ?>
<p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
<div class="clear"></div>
<?php endif; ?>
<ul class="add-to-links">
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
<?php endif; ?>
<?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
<li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
<?php endif; ?>
</ul>
<?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
</div>
</div>
</td>
<?php if ($i%3==0 or $i==$_collectionSize): ?>
</tr>
<?php endif ?>
<?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>


Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}

Update products price and special price with sku-simple script in magento

 I am searching with this topic but all I find the paid extension for bulk product updation of price. so I made a simple script to update the product with special price and price through their respective sku.

<?php
/**
 * @author      MagePsycho <info@magepsycho.com>
 * @website     http://www.magepsycho.com
 * @category    Export / Import
 */
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

set_time_limit(0);
ini_set('memory_limit','1024M');

/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
    return Mage::getSingleton('core/resource')->getConnection($type);
}

function _getTableName($tableName){
    return Mage::getSingleton('core/resource')->getTableName($tableName);
}

function _getAttributeId($attribute_code = 'price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getAttributeId1($attribute_code = 'special_price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id1 = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id1, $attribute_code));
}

function _getEntityTypeId($entity_type_code = 'catalog_product'){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
    return $connection->fetchOne($sql, array($entity_type_code));
}

function _getIdFromSku($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne($sql, array($sku));

}


function _checkIfSkuExists($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    $count      = $connection->fetchOne($sql, array($sku));
    if($count > 0){
        return true;
    }else{
        return false;
    }
}

function _updatePrices($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $newPrice       = $data[1];
 $specialPrice   = $data[2];
    $productId      = _getIdFromSku($sku);
    $attributeId    = _getAttributeId();
 $attributeId1    = _getAttributeId1();

    $sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
                SET  cped.value = ?
            WHERE  cped.attribute_id = ?
            AND cped.entity_id = ?";
$sql1 = "UPDATE " . _getTableName('catalog_product_index_price') . " cpip
                SET  cpip.final_price = ?
            WHERE cpip.entity_id = ?";


    $connection->query($sql, array($newPrice, $attributeId, $productId));
 $connection->query($sql, array($specialPrice, $attributeId1, $productId));
 $connection->query($sql1, array($specialPrice, $productId));

}

/***************** UTILITY FUNCTIONS ********************/

$csv                = new Varien_File_Csv();
$data               = $csv->getData('var/import/prices.csv'); //path to csv
array_shift($data);

$message = '';
$count   = 2;
foreach($data as $_data){
    if(_checkIfSkuExists($_data[0])){
        try{
            _updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[1] . ') of Sku (' . $_data[0] . '). <br />';
_updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[2] . ') of Sku (' . $_data[0] . '). <br />';

        }catch(Exception $e){
            $message .=  $count .'> Error:: While Upating  Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
$message .=  $count .'> Error:: While Upating  Price (' . $_data[2] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
        }
    }else{
        $message .=  $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
    }
    $count++;
}
echo $message;
?>



save this script to your root file and run it...
and for csv your field should be:

sku    price   special_price



The csv save in var/import/prices.csv
Note:- prices.csv is the name of csv file.

Reindexing of Product Flat Data in magento:

You have to truncate all the 'catalog_product_flat_i' table:
where 'i' can be 1,2,3,4,....

In my case there are 3 table so i fire this query to my phpmyadmin:
TRUNCATE `catalog_product_flat_1`;
TRUNCATE `catalog_product_flat_2`;
TRUNCATE `catalog_product_flat_3`;

How to increase page speed in magento:('without merge css and javascript files')

In you htaccess file do chages as:

Uncomment the line
 php_flag zlib.output_compression on
means remove '#' from starting of php_flag zlib.output_compression on.

write these line in your htaccess file

<IfModule mod_expires.c>

# Enable expirations

ExpiresActive On

# Default directive

ExpiresDefault "access plus 1 year"

# My favicon

ExpiresByType image/x-icon "access plus 1 year"

# Images

ExpiresByType image/gif "access plus 1 year"

ExpiresByType image/png "access plus 1 year"

ExpiresByType image/jpg "access plus 1 year"

ExpiresByType image/jpeg "access plus 1 year"

# CSS

ExpiresByType text/css "access 1 year"

# Javascript

ExpiresByType application/javascript "access plus 1 year"

</IfModule>


Uncomment the lines:

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary


means remove '#' from starting of these lines.

How to overwrite magento controller in local directory

For Example you have to overwrite Mage/Contacts/controller/IndexController.php
Step 1: First you have to make a xml in app/etc/modules/ with name CompanyName_NameSpace.xml true local 0.1.0

Step2: You have to create the folders if not exist in local/CompanyName/NameSpace/etc/ local/CompanyName/NameSpace/controllers/ In etc folder you have to create a config.xml file Shweta_Newscontacts In controllers folder copy the Mage/Contacts/controller/IndexController.php file and include the lines: include_once('Mage/Contacts/controllers/IndexController.php'); and change the class name as: class CompanyName_NameSpace_IndexController extends Mage_Core_Controller_Front_Action Now apply changes in the file you wanted. Now also, Magento take local pool file instead of core pool.

customize of label "choose an option" of configurable product in magento

Step 1: Change in catalog/product/view/type/options/configurable.phml getProduct(); $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes()); ?> isSaleable() && count($_attributes)):?>
getAttributeId(); $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId); $_attributeLabel = str_replace(' ','-',strtolower($_attributeInfo->getFrontendLabel())); ?>
decoratedIsLast){?> class="last">
Step 2: js/varien/configurable.js replace line 171 = element.options[0] = new Option(element.config.label, '');

 Step 3: app/design/frontend/default/grayscale/template/catalog/product/view/type/options/configurable.php change this line: 'label' => 'choose a '.$attribute->getLabel(),