HTML/JavaScript

Wednesday, October 23, 2013

Magento Remove Super Attribute from Configurable Product

Sometimes We need to remove the Attribute from already build Configurable product…As it is hard to remove but we can remove from MYSQL Raw Query …which against the Standard but if it is requried we can edit like this
To remove one super product attribute (as they are called) from all configurable products, you could execute this SQL query in the database:
DELETE FROM catalog_product_super_attribute WHERE attribute_id = “attribute ID which should be removed”
The table catalog_product_super_attribute links products to super product attributes. You can add and remove attributes to created configurable products there.

Magento adding Super Attribute to configurable products

Create attribute
  •     Drag it to appropriate attribute set
  •     Go to phpmyadmin, table ‘catalog_eav_attribute’ and look at the last one, note the ‘attribute id’, also note the product id -> go to catalog_product_entity and look for the configurable product you want, and note entity_id -> this is the product_id
  •     Go to catalog_product_super_attribute and insert new record with product_id and attribute_id, note of the product_super_attribute_id
  •     Go to catalog_product_super_attribute_label and insert new record with product_super_attribute_id and the value of your new attribute, like ‘Color’ or ‘Size’ which you used when adding the attribute in the admin
  •     Go back to admin and click the configurable product, you will notice none of your child products is associated to your configurable product.
  •     Click one of the child products, and select appropriate attribute value, you may also change the sku.
  •     Export all child products and add the new attribute and sku values to it, import it back and you are done or you may have to manually change all in the admin without using the dataflow.
Hope this will help you

Magento Log Cleaning

If certain precaution are not taken on time then magento Database could go extremely large.AS most of the low performance of the website is the Data which is not of used but stored in Database……Clearing these out not only saves disk space but can lead to some dramatic speed improvements as well.As Magento has several tables to store log details. These log tables has contain the customer Visited url, compared products, import & export Data flow table.
Magento has this features to clean these logs, but unfortunately this feature is disabled by default, most of the magento users to don’t turn it on.
There are two  ways to clear the log tables.
We can manually clear these log details by MYSQL Query
Enable Log cleaning from admin and set the cron job for that.
1. Manually Clean directly on Table:
i) Directly run this RAW query which will allow to delete the table
TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
Generally log table works in some of the follwoing functionality
catalog_product_view (products recently viewed box)
sendfriend_product
catalog_product_compare_add_product (recently compared products box and compare box)
checkout_cart_add_product
wishlist_add_product (wishlist box not wishlist itself)
wishlist_share .
2) Enable log cleaning in magento:
1. Go to System > Configuration > Advanced > System > Log Cleaning
by default Enable Log Cleaning is disbale make it enable and set the days so that when cron will run in that time it will delete all your log tables
and boom as excpected
Hope this will help you

Wednesday, October 9, 2013

How to show out of stock products to the end of the product list in Magento

First of all overwrite the file

app/code/core/Mage/Catalog/Model/Layer.php

and copy this file to

app/code/local/Mage/Catalog/Model/Layer.php

In function getProductCollection(), Put this code after line #102

<?php
$collection->joinField('inventory_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id','is_in_stock>=0', 'left')->setOrder('inventory_in_stock', 'desc');
?>

How to get currency code in Magento

We know Magento support multiple currency. Use following code given below to check current currency in the Magento site frontend.

To get current currency code

<?php echo $current_currency_code = Mage::app()->getStore()
->getCurrentCurrencyCode(); ?>

If you looking for current currency symbol use :

<?php echo Mage::app()->getLocale()->currency(Mage::app()
->getStore()->getCurrentCurrencyCode())->getSymbol(); ?>

Monday, September 16, 2013

addAttributeToFilter Conditionals In Magento

addAttributeToFilter is a function that can be called on a product collection in Magento. In short, it adds a condition to the WHERE part of the MySQL query used to extract a product collection from the database.
   
$_products = Mage::getModel('catalog/product')->getCollection()
   ->addAttributeToSelect(array('name', 'product_url', 'small_image'))
   ->addAttributeToFilter('sku', array('like' => 'UX%'))
    ->load();

The above code would get a product collection, with each product having it's name, url, price and small image loaded in it's data array. The product collection would be filtered and contain only products that have an SKU starting with UX.
addAttributeToFilter Conditionals

Notice above, I used the LIKE operator? There are many more operators in SQL and addAttributeToFilter will accept them all. I include them below as well as a reference for you. Hopefully this will save you some time.
Equals: eq
$_products->addAttributeToFilter('status', array('eq' => 1));

Not Equals - neq
$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));

Like - like
$_products->addAttributeToFilter('sku', array('like' => 'UX%'));

One thing to note about like is that you can include SQL wildcard characters such as the percent sign.
Not Like - nlike

$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));

In - in
$_products->addAttributeToFilter('id', array('in' => array(1,4,98)));

When using in, the value parameter accepts an array of values.
Not In - nin
$_products->addAttributeToFilter('id', array('nin' => array(1,4,98)));

NULL - null
$_products->addAttributeToFilter('description', 'null');

Not NULL - notnull
$_products->addAttributeToFilter('description', 'notnull');

Greater Than - gt
$_products->addAttributeToFilter('id', array('gt' => 5));

Less Than - lt
$_products->addAttributeToFilter('id', array('lt' => 5));

Greater Than or Equals To- gteq
   
$_products->addAttributeToFilter('id', array('gteq' => 5));

Less Than or Equals To - lteq

$_products->addAttributeToFilter('id', array('lteq' => 5));

addFieldToFilter()
Debugging The SQL Query

There are two ways to debug the query being executed when loading a collection in Magento.
   
// Method 1
Mage::getModel('catalog/product')->getCollection()->load(true);

// Method 2 (Quicker, Recommended)
$collection = Mage::getModel('catalog/product')->getCollection();

echo $collection->getSelect();

Both method 1 and method 2 will print out the query but both will do it in slightly different ways. Method 1 prints the query out as well as loading the products while method 2 will just convert the query object to a string (ie. will print out the SQL). The second method is definitely better as it will be executed much quicker but I include them both here for reference.

Wednesday, September 4, 2013

Filters in Query in Magento

When we are filtering data in Magento, time occurs when we want to fetch result after filters like Not equal, greater than, less than, etc.

The addFieldToFilter method’s second parameter is used for this. It supports an alternate syntax where, instead of passing in a string, you pass in a single element Array.

The key of this array is the type of comparison you want to make. The value associated with that key is the value you want to filter by.

public function testAction()
{
    var_dump(
    (string)
    Mage::getModel('catalog/product')
    ->getCollection()
    ->addFieldToFilter('sku',array('eq'=>'n2610'))
    ->getSelect()
    );        
}

Calling out our filter
   
addFieldToFilter('sku',array('eq'=>'n2610'))

As you can see, the second parameter is a PHP Array. Its key is eq, which stands for equals. The value for this key is n2610, which is the value we’re filtering on

Listed below are all the filters, along with an example of their SQL equivalents.

array("eq"=>'n2610')
WHERE (e.sku = 'n2610')

array("neq"=>'n2610')
WHERE (e.sku != 'n2610')

array("like"=>'n2610')
WHERE (e.sku like 'n2610')

array("nlike"=>'n2610')
WHERE (e.sku not like 'n2610')

array("is"=>'n2610')
WHERE (e.sku is 'n2610')

array("in"=>array('n2610'))
WHERE (e.sku in ('n2610'))

array("nin"=>array('n2610'))
WHERE (e.sku not in ('n2610'))

array("notnull"=>'n2610')
WHERE (e.sku is NOT NULL)

array("null"=>'n2610')
WHERE (e.sku is NULL)

array("gt"=>'n2610')
WHERE (e.sku > 'n2610')

array("lt"=>'n2610')
WHERE (e.sku < 'n2610')

array("gteq"=>'n2610')
WHERE (e.sku >= 'n2610')

array("moreq"=>'n2610') //a weird, second way to do greater than equal
WHERE (e.sku >= 'n2610')

array("lteq"=>'n2610')
WHERE (e.sku <= 'n2610')

array("finset"=>array('n2610'))
WHERE (find_in_set('n2610',e.sku))

array('from'=>'10','to'=>'20')
WHERE e.sku >= '10' and e.sku <= '20'

Tuesday, August 27, 2013

Generate Category Tree Recursively

In this blog we will see how generate a category tree, recursively showing all categories and sub categories.

The code is given below, will explain the code line by line

<?php
$rootcatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function  get_categories($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
           $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  get_categories($children);
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  get_categories($categories); ?>

Explanation of the code step by step:

  $rootcatId= Mage::app()->getStore()->getRootCategoryId();

This function gives return the Root Catalog Id of your current store. Usually the value is 2 but its always better to use this function.

$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);

This function returns all sub categories of the parent category. This function is defined in Mage_Catalog_Model_Category. the definition is

/**
     * Retrieve categories by parent
     *
     * @param int $parent
     * @param int $recursionLevel
     * @param bool $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return mixed
     */
    public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true);

function  get_categories($categories) { //This is the recursive function created and here we pass the a collection of categories.
$array= '<ul>';  //$array is a variable to store all the category detail .
foreach($categories as $category) {
         $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount(); //$count the total no of products in the category
        $array .= '<li>'.'<a href="' . Mage::getUrl($cat->getUrlPath()). '">' . $category->getName() . "(".$count.")</a>\n"; //In this line we get an a link for the product and product count of that category
        if($category->hasChildren()) {  if category has children or not. If yes then it proceed in inside loop.
             $children = Mage::getModel('catalog/category')->getCategories($category-> getId()); // $children get a list of all subcategories
            $array .=  get_categories($children); //recursive call the get_categories function again.
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  get_categories($categories); //echo all categories in the website, with number of products

You can use your own css and javascript to design the html generated.
- See more at: http://excellencetechnologies.co.in/Telephonia/blog/magento-generate-category-tree-recursively/#sthash.vDwZfAn4.dpuf

Magento: How to get most viewed products?

Here, I will show you the code to get the most viewed products in Magento. The function addViewsCount() filters the products with their views count.

Here is the code:-

Get overall Most viewed products
public function getMostViewedProducts()
{     
    /**
     * Number of products to display
     * You may change it to your desired value
     */
    $productCount = 5;
    
    /**
     * Get Store ID
     */
    $storeId    = Mage::app()->getStore()->getId();     
    
    /**
     * Get most viewed product collection
     */
    $products = Mage::getResourceModel('reports/product_collection')
        ->addAttributeToSelect('*')    
        ->setStoreId($storeId)
        ->addStoreFilter($storeId)
        ->addViewsCount()
        ->setPageSize($productCount);
    
    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);
    
    return $products;
}

Get Most viewed products for current category
public function getMostViewedProducts()

    // number of products to display
    $productCount = 5;
    
    // store ID
    $storeId    = Mage::app()->getStore()->getId();     
    
    // get most viewed products for current category
    $products = Mage::getResourceModel('reports/product_collection')
        ->addAttributeToSelect('*')    
        ->setStoreId($storeId)
        ->addStoreFilter($storeId)
        ->addViewsCount()
        ->addCategoryFilter(Mage::registry('current_category'))
        ->setPageSize($productCount);
    
    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);
    
    return $products;
}

Get Most viewed products for last 30 days
public function getMostViewedProducts()

    // number of products to display
    $productCount = 5;
    
    // store ID
    $storeId    = Mage::app()->getStore()->getId();
    
    // get today and last 30 days time
    $today = time();
    $last = $today - (60*60*24*30);

    $from = date("Y-m-d", $last);
    $to = date("Y-m-d", $today);
    
    // get most viewed products for last 30 days
    $products = Mage::getResourceModel('reports/product_collection')
        ->addAttributeToSelect('*')    
        ->setStoreId($storeId)
        ->addStoreFilter($storeId)
        ->addViewsCount()
        ->addViewsCount($from, $to)
        ->setPageSize($productCount);
    
    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);
    
    return $products;
}

Hope this helps and thanks for reading.
- See more at: http://blog.chapagain.com.np/magento-how-to-get-most-viewed-products/#sthash.s6biTMMA.dpuf

Ways to Enable or Add Custom Breadcrumbs in Magento

There are some pages in Magento with no breadcrumbs enabled by default. In order to enable it, for example, on the checkout page, open checkout.xml file stored in 'layout' folder of the current theme, and find there 'checkout_onepage_index' block.  Then add to the block this code:
   
<reference name="breadcrumbs">
            <action method="addCrumb">
                <crumbName>Home</crumbName>
                <crumbInfo>
                    <label>Home</label>
                    <title>Home</title>
                    <link>/home</link>
                </crumbInfo>
            </action>
            <action method="addCrumb">
                <crumbName>Cart</crumbName>
                <crumbInfo>
                    <label>Cart</label>
                    <title>Cart</title>
                </crumbInfo>
            </action>
        </reference>

If the modified store is multilingual add into the opening tag of the block <translate="label">, here's the example:
   
< checkout_onepage_index translate="label">

The content of 'label' tag and proper translation should be added to mage_checkout.csv file.

The above described example illustrates how to show breadcrumbs with the help of xml, but it is possible to do it directly in the code of the phtml files. With the help of the line (see the example below) it is possible to enable breadcrumbs and show it on a certain page:
   
echo $this->getLayout()->getBlock('breadcrumbs')->toHtml();

This example describes a simple method how to add custom breadcrumbs:

// get breadcrumbs block
$breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
// add first item with link
$breadcrumbs->addCrumb(
'home',
 array(
'label'=>$this->__('Home'),
'title'=>$this->__('Home'),
'link'=>Mage::getBaseUrl()
)
);
// add second item without link
$breadcrumbs->addCrumb(
'brands',
 array(
'label'=>$this->__('Brands'),
'title'=>$this->__('Brands')
)
);
echo $breadcrumbs->toHtml();

The advantage of this method is that you can dynamically modify breadcrumbs (if it's necessary).

Creating Recursive Menu in Magento

In order to create the menu a function need to be added. The function that will receive the ID of the parent (main) categories as an argument and will be displaying child categories. Also the function should check presence of the sub-categories each time a child category is called. 

Here's the example of the 'recursive' function:
   
<?php
$rootСatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootСatId);
function  get_categories($categories) {
    $tree= '<ul>';
    foreach($categories as $category) {
        $cat = Mage::getModel('catalog/category')->load($category->getId());
        $tree .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
            $category->getName() . "(" . $cat->getProductCount(). ")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $tree .=  get_categories($children);
            }
         $tree .= '</li>';
    }
    return  $tree . '</ul>';
}
echo  get_categories($categories); ?>



To get the parent category ID and all its child categories, use this script:
   
$rootСatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootСatId);



In function: get_categories the list of the categories' links, the titles and products quantities in each of it, is formed.



Then the presence of the sub-categories should be checked. If there are some we should call function: get_categories with the current category ID as a parameter.
   
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')
->getCategories($category->getId());
$tree .=  get_categories($children);
     }

This circle could be repeated many times until the full list of the categories is formed.  And that's it.

Magento Layered Navigation in Drop-Down

Magento Layered Navigation in Drop-Down

It is very simple.
We just need to replace the contents of file
/app/design/frontend/default/your-magento-template/template/catalog/layer/filter.phtml
with

<select onchange="setLocation(this.value)">
  <option value=""><?php echo 'Choose an Option...' ?></option>
<?php foreach ($this->getItems() as $_item): ?>
    <option
        <?php if ($_item->getCount() > 0): ?>
        value="<?php echo $this->urlEscape($_item->getUrl()) ?>">
<?php echo $_item->getLabel() ?>
        <?php else: echo '>' . $_item->getLabel() ?>
        <?php endif; ?>
        (<?php echo $_item->getCount() ?>)
    </option>
<?php endforeach ?>
</select>

Magento : Category Flat Data index error

When reindexing "Category Flat Data " gives error
Cannot initialize the indexer process.
 I run the below query and the issue resolved.

ALTER TABLE catalog_category_entity ENGINE=INNODB;
ALTER TABLE core_store ENGINE=INNODB;
:)

Getting Configurable Product from Simple Product ID in Magento 1.5+

<?php
$simpleProductId = 465;
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
->getParentIdsByChild($simpleProductId);
$product = Mage::getModel('catalog/product')->load($parentIds[0]);
echo $product->getId(); // ID = 462 (aka, Parent of 465)
?>

Monday, August 26, 2013

Magento: Difference between order states and statuses

If you are building website in Magento, you may have noticed that there are two columns insales_flat_order table which are confusing. These are state and status. You might think what is the difference between these two, both having same meaning.
Well, this is not the case. They both are different. State is used by magento to tell if the order is new, processing, complete, holded, closed, canceled, etc.; while Statuses are the one that YOU would be defining at the backend in System -> Order Statuses. Magento displays order STATUSES and not STATES in the backend order detail page to let you know which status is assigned as per your mapping. Remember, multiple statuses can be mapped with one state, while vice versa is not possible.
Consider an example, your customer places an order as Cash on Delivery, you will need something like COD_Pending as the order status so that you know it is not yet paid. Magento will have state new for this, which makes you unpredictable of what kind of transaction is this, COD or Prepaid. The STATUS can be anything, as you define, for your understanding; while STATE is something which Magento needs to understand, internally.
In short, Magento uses order state internally for processing order, whereas order status are used by store owners to understand the exact order flow where one state can be assigned to multiple statuses.
To understand this in detail, have a look at this
Hope it helps!

Social media buttons

//linked in like button
http://developer.linkedin.com/plugins/share-button

//twitter tweet button
https://twitter.com/about/resources/buttons#tweet
https://dev.twitter.com/docs/tweet-button

//facebook like button
http://developers.facebook.com/docs/reference/plugins/like/

//google +1 button
http://www.google.com/intl/en/webmasters/+1/button/index.html

Magento : Add custom image attribute to category

Magento : Add custom image attribute to category

Just copy paste the below code in header.phtml and run yourmagento once, your attribute will be created and you can see in backend under manage category. After you are done remove this code again.

 ------------------------------------------------------------------------------------------
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$setup->addAttribute('catalog_category', 'sliderimage', array(
    'group'         => 'General',
    'input'         => 'image',
    'type'          => 'varchar',
    'label'         => 'Slider Image',
    'backend'       => 'catalog/category_attribute_backend_image',
    'visible'       => 1,
    'required'        => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

Magento : Product list page wrong sorting by price

Magento : Product list page wrong sorting by price

When we install webtex_customergroupprice it has a bug when it sorts products

on product list page it is not correct. For this we need to change collections orderby.

We add

$collection->getSelect()->reset(Zend_Db_Select::ORDER)
->order('(min_price)'.$orderDir);

at the end of the function public function sortByPrice() in file "app/code/local/Webtex/Customer

GroupsPrice/Model/Observer.php".

Refresh Cache and the sorting is perfect.

Enjoy!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Magento : Change page layout from controller

Just you need to replace one line of code in your controller
where you want to change the layout of the page if you are not
able to do from xml through setlayout.

Replace
$this->loadLayout();

with
$this->loadLayout()->getLayout()
->getBlock('root')->setTemplate('page/1column.phtml');

Magento : Change options of configurable product to radio button

Magento : Change options of configurable product to radio button

Replace the configurable.phtml code with below code:
<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
            <div class="input-box">
                <select style="display:none;" name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]"
id="attribute<?php echo $_attribute->getAttributeId() ?>"
 class="required-entry super-attribute-select">
                  
                  </select>
              </div>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
        var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
    </script>
<?php endif;?>
<div id="r"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#attribute<?php echo $_attribute->getAttributeId() ?> option").each(function(i, e) {
    if(jQuery(this).val() == '')
    {}
    else
    {
    jQuery("<input type='radio' name='r' />")
        .attr("value", jQuery(this).val())
        .attr("checked", i == 0)
        .click(function () {
            jQuery("#attribute<?php echo $_attribute->getAttributeId() ?>").val(jQuery(this).val());
        })
        .appendTo("#r");
        jQuery("<span >&nbsp;&nbsp;&nbsp;"+jQuery(this).html()+"&nbsp;&nbsp;&nbsp;</span>")
        .appendTo("#r");
    }
      
});
});


</script>

Delete all products

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

Get Configurable product's Child products

<?php
// input is $_product and result is iterating child products
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
?>

Sunday, August 25, 2013

Clear cache/reindex

<?php
// clear cache
Mage::app()->removeCache('catalog_rules_dirty');
// reindex prices
Mage::getModel('index/process')->load(2)->reindexEverything();
/*
1 = Product Attributes
2 = Product Attributes
3 = Catalog URL Rewrites
4 = Product Flat Data
5 = Category Flat Data
6 = Category Products
7 = Catalog Search Index
8 = Tag Aggregation Data
9 = Stock Status
*/
?>

Get Magento Urls in Phtml Page

Get Base Url :
Mage::getBaseUrl();
Get Store Url : 
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
Get Skin Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
$this->getSkinUrl(‘images/imagename.jpg’);
Get Media Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
Get Js Url : 
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
Get Current Url
Mage::helper(‘core/url’)->getCurrentUrl();
Get Home Url
Mage::helper(‘core/url’)->getHomeUrl();

Changing the Admin URL

Open up the /app/etc/local.xml file, locate the <frontName> tag, and change the ‘admin’ part it to something a lot more random, eg:

<frontName><![CDATA[supersecret-admin-name]]></frontName>

Clear your cache and sessions.

Return Product Attributes

<?php
$_product->getThisattribute();
$_product->getAttributeText('thisattribute');
$_product->getResource()->getAttribute('thisattribute')
->getFrontend()->getValue($_product);
$_product->getData('thisattribute');
// The following returns the option IDs for an
//attribute that is a multiple-select field:

$_product->getData('color'); // i.e. 456,499
// The following returns the attribute object,
//and instance of Mage_Catalog_Model_Resource_Eav_Attribute:

$_product->getResource()->getAttribute('color');
// instance of Mage_Catalog_Model_Resource_Eav_Attribute
// The following returns an array of
//the text values for the attribute:

$_product->getAttributeText('color');
// Array([0]=>'red', [1]=>'green')
// The following returns the text for the attribute
if ($attr = $_product->getResource()->getAttribute('color')):
echo $attr->getFrontend()->getValue($_product); 
// will display: red, green
endif;
?>

Is product purchasable?

<?php if($_product->isSaleable()) { // do stuff } ?>

Run Magento Code Externally

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
// Run you code here
?>

Get Simple Products of a Configurable Product

<?php
if($_product->getTypeId() == "configurable") {
$ids = $_product->getTypeInstance()->getUsedProductIds();
?>
<ul>
<?php
foreach ($ids as $id) {
$simpleproduct = Mage::getModel('catalog/product')
->load($id);
?>
<li>
<?php
echo $simpleproduct->getName() . " - " .
(int)Mage::getModel('cataloginventory/stock_item')
->
loadByProduct($simpleproduct)->getQty();
?>
</li>
<?php
}
?>
</ul>
<?php
}
?>

Saturday, August 24, 2013

Create Catalog Price Rule Programmatically in Magento

Here, you will see how to create Catalog Price Rule in Magento through code.

Catalog Rules are applied on products before they are added to the cart.

To create a Catalog Price Rule from Admin Panel, we go to Promotions -> Catalog Price Rules and select Add New Rule.

Basically, there are three main parts for Catalog Price Rule, i.e. Rule Information, Conditions, and Actions.

Here is the code to create Catalog Price Rule. In this code example, I have created Catalog Price Rule with the following information:-

- The rule is applied to particular product with the particular SKU (in our case: ‘chair’)
- The rule is applied as Fixed Amount Discount To certain amount (in our case: 20) of currency amount

$name = "My Catalog Price Rule"; // name of Catalog Price Rule
$websiteId = 1;
$customerGroupId = 2;
$actionType = 'to_fixed'; // discount to fixed amount
//(other options are: by_fixed, by_percent, to_percent)
$discount = 20; // discount amount
$sku = 'chair'; // product sku

$catalogPriceRule = Mage::getModel('catalogrule/rule');

$catalogPriceRule->setName($name)
                 ->setDescription('')
                 ->setIsActive(1)
                 ->setWebsiteIds(array($websiteId))
                 ->setCustomerGroupIds(array($customerGroupId))
                 ->setFromDate('')
                 ->setToDate('')
                 ->setSortOrder('')
                 ->setSimpleAction($actionType)
                 ->setDiscountAmount($discount)
                 ->setStopRulesProcessing(0);

$skuCondition = Mage::getModel('catalogrule/rule_condition_product')
                    ->setType('catalogrule/rule_condition_product')
                    ->setAttribute('sku')
                    ->setOperator('==')
                    ->setValue($sku);

try {
    $catalogPriceRule->getConditions()->addCondition($skuCondition);
    $catalogPriceRule->save();
    $catalogPriceRule->applyAll();
} catch (Exception $e) {
    Mage::getSingleton('core/session')->addError(Mage::helper('catalog')
->__($e->getMessage()));
    return;
}

A new Catalog Price Rule with the name “My Catalog Price Rule” has been created. You can view the rule from Promotions -> Catalog Price Rules in admin.

Get methods of an object

First, use get_class to get the name of an object's class.

<?php $class_name = get_class($object); ?>

Then, pass that get_class_methods to get a list of all the callable methods on an object

<?php
$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
{
var_dump($method);
}
?>

Get associated products

In /app/design/frontend/default/site/template/catalog/product/view/type/

<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_associatedProducts = $this->getAllowProducts() ?>
<?php //var_dump($_associatedProducts); ?>
<br />
<br />
<?php if (count($_associatedProducts)): ?>
    <?php foreach ($_associatedProducts as $_item): ?>
        <a href="<?php echo $_item->getProductUrl() ?>"><?php echo $_helper->productAttribute($_item, $_item->getName(), 'name') ?> |
<?php echo $_item->getName() ?> |
<?php echo $_item->getPrice() ?></a>
        <br />
        <br />
    <?php endforeach; ?>
<?php endif; ?>

Get the current category/product/cms page

<?php
$currentCategory = Mage::registry('current_category');
$currentProduct = Mage::registry('current_product');
$currentCmsPage = Mage::registry('cms_page');
?>

How to delete a quote in Magento

Use the code below to delete a quote:


<?php
$quoteID = Mage::getSingleton("checkout/session")
->getQuote()->getId();

if($quoteID)
{
try {
$quote = Mage::getModel("sales/quote")->load($quoteID);
$quote->setIsActive(false);
$quote->delete();

return "cart deleted";
} catch(Exception $e) {
return $e->getMessage();
}
}else{
return "no quote found";
}

Cart Data

<?php
$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
print_r($cart);
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
print_r($cart);
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) {
echo $item->getName();
Zend_Debug::dump($item->debug());
}
?>

Friday, August 23, 2013

Turn template hints on/off via database

UPDATE
`core_config_data`
SET
`value` = 0
WHERE
`path` = "dev/debug/template_hints"
OR
`path` = "dev/debug/template_hints_blocks";

How to get shipping and handling cost, tax, discount in magento on shopping cart page

We can simply use the following code
// To get the shipping and handling charge on shopping cart page
Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingAmount();
 // To get discount and tax  on shopping cart page
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
 // To get the discount
if(isset($totals['discount']) && $totals['discount']->getValue()) {
echo 'Discount :'. $discount = $totals['discount']->getValue(); //Discount value if applied
} else {
$discount = '';
}
 // To get tax
if(isset($totals['tax']) && $totals['tax']->getValue()) {
echo 'Tax :'.$tax = $totals['tax']->getValue(); //Tax value if present
} else {
$tax = '';
}

How to Override controller in magento / Override controller’s action in magento

Requirement : Some times you may run into situation where you want to override the core functionality of Magento core controllers. So in this case, The best practise is override the controller then override actions or add new actions for custom requirement.

For example you want to override OnepageController.php file and overwride indexAction.

In this example my custom module name space is “MyBlog” and i am going to overwride indexAction Mage_Checkout_OnepageController

Base File Path : app/code/core/Mage/Checkout/controllers/OnepageController.php

To Do the same we have to follow bellow steps.

Step1: We need to create a custom module

File Path : app/etc/modules/

File Name: MyBlog_Checkout.xml

File Content:

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

Step2: Now we have to create bellow files in our custom module

File Path: app/code/local/MyBlog/Checkout/etc/config.xml

Bellow is content for config.xml file

<?xml version="1.0"?>
<config>
     <modules>
       <MyBlog_Checkout>
         <version>0.0.1</version>
       </MyBlog_Checkout>
     </modules>

    <frontend>
        <routers>
            <checkout>
                <args>
                    <modules>
                        <MyBlog_Checkout before="Mage_Checkout">MyBlog_Checkout</MyBlog_Checkout>
                    </modules>
                </args>
            </checkout>
        </routers>
    </frontend>
</config>

Bellow is content for OnepageController.php

File Path : app/code/local/MyBlog/Checkout/controllers/OnepageController.php

<?php

require_once 'Mage/Checkout/controllers/OnepageController.php';
class MyBlog_Checkout_OnepageController extends Mage_Checkout_OnepageController {

     public function indexAction()
    {
        echo "Great! You are in MyBlog checkout controller section";
        exit;
    }

}
?>

How to Add related products in Magento by code / script

To create the related product programmatically in Magento

<?php
set_time_limit(0);
ini_set(‘memory_limit’,’1024M’);
require_once ‘../../app/Mage.php’;
Mage::app();

$sku=’12345’;  //some Sku
$product = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’,$sku);

if($product){
$sRelatedProducts = "123456,123";
$aRelatedProducts = explode(‘,’, $sRelatedProducts);  // or other way to get the array of related product sku

$aParams = array();
$nRelatedCounter = 1;
$aProduct    = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sku);
$aMainProduct = Mage::getModel(‘catalog/product’);
$aMainProduct->load($aProduct['entity_id']);

foreach($aRelatedProducts as $sSku)
{
$aRelatedProduct = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sSku);

$aParams[$aRelatedProduct['entity_id']] = array(
‘position’     => $nRelatedCounter
);

$nRelatedCounter++;
}

$product->setRelatedLinkData($aParams);
$product->save();
}

echo “Great!!”;

?>

How to call category list in footer in magento

<?php $helper = $this->helper('catalog/category') ?>

<?php foreach ($helper->getStoreCategories() as $_category): ?>
<a href="<?php echo Mage::getModel('catalog/category')                                                                                                                                                                                                                                                                                            ->setData($_category->getData())->getUrl(); ?>" title="<?php echo $_category->getName() ?>">   <?php echo $_category->getName() ?></a>
<?php endforeach ?>

Create a Country Drop Down in the Magento Admin

<?php
$fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel
(
'adminhtml/system_config_source_country')
->toOptionArray(),
));
?>

Get An Array of Country Names/Codes in Magento

<?php
$countryList = Mage::getResourceModel 
                ('directory/country_collection')
->loadData()
->toOptionArray(false);

echo '<pre>';
print_r( $countryList);
exit('</pre>');
?>

Create a Country Drop Down in the Frontend of Magento

<?php
$_countries=
 Mage::getResourceModel('directory/country_collection')
                                    ->loadData()
                                    ->toOptionArray(false) ?>
<?php if (count($_countries) > 0): ?>
    <select name="country" id="country">
        <option value="">-- Please Select --</option>
        <?php foreach($_countries as $_country): ?>
            <option value="<?php echo $_country['value'] ?>">
                <?php echo $_country['label'] ?>
            </option>
        <?php endforeach; ?>
    </select>
<?php endif; ?>

Category Navigation Listings in Magento

<div id="leftnav">
<?php $helper = $this->helper('catalog/category') ?>
<?php $categories = $this->getStoreCategories() ?>
<?php if (count($categories) > 0): ?>
<ul id="leftnav-tree" class="level0">
<?php foreach($categories as $category): ?>
<li class="level0<?php if ($this->isCategoryActive($category)): ?>
active<?php endif; ?>">
<a href="<?php echo $helper->getCategoryUrl($category) ?>">
<span>
<?php echo $this->escapeHtml($category->getName()) ?>
</span>
 </a>
 <?php if ($this->isCategoryActive($category)): ?>
<?php $subcategories = $category->getChildren() ?>
<?php if (count($subcategories) > 0): ?>
<ul id="leftnav-tree-<?php echo $category->getId() ?>"
class="level1">
<?php foreach($subcategories as $subcategory): ?>
<li class="level1
<?php if ($this->isCategoryActive($subcategory)):?>
active<?php endif; ?>">
<a href="<?php echo $helper->getCategoryUrl($subcategory) ?>">
<?php echo $this->escapeHtml(trim($subcategory->getName(),'-'))?>
</a>
</li>
 <?php endforeach; ?>
 </ul>
<script type="text/javascript">decorateList
('leftnav-tree-<?php echo $category->getId() ?>',

'recursive')

</script>
<?php endif; ?>
 <?php endif; ?>
 </li>
<?php endforeach; ?>
</ul>
<script type="text/javascript">
decorateList('leftnav-tree', 'recursive')
</script>
<?php endif; ?>
</div>

Debug using zend

<?php echo Zend_Debug::dump($thing_to_debug, 'debug'); ?>

$_GET, $_POST & $_REQUEST Variables

<?php
// $_GET
$productId = Mage::app()->getRequest()->getParam('product_id');
// The second parameter to getParam allows you to
// set a default value 
//which is returned if the GET value isn't set
$productId =Mage::app()->getRequest()->getParam('product_id',44);
$postData = Mage::app()->getRequest()->getPost();
// You can access individual variables like...
$productId = $postData['product_id']);
?>

Magento: Mass Exclude/Unexclude Images

# Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
# Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

Get The Root Category In Magento

<?php
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$_category = Mage::getModel('catalog/category')
         ->load($rootCategoryId);
// You can then get all of the top level categories using:
$_subcategories = $_category->getChildrenCategories();
?>

Get The Current URL In Magento

<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>

Check if customer is logged in

<?php $logged_in = Mage::getSingleton('customer/session')
->isLoggedIn(); // (boolean) ?>

how to add/update category in magento from csv programmatically

<?php
set_time_limit(0);
ini_set(‘memory_limit’,’1024M’);
require_once ‘../../app/Mage.php’;
Mage::app();

//read data from csv file
$row = 1; $cat_arr = array();
if (($handle = fopen(“category.csv”, “r”)) !== FALSE)
{
while (($data = fgetcsv($handle, 100000, “,”)) !== FALSE)
{
if($row > 1)
{

/* $data[0] is csv column in csv file
$data[1],$data[2],$data[3],$data[4] is category Id column */

$cat_arr[trim($data[0])] = $data[1].”,”.$data[2].”,”.$data[3].”,”.$data[4].”,”.$data[5].”,”.$data[6].”,”.$data[7]; // $data[0] column represent sku

}

$row++;
}
fclose($handle);
}

$products = Mage::getResourceModel(‘catalog/product_collection’);
$i = 1 ;
foreach ( $products as $index => $productModel )
{
$_product = Mage::getModel(‘catalog/product’)->load($productModel->getId());
$cnids = $cat_arr[$_product->getSku()];
$ids = explode(“,”,$cnids);
$_product->setCategoryIds($ids);
$_product->save();
$i++;
}

?>

Get Configurable product's Children's (simple product) custom attributes

<?php
// input is $_product and result is iterating child products
$conf = Mage::getModel('catalog/product_type_configurable')
->setProduct($_product);
$col = $conf->getUsedProductCollection()
->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($col as $simple_product){
var_dump($simple_product->getId());
}
?>

Load category by id

<?php
$_category = Mage::getModel('catalog/category')->load(89);
$_category_url = $_category->getUrl();
?>

Load product by id or sku

<?php
$_product_1 = Mage::getModel('catalog/product')->load(12);
$_product_2 = Mage::getModel('catalog/product')
->
loadByAttribute('sku','cordoba-classic-6-String-guitar');
?>

Load Products by Category ID

<?php
$_category = Mage::getModel('catalog/category')->load(47);
$_productCollection = $_category->getProductCollection();
if($_productCollection->count()) {
foreach( $_productCollection as $_product ):
echo $_product->getProductUrl();
echo $this->getPriceHtml($_product, true);
echo $this->htmlEscape($_product->getName());
endforeach;
}
?>

Update all subscribers into a customer group (e.g. 5)

UPDATE
customer_entity,
newsletter_subscriber
SET
customer_entity.`group_id` = 5
WHERE
customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
AND
newsletter_subscriber.`subscriber_status` = 1;

Including jquery to magento

First step is to include j query to your magento website.To achieve this just add a new line add js to your page.xml layout or you can include js in template/page/html/head.phtml .

After this just include jquery.noConfilct to remove conflict between prototype.js and jquery library
For this use following  snippet

var $j = jQuery.noConflict(); 

$j
(document).ready(function(){
    //here you can add your jquery code and jquery
 $ is to be replaced with $j 
   as it is the new replaced variable 
for the jquery script
});

Magento Enable template path hint

To enable magento path hint for your magento website first login into your admin section i.e magento backend now go to System->Configuration->Developer
Inside this you have to Debug option.If the Current Configuration Scope is Default you will be not able to set template path hints for your magento website So change to you website after this change Template Path Hints to yes.

Your Template path hint has been enabled after this you can view template path hint on the frontend of your website if some how due to cache you are not getting the path hint so go to System Cache management flush or refresh the cache are you are ready to go.

Magento new feature for Category manager

Magento 1.5 has come up with anew feature for categories and made category design management a lot more easier now when you click on a category and apply a custom or a new design for a particular category you can extend that design for its sub categories and products by just selecting the use parent category settings and apply to products.

Magento Tutorial : Adding a product

Steps to Follow to add new Product:-
1)      First login into Magento admin section 

2) Now from top menu go to Catalog->Manage Product.

3) To add new Product click on the button Add Product .

4) First Product Setting Page is prompted Now select Attribute Type as Default and and Product type as Simple Product.

5) After proceeding further you will be redirected to Product information page  in the General tab Provide the details
i.e
 Name :- Product Name
SKU :- Unique Sku number product
Weight :- Product weight
Status :- Enable to activate the product
Tax Class:-According to the product 
Visiblity :- Whether product is searchable from web site  default is [catalog/search]
Brands: Select From Drop Down

6)  After that go to price section here provide Price which is required
    Beside this you can also provide cost and
Tier price  which is buy 2 for
Special price for sale price special price you offer in your store

7)In Meta section we can provide meta data about product to make your store seo friendly

8)In Image section We can upload images of product from our local file system and assign distinguished image for small image thumbnail and base image

9)In description section We provide description about the Product which will displayed on the frontend of product view page.

10)Now Go to Inventory Section Provide Details about product stock the qty(availability of product ) and set
Stock Availability:in Stock  if the stock availability is set to out of stock the product will not be available on frontend

11)In Website Section Check the website in which the product will be available now we have only one website we can check  main website to true i.e our website will be available to our main website.

12)After This Click on Categories tab to assign category to the product

 13) To assign Best Suitable Products to a product go to Up-sells tab Search the best suitable product from the grid now assign the product  which suits best with this product.

14)After that we can also provide custom option to the product  For this we have assign size custom option for the jeans we can go to custom options add a new option from custom option assign its Title as size now will also assign its type i.e drop down radio button or check-box we can assign different price list for different  product options.