Saturday, 20 October 2012

How to set featured product in magento

 This tutorial will show you  how to implement a Featured Product in magento.
Step 1: Add a new attribute: (Login to magento Admin area)
Now to add new attribute option from  “Catalog (Top Menu) > Attributes > Manage Attributes > Add New Attribute
Add appropriate values for property mentioned bellow and Save the new attribute.
Attribute Properties
  • Attribute Identifier: featured
  • Scope: Store View
  • Catalog Input Type for Store Owner: Yes/No
  • Unique Value (not shared with other products): No
  • Values Required: No
  • Input Validation for Store Owner: None
  • Apply To: All Product Types
Front End Properties
  • Use in quick search: No
  • Use in advanced search: Yes
  • Comparable on Front-end: No
  • Use In Layered Navigation (Can be used only with catalog input type ‘Dropdown’): No
  • Visible on Catalog Pages on Front-end: Yes
Manage Label/Options
  • Default: Featured Product
  • English: Featured Product
we have added new attribute for featured product.

Step 2: Now we have to add newly created attribute to the attribute set.
Lets  go to  Catalog  > Attributes > Manage Attributes Sets  to add the attribute to the default feature set.  Newly created attribute is visible under the  “Unassigned Attributes”  in right hand side on the screen.  Now select featured attribute and perform Drag and Drop Operation in order to assign the property under “Group” section under  “General” tab. and click on “save attribute set” button.

Step 3:  Lets create the module
Lets say we have installed magento under folder “magento”.  go to the local directory  “app/code/local/” and create directory
Create directory level “FeaturedProduct/Catalog/Block/Product/Featured.php”
view plaincopy to clipboardprint?

    class FeaturedProduct_Catalog_Block_Product_Featured extends Mage_Catalog_Block_Product_Abstract 
    { 
     
    public function getSubCategory($category_id) { 
    $idList = ""; 
    $categories = ''; 
    $layer = Mage::getSingleton('catalog/layer'); 
    $category = Mage::getModel('catalog/category')->load($category_id); 
    $categories = $category->getChildren(); 
    $idList = $categories; 
    $list = explode(",", $categories); 
     
    foreach($list as $ccid) { 
    $cat = Mage::getModel('catalog/category')->load($ccid); 
    if($cat->getChildren()) $idList .= ",".$cat->getChildren(); 
    } 
    return $idList; 
    } 
     
    public function getFeaturedProduct() 
    { 
     
    $storeId = Mage::app()->getStore()->getId(); 
     
    $ccontroller = Mage::app()->getFrontController()->getRequest()->getControllerName(); 
     
    $categoryId = $this->getRequest()->getParam('id', false); 
     
    if($ccontroller == "product") { 
    $productId = $this->getRequest()->getParam('id', false); 
    $cproduct = Mage::getModel('catalog/product')->load($productId); 
     
    $categoryArr = $cproduct->getCategoryIds(); 
    $categoryId = $categoryArr[0]; 
     
    /*Setting the bundle flag here*/ 
    if($cproduct->getTypeId() == 'bundle'){ 
    $bundleFlag = 1; 
    $bundleCategoryId = $categoryArr[0]; 
    } 
    } 
     
    $resource = Mage::getSingleton('core/resource'); 
    $product    = Mage::getModel('catalog/product'); 
    $currentCategory = Mage::getModel('catalog/category')->load($categoryId); 
     
    $isTopCat = 0; 
    $categoryLevel = $currentCategory->getLevel(); 
     
    if($categoryLevel == 2) $isTopCat = 1; 
     
    $csubcats = $currentCategory->getChildren(); 
     
    if(!emptyempty($csubcats) || $ccontroller == "product" ) { 
     
    $subcats = 0; 
    if($categoryLevel >= 2) { 
    $pathArr = explode("/", $currentCategory->getPath()); 
    $subcats = $this->getSubCategory($pathArr[2]); 
    } 
     
    $categoryId = $this->getRequest()->getParam('id', false); 
    $resource = Mage::getSingleton('core/resource'); 
    $read = $resource->getConnection('catalog_read'); 
    $categoryProductTable = $resource->getTableName('catalog/category_product'); 
    $productEntityIntTable = (string)Mage::getConfig()->getTablePrefix() . 'catalog_product_entity_int'; 
    $eavAttributeTable = $resource->getTableName('eav/attribute'); 
     
    if(emptyempty($subcats)) $subcats = '0'; 
     
    //checking for Bundle Product flag here 
    if($bundleFlag == 1){ 
    $subcats = $bundleCategoryId; 
    } 
     
    $select = $read->select() 
    ->from(array('cp'=>$categoryProductTable)) 
    ->join(array('pei'=>$productEntityIntTable), 'pei.entity_id=cp.product_id', array()) 
    ->joinNatural(array('ea'=>$eavAttributeTable)) 
    ->where('cp.category_id IN ('.$subcats.')') 
    ->where('pei.value=1') 
    ->where('ea.attribute_code="featured"'); 
     
    $featuredProductData = $read->fetchAll($select); 
    $i=0; 
    $product=array(); 
    $productid=array(); 
    foreach ($featuredProductData as $row) { 
    $productid[$i] = $row['product_id']; 
    $i++; 
    } 
     
    $productid = array_unique($productid); 
    $i=0; 
    $prodObj = ''; 
    foreach($productid as $id){ 
    if($id != '') { 
    $prodObj = Mage::getModel('catalog/product')->load($id); 
    if($prodObj->getVisibility() == 4 && $prodObj->isSaleable() == 1) { 
    $product[$i] = $prodObj; 
    $i++; 
    } 
    } 
    } 
     
    } else { 
    $product = ''; 
    } 
    return $product; 
     
    } 
     
    } 

Step 4:  Lets create the template file for featured product listing.
Replace keyword “currentTheme” with actual theme bellow.

Go to the directory and create “/app/design/frontend/currentTheme/template/catalog/product/featured.phtml”
view plaincopy to clipboardprint?

    <?php 
    echo $this->__('Featured products'); 
    // Now fetch featured product. 
    $product = $this->getFeaturedProduct(); 
    if($product) { 
    foreach($product as $_product) { 
    echo "Product Name". $_product->getName() . "<BR>"; 
    echo "Product Price".  $this->getPriceHtml($_product) .  "<BR>"; 
    echo "Product short Description" . $_product->getShortDescription() .  "<BR>"; 
    echo "Product Image" .  $this->helper('catalog/image')->init($_product, 'small_image')->resize(200);   . "<BR>"; 
    echo "Product URL" .  $_product->getProductUrl() . "<BR>"; 
    } 
    ?> 

Step 5:  Now add entry to the local.xml file located at app/etc/.  Add following set of lines inside the  global tags.

    <blocks> 
    <catalog> 
    <rewrite> 
    <product_featured>FeaturedProduct_Catalog_Block_Product_Featured</product_featured> 
    </rewrite> 
    </catalog> 
 

How to manually reindex in magento

Reindex data via SSH. 
All Magento data can be reindexed through the Magento Index Management section in the admin panel. However, sometimes the reindexing process times out and does not complete.

Reindex data via magento admin panel.
Easiest way is to login magento admin panel, got o “Systems > Index Management” and select all indexs, action to “Reindex Data” and click on submit button.

Reindex data programmatically in magento
Magento has different 9 different indexes. If you want to refresh all of them then following code will help you.
view plaincopy to clipboardprint?

    for ($i = 0; $i < = 8; $i++) { 
        $process = Mage::getModel('index/process')->load($i); 
        $process->reindexAll(); 
    } 
 

How to get all products of cart magento

Here, I will show you how to get all shopping cart items and total in Magento Shopping Cart.
 - Get products id, name, price, quantity, etc. present in your cart.
- Get number of items in cart and total quantity in cart.
- Get base total price and grand total price of items in cart.

view plaincopy to clipboardprint?

     $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems(); 
     foreach($items as $item) { 
        echo 'Product ID: '.$item->getProductId().'<br>'; 
        echo 'Product Name: '.$item->getName().'<br>'; 
        echo 'Product Sku: '.$item->getSku().'<br>'; 
        echo 'Product Quantity: '.$item->getQty().'<br>'; 
        echo 'Product Price: '.$item->getPrice().'<br>'; 
     
    if ($this->helper('tax')->displayCartPriceInclTax() || $this->helper('tax')->displayCartBothPrices()): 
        $_incl = $this->helper('checkout')->getPriceInclTax($item); 
        echo 'Product Price: '. $this->helper('checkout')->formatPrice($_incl- $item->getWeeeTaxDisposition()); 
    else: 
        echo 'Product Price: '. $magento_style_price = Mage::helper('core')->currency($item->getPrice()); 
    endif; 
       echo "<br>"; 
     } 
     
    // Total items added in cart 
    $totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount(); 
     
    // Total Quantity added in cart 
    $totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty(); 
     
    // Sub Total for item added in cart 
    $subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal(); 
     
    //grand total for for item added in cart 
    $grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal(); 

Magento tutorial for beginners

Magento is an open source eCommerce solution. It comes with a variety of tools, necessarily for building a successful online shop.
There are many tutorials scattered through out the community site for both beginners and advanced users.
Here are some links that beginners can start with:
Magento Knowledge Base - http://www.magentocommerce.com/knowledge-base/all/
Magento Screencasts - http://www.magentocommerce.com/media/screencasts
Magento Wiki - http://www.magentocommerce.com/wiki/index/categories/
Designer’s Guide - http://www.magentocommerce.com/design_guide 

when you have any issue just search in google with your query i.e.

How to install Magento shopping cart?
Learn how to start creating your Magento web store?
How to add new products in Magento?
How to change Magento themes?
How to use Magento CMS options to manage your shop pages?
How to set SSL certificate in Magento?

Thursday, 18 October 2012

How to reindex in magento programmatically

There are different ways we can re-index magento data.

I have created three different examples on how to reindex data.

Example 1: reindex data via magento admin panel.

Easiest way is to login magento admin panel, got o “Systems > Index Management” and select all indexs, action to “Reindex Data” and click on submit button.

Example 2: how to reindex data programmatically in magento?.
Magento has different 9 different indexes. If you want to refresh all of them then following code will help you.
view plaincopy to clipboardprint?

    for ($i = 0; $i < = 8; $i++) { 
        $process = Mage::getModel('index/process')->load($i); 
        $process->reindexAll(); 
    } 

Example 3: Out of the box data reindexing in magento?.
Create a file reindex.php and execute this file on linux command prompt. If you reindex data manually using following script it will resolve the problem like reindex is incomplete or still showing indexing from long time, etc.

PS: Change path for ‘Mage.php’ & “indexer.php” file path in following code according to environment.
view plaincopy to clipboardprint?

    set_time_limit(0); 
    error_reporting(0); 
    require_once '/var/www/html/app/Mage.php'; 
    umask(0); 
     
    $indexer="/var/www/html/shell/indexer.php"; 
     
    if(file_exists($indexer)) 
    { 
                    $idxlist=array("catalog_product_attribute", 
                                   "catalog_product_price", 
                                   "catalog_product_flat", 
                                   "catalog_category_flat", 
                                   "catalog_category_product", 
                                   "catalog_url", 
                                   "catalogsearch_fulltext", 
                                   "cataloginventory_stock"); 
     
     
            //reindex using magento command line 
            foreach($idxlist as $idx) 
            { 
                echo "reindex $idx n "; 
                exec("php /var/www/html/shell/indexer.php --reindex $idx"); 
            } 
     
    } 



How to get attribute value of product in magento

Being a Magento developer its little difficult specially for beginner to get attribute values and labels.  e.g. Options of color or manufacturer or size attribute, etc.
You may also need to find out what are the different options available for color attribute before you add new option pro-grammatically.
Or you may need to add assign the option’s ID to a product. Here’s what you need to do.
Few Qick and Easy Ways, isn’t it! Code is below.

// Lets say $_product is the product object.
$_attributes = Mage::helper('core')->decorateArray($_product->getAllowAttributes());

foreach($_attributes as $_attribute):
// Get Attribute Code
$attCode = $_attribute->getProductAttribute()->getFrontend()->getAttribute()->getAttributeCode();

// Get Attribute Id
$attrId =  $_attribute->getAttributeId();

foreachend;
In following example $product_id is current product, for whom you want to fetch attribute value.

  1. Mage::getModel('catalog/product')->load($product_id)->getAttributeText("size")  
  2.   
  3. // Change the attribute code here.  
  4. $attribute=$product->getResource()->getAttribute("color");  
  5.   
  6. // Checking if the attribute is either select or multiselect type.  
  7. if($attribute->usesSource()){  
  8.   
  9. // Getting all the sources (options) and print as label-value pair  
  10. $options = $attribute->getSource()->getAllOptions(false);  
  11. print_r($options);  
  12. }  
How do i get selected value for a attribute?
The following line will return you the selected value for the attribute. Replace variable $product_id with actual product id.

  1. $attrValue = Mage::getModel('catalog/product')->load($product_id)->getAttributeText('color');  
How to fetch attribute value sort order?
Here is the Qick and Easy hack on how to get attribute value sort positing.
Change value for variables in following code

  1. 1. $CurtAtr  is  current attribute like color, size, etc  
  2. 2. $attrVal is attribute value e.g. size has "small, medium, Large, etc"  
  3.   
  4. $resource = Mage::getSingleton('core/resource');  
  5. $read = $resource->getConnection('catalog_read');  
  6. $read->fetchAll("SELECT ao.sort_order FROM mage_eav_attribute_option_value as aov, mage_eav_attribute_option as ao where value='$attrVal' and aov.option_id = ao.option_id and attribute_id=$CurtAtr limit 1");  

magento configurable product – how to get available values for color attribute?
In following snippet i have fetched color attribute values just change color to other attribute you should be able to get value for other multi select attribute in magento. Bingo !!

  1. $product = $this->getProduct();  
  2. $attrs  = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);  
  3. foreach($attrs as $attr) {  
  4.     if(0 == strcmp("color"$attr['attribute_code'])) {  
  5.         $options    = $attr['values'];  
  6.     foreach($options as $option) {  
  7.         echo $option[];  
  8.     }  
  9.     }  
  10. }