Monday, October 17, 2011

"Image type and information need to be specified for each store view" Product Image upload problem in magento 1.6


Solution:

Install magento dull image uploader / No flash image uploader extension (Here). This will help to import images.

That’s all, go to admin panel in Magento admin panel and upload and import product successfully.

How to get products available stock quantity in magento?

Here is the code to get produts stock quantity. Place this code in your view.phtml file.
echo $qtyStock = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();

Thursday, October 6, 2011

How to remove validation on zip code in magento checkout page?

Login to your your magento admin panel then go to System -> Configuration->General. From Country option tab you can see there is an option "Postal code is optional for the following countries" Select the country which you want to Optional/Not validate . then click on save config to save your settings.



That's it you are done.

Tips to use home page url, custom page url and pass query string in Magento CMS Page

{{store url=""}} -> Used to get Store's home page URL.
Resulting in a URL like "http://yourstore.com/"

{{store url="contacts"}} -> Used to get contact us page URL.
Resulting in a URL like "http://yourstore.com/contacts/"

If you want to show custom URL Use direct_url
{{store direct_url="category/subcategory.html"}} -> Used to get custom URL.
Resulting in a URL like "http://yourstore.com/category/subcategory.html"

If you want to pass parameters in query string use _query
{{store direct_url="category/subcategory.html" _query="a=param_a&b=param_b"}} -> Used to Pass query string
Resulting in a URL like "http://yourstore.com/category/subcategory.html?a=param_a&b=param_b"

{{skin url='images/homepageimage.jpg'}} -> Used to get image url

Wednesday, October 5, 2011

How to prevent not logged in users from accessing magento site and force customer to login?

Step 1:
Create and put below content to the file named "redirect.phtml" and place under "/template/page/html/".
Mage::getSingleton('customer/session')->setBeforeAuthUrl($this->getRequest()->getRequestUri());  //save requested URL for later redirection
if(!Mage::getSingleton('customer/session')->isLoggedIn()) {  // if not logged in
    header("Status: 301");
    header('Location: '.$this->getUrl('customer/account/login')) ;  // send to the login page
    exit; 
} 
Step 2:
Edit "page.xml" and place the code

after

Step 3:
Edit the below files "template/page/"
1. 1column.phtml
2. 2columns-left.phtml
3. 2columns-right.phtml
4. 3columns.phtml

and Insert the following line at the start of all the files.
echo $this->getChildHtml('auth-redirect')
Step 4:
Now Add exceptions for home, login and cms page.
Edit your "layout/customer.xml"
Add below code
<remove name="auth-redirect" />
under
<customer_account_login>
Also If you want users to be able to create an account, another good one to make public might be place code under
<customer_account_create>
in "layout/customer.xml"
If you want to make the home (front) page public, add the "remove" code to the 

<cms_index_index>
That's it you are done.

Export Magento categories with ID using php script

Copy the code below into a new file "categorywithid.php" and place this file in your root folder
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();

$category = Mage::getModel ( 'catalog/category' );
$tree = $category->getTreeModel ();
$tree->load ();

$ids = $tree->getCollection ()->getAllIds ();

if ($ids) {
 $file = "var/export/catwithid.csv";
 file_put_contents($file,"catId, catName\n");
 foreach ( $ids as $id ) {
   $string = $id . ', ' .$category->load($id)->getName() . "\n";
  file_put_contents($file,$string,FILE_APPEND);
 }
}
Hit Your browser like www.YourDomain.com/categorywithid.php Thats it. You are done. Get the csv file under "var/export/catwithid.csv".

Mass Products Stock levels Update in Magento

Step 1:
Create a CSV with a minimum of 3 columns, the SKU, qty and is_in_stock.
Then save it to "/app/var/import/updateStockLevels.csv".
For instance, we will use,
"sku","qty","is_in_stock"
"prod1","100","1"

Step 2:
Copy the code below into a new file "updateStock.php" and place this file in your root folder
define('MAGENTO', realpath(dirname(__FILE__)));
 require_once MAGENTO . '/app/Mage.php';
 umask(0); $count = 0;
 Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
 
 $file = fopen(MAGENTO . '/var/import/updateStockLevels.csv', 'r');
 while (($line = fgetcsv($file)) !== FALSE) {
   if ($count == 0) {
   foreach ($line as $key=>$value) {
   $cols[$value] = $key;
   }
 }
 
 $count++;
 if ($count == 1) continue;
 
 #Convert the lines to cols
 if ($count > 0) {
   foreach($cols as $col=>$value) {
   unset(${$col});
   ${$col} = $line[$value];
   }
 }
 
 // Check if SKU exists
 $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
 if ( $product ) {
   $productId = $product->getId();
   $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
   $stockItemId = $stockItem->getId();
   $stock = array();
   if (!$stockItemId) {
     $stockItem->setData('product_id', $product->getId());
     $stockItem->setData('stock_id', 1);
     } else {
       $stock = $stockItem->getData();
   }
 
   foreach($cols as $col=>$value) {
   $stock[$col] = $line[$value];
   }
 
   foreach($stock as $field => $value) {
   $stockItem->setData($field, $value?$value:0);
   }
 
 $stockItem->save();
 unset($stockItem); unset($product);
 }
 echo "
Stock updated $sku"; 
}
 fclose($file);

Step 3:
Run the php script in  Your browser like "www.YourDomain.com/updateStock.php".
Thats it. You are done.

How to remove right column sidebar from product view page in Magento?

Edit your theme's "/layout/catalog.xml" file. Find the below lines.

  
      
        
      
You can set your template to 1column like this:
 
or use "<remove name="right"/>" code to remove right sidebar.


  
  
    
      
        
      
After making changes dont forget to refresh the cache. That's it. You are done.

How to remove the Discount Code / Coupon Code box in Magento My cart page?

Solution 1:
Edit your theme's "/layout/checkout.xml" file. Find and Comment the below lines.

Solution 2:
Add new local.xml file under your theme's layout folder.

   
      
   
 
Here, You no need to search for any template or layout file. This code will do the trick. After making changes dont forget to refresh the cache. That's it. You are done.

How to remove the Estimate Shipping and Tax box in Magento My cart page?

Solution 1:
Edit your theme's "/layout/checkout.xml" file. Find and Comment the below lines.

Solution 2:
Add new "local.xml" file under your theme's layout folder.

   
      
   
 
Here, You no need to search for any template or layout file. This code will do the trick. After making changes dont forget to refresh the cache. That's it. You are done.

How to Remove Add to Compare link in magento product view page?

Edit your theme's "templae/catalog/product/view/addto.phtml" file. Find and Comment the below lines.
<?php
    $_compareUrl = $this->helper('catalog/product_compare')->getAddUrl($_product);
?>
<?php if($_compareUrl) : ?>
    <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
<?php endif; ?> 

Move or Remove Callouts on the left or right sidebar in magento

Edit your theme's "/layout/catalog.xml" file. Fine the below lines.


    

        images/media/col_left_callout.jpg

        Our customer service is available 24/7. Call us at (555) 555-0123.

        checkout/cart

    


If you want to remove callout from left sidebar just comment those lines. Suppose you want to show that callout in your right sidebar just change reference name="left" to reference name="right". Likewise you can do it for right sidebar callout.
Remove Your cache and check. Thats it you are done.

How to enable template path hints in magento admin panel?

1. Admin > System > Configuration
2. Switch your "Current Configuration Scope" to your store (’Main Website’ on a stock build)
3. Click on the Developer Tab (bottom left) and find the Debug area
4. Template Path Hints: Yes (also might want to add Block Names to hints)

How to remove a block from just one page cart, cms or product page?

For page specific layout updates, either you can use backend layout updates sections(category, product, cms pages) or the following code in the "app/etc/local.xml"

    

for instance, use this code to remove the sidebar cart from the product view page.

     

How to remove parent category path from sub category in magento URL?

Step 1:
Edit "/app/code/core/Mage/Catalog/Model/Url.php"
Around line 805 comment the below lines:
//if (null === $parentPath) {
//    $parentPath = $this->getResource()->getCategoryParentPath($category);
//}
//elseif ($parentPath == '/') {
    $parentPath = '';
//}
Step 2:
Now re-index Catalog URL Rewrites in Index Management. That's it you are done.

Wednesday, September 28, 2011

How to show only first name in magento welcome message?

Comment the welcome message code in "template/page/html/header.phtml" and Use the below code to show first name only.
$customer = Mage::getSingleton('customer/session')->getCustomer()->getData();
if(Mage::getSingleton('customer/session')->isLoggedIn()){
   echo $this->__('Welcome, %s!', $customer['firstname']);
}else{
   echo $this->__('Welcome Guest');
}

Thursday, September 22, 2011

How to find magento version?

There are two ways to see what version of magento you’re using.

Method 1:
Login to the admin for Magento:
http://www.yourdomain.com/admin/
...and look in the footer, you should see the following:
Magento ver. X.X.X
Where X.X.X is the version number.

Method 2:
If you only have access to the source code, Use the below code.
echo Mage::getVersion();
print_r(Mage::getVersionInfo());

How to Enable template path hints for Magento Admin Panel?

When developing a new Magento Admin theme, one of the tools that will make your life easier is the template path hints. One thing this feature is missing, is the ability to show the template path hints on the admin panel. Whether you’re working on a custom admin theme or module or you’re just curious about what’s under the hood, being able the enable the hints in the admin would be a cool feature. Here is the easy way to accomplish this:

Run the following query to enable the hints:
INSERT INTO core_config_data SET scope = 'default', scope_id = 0,
            path = 'dev/debug/template_hints', value = 1;
INSERT INTO core_config_data SET scope = 'default', scope_id = 0,
            path = 'dev/debug/template_hints_blocks', value = 1;
Clear the config cache, Thats it. You have template path hints in the admin. To disable run a sql query to set the value to 0.

Tuesday, September 20, 2011

How to remove an item from magento shopping cart automatically?

$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
    if ($item->getProduct()->getId() == $productId) {
        $itemId = $item->getItemId();
        $cartHelper->getCart()->removeItem($itemId)->save();
        break;
    }
} 
Note:
The ItemId (ID of an item in the cart) is not the same as the ProductId of the product it represents. Try iterating through the items in the cart until you find the one with the ProductId you want to remove.

How to Add a custom State / Province / Region to a Country in magento?

If you need to add a custom State / Province / Region to a Country in Magento, you’ll need to modify the database manually as there currently isn’t a means to do this from within the Magento admin. Fortunately it’s pretty simple – there are 2 tables involved: directory_country_region and directory_country_region_name.

Adding a record to directory_country_region for a specified country_id will make that new entry show up in the State/Province drop box on the address forms. It will also make that a required field, so you need to make sure you add all the possible options.

You then need to add a corresponding record to directory_country_region_name, using the region_id generated when you inserted into directory_country_region. This entry will make the new region show up when a whole address is displayed on the screen or email, e.g. in an order summary.

Example: Add Tamil Nadu to India

So let’s say that like me, you live in India and want to add 2 regions: Tamil Nadu and Kerala. The country id for India is IN, the region code is a unique identifier so I’m going with Tamil Nadu and at the moment I’m only interested in the en_US locale.

First I will insert Tamil Nadu into directory_country_region as follows:
INSERT INTO `directory_country_region`
(`region_id`,`country_id`,`code`,`default_name`)
VALUES (NULL,'IN','TAMIL','Tamil Nadu');
Note the NULL entry for the region_id field which will auto_increment. I need to find out this new region_id for my next insert so I can either browse the table manually, or this query will do the trick:
SELECT * FROM `directory_country_region`
WHERE `country_id`='IN' AND`code`='TAMIL' AND `default_name`='Tamil Nadu';
In my case, the new region_id is 485, so with that I’ll now insert into directory_country_region_name as follows:
INSERT INTO `directory_country_region_name`
(`locale`,`region_id`,`name`)
VALUES ('en_US','485','Tamil Nadu');
Now I just repeat those steps for Kerala and I’m all set.

Got fatal error when i enabling compilation in magento

Open your "root/includes/config.php" file.
Comment the below line using '#' symbol.
define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
Thats it. Refresh the cache and check now.

How to add CSS and JS files in magento header?

Open your page.xml file and add the below lines
skin_csscss/YOURCSSFILENAME.css
skin_jsjs/YOURJSFILENAME.js
Refresh your cache. Thats it. You are done.

Maximum execution time of 30 seconds exceeded

To fix it, open your php.ini and replace the value for 'max_execution_time' and 'max_input_time' as per below.
max_execution_time = 3600
max_input_time = 3600

How to hide shopping cart sidebar when it is empty?

Displaying the shopping cart when the user has nothing in it is not necessary. To hide the cart in the sidebar, try the following steps.
Step 1: Edit your "/template/checkout/cart/sidebar.phtml" and look for line
<div class="box base-mini mini-cart"> 
Step 2: Add these lines before the opening div tag
<?php $_cartQty1 = $this->getSummaryCount() ?>
<?php if ($_cartQty1 >0): ?>
Step 3: Add this line to the bottom of the file
<?php endif ?> 
Thats it. You are done.

Add a custom "add to cart" button on Magento CMS pages

Sometimes you'll want to show your products or introduce it on a CMS page for some reason. If you want to do that it's actually not so complicated, in your cms page editor, just add the following HTML code where you want it to appear in the page.
<button onclick="location.href ='{{config path="web/unsecure/base_url"}}/checkout/cart/add?product=1&qty=1′">Buy It Now</button> 
Save the page and refresh the cache. Now if you open the page in you should be able to see "Buy It Now" button. When clicked it adds 1 product with ID=1 to your shopping cart.
To make it a little more advanced, you can add the quantity of products you want to let the customers add, in that case use this code (example for five products).
<button onclick="location.href ='{{config path="web/unsecure/base_url"}}/checkout/cart/add?product=1&qty=5'">Buy 4 Get 1 Free</button> 

Monday, September 19, 2011

How to get magento admin username, id, email and password?

Here is a quick code to get the admin user’s data (id, username, email, password, etc).
$user = Mage::getSingleton('admin/session')->getData();
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();
Hope this helps. Thanks.

Magento mysql table install, create and upgrade scripts using custom module

Here is the code to create or update magento mysql table. This module helps to create new table.
"app/etc/modules/Company_Track.xml"

  
      
          true
          local
      
  

"app/code/local/Company/Track/etc/config.xml"

   
    
        0.1.0
   


    
       
            
                Company_Track
                Company_Track_Model_Mysql4_Setup
                
  
                    core_setup
                
        
    



"app/code/local/Company/Track/Model/Mysql/Setup.php"
class Company_Track_Model_Mysql4_Setup extends Mage_Catalog_Model_Resource_Eav_Mysql4_Setup
{
}
Here is the code to create table query.
"app/code/local/Company/Track/sql/track_setup/mysql4-install-0.1.0.php"
$installer = $this;
 
$installer->startSetup();
 
$installer->run("
 
-- DROP TABLE IF EXISTS {$this->getTable('customer_track')};
CREATE TABLE IF NOT EXISTS {$this->getTable('customer_track')} (
`id` INT UNSIGNED NOT NULL ,
`sku` varchar(64) NOT NULL ,
`customer_id` INT NOT NULL ,
`region` varchar(255) NOT NULL ,
`country_id` char(2) NOT NULL
) ;

"); 
$installer->endSetup();
If you want to update mysql table using update query you have to use the below coding. Here im going to remove last name required option to not required.
"app/code/local/Company/Track/sql/track_setup/mysql4-upgrade-0.1.0-0.1.1.php"
/* @var $eav Mage_Eav_Model_entity_Setup */
$eav = Mage::getModel('eav/entity_setup', 'core_setup');
$eav->updateAttribute('customer_address', 'lastname', 'is_required', false);

How to overwrite / rewrite a store cookie in Magento Mage_Core_Model_App class?

We can not rewrite Mage_Core_Model_App class. The reason is explained here.
Copy your "Mage/Core/Model/App.php" to "app/code/local/Mage/Core/Model/App.php".
Find the function "_checkGetStore($type)"
Replace the below line
if (empty($_GET)) {
    return $this;
}
 */
/**
 * @todo check XML_PATH_STORE_IN_URL
 */
/*if (!isset($_GET['___store'])) {
    return $this;
}

$store = $_GET['___store'];
with
if(!isset($_REQUEST['mystore'])) {
 return $this;
}

$store = $_REQUEST['mystore'];
pass your store code to the url like www.mysite.com?mystore=your_store_code
Thats it you are done.

How to add category and manufacturer dropdown to the magento default search?

Here is the code to add category and manufacturer / brand dropdown to the magento default search. Just replace your "template/catalogsearch/form.mini.phtml" with the below code.
<?php
$category = Mage::getModel('catalog/category');
if(is_object(Mage::registry('current_category'))){
    $current_category_path=Mage::registry('current_category')->getPathIds();
}else{
    $current_category_path = array();
}
$category->load(Mage::app()->getStore()->getRootCategoryId());
$children_string = $category->getChildren();
$children = explode(',',$children_string);
$extra_options='';
foreach($children as $c){
    $selected = (in_array($c, $current_category_path))?'SELECTED':'';
    $extra_options.= '<option $selected . value="' . $c . '" ' . '>' . htmlspecialchars($category->load($c)->getName()) . '</option>' . "\n";
}
?>

<form id="search_mini_form" action="<?php echo $this->helper('catalogSearch')->getResultUrl() ?>" method="get">
   <fieldset>
        <legend><?php echo $this->__('Search Site') ?></legend>
        <div class="mini-search">
            <input id="search" type="text" class="input-text" name="<?php echo $this->helper('catalogSearch')->getQueryParamName() ?>" value="<?php echo $this->helper('catalogSearch')->getEscapedQueryText() ?>" />
            <select name="cat">
            <option value="">Select Category</option>
            <?= $extra_options ?>
           </select>    
           <?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);?>
 <select name="manufacturer" id="manufacturer" class="" title="Manufacturer" >
          <?php foreach ($manufacturers as $manufacturer): ?>
            <option value="<?php echo $manufacturer['value'] ?>"><?php echo $manufacturer['label'] ?></option>
   <?php endforeach; ?>
       </select>
           <input type="submit" value="Go" style="border: 1px solid #808080;" alt="<?php echo $this->__('Search') ?>" />
            <div id="search_autocomplete" class="search-autocomplete"></div>
           <script type="text/javascript">
            //<![CDATA[
                var searchForm = new Varien.searchForm('search_mini_form', 'search', '<?php echo $this->__('Search Entire Site...') ?>');
                searchForm.initAutocomplete('<?php echo $this->helper('catalogSearch')->getSuggestUrl() ?>', 'search_autocomplete');
            //]]>
            </script>
        </div>
    </fieldset>
</form>  

How to show all the manufactures or brand list in magento left sidebar?

create a manufacturers.phtml file under "app/design/frontend/default/YOURTHEME/template/catalog/product"
<?php
/*
 * Manufacturers Listing on sidebar
 * @category    design
 * @package     base_default
 */
?>

<div>
  <div>
    <h4><span>Our Brands</span></h4>
  </div>
  <div>
  <?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="<?php echo Mage::getBaseUrl(); ?>catalogsearch/advanced/result/?manufacturer[]=<?php echo $manufacturer['value'] ?>"><?php echo $manufacturer['label'] ?></a></li>
      <?php endforeach; ?>
    </ul>
  </div>
  <div></div>
</div> 
Add the below code in your "/app/design/frontend/default/YOURTHEME/layout/catalog.xml" file.



Thats it you are done.

How to get configurable products attributes / super attributes details in magento?

   $productId = $_product->getId();
   $product=Mage::getModel("catalog/product")->load($prodcutId);
 
    /**
     * Get Configurable Type Product Instace and get Configurable attributes collection
     */
    $configurableAttributeCollection=$product->getTypeInstance()->getConfigurableAttributes();
 
    /**
     * Use the collection to get the desired values of attribute
     */
    foreach($configurableAttributeCollection as $attribute){
        echo "Attr-Code:".$attribute->getProductAttribute()->getAttributeCode()."
"; echo "Attr-Label:".$attribute->getProductAttribute()->getFrontend()->getLabel()."
"; echo "Attr-Id:".$attribute->getProductAttribute()->getId()."
"; }

Wednesday, September 14, 2011

How to get Parent category id in Magento?

Here is the code to get parent category id.
$current_category = Mage::registry('current_category');
echo $parent_id = $current_category->parent_id; 

Magento how to get category id in product page?

<?php $categories = $_product->getCategoryIds(); ?>
<?php foreach($categories as $k => $_category_id): ?>
    <?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
    <a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
<?php endforeach; ?> 
This will load and link all of the categories that the product is found in.

How do I change SHOP BY text in left sidebar Magento?

Are you trying to replace the "SHOP BY" text? And failed to replace the text? Dont worry, that is not actaully a text. That is Image.
Solution 1: You will need to replace the image under "skin/frontend/default/default/images/bkg_block-layered-title.gif";
Solution 2: Locate a file "app/design/frontend/default/YOURTHEME/template/catalog/layer/view.phtml" Change the class name "block-title" to something else.

How to show country flag in Magento language or currency dropdown?

Edit your page.xml file ("app/design/frontend/default/YOURTHEME/layout/page.xml")
Around line 58 change
 
to
 
Note: You have to place your country flag images under "skin/frontend/default/YOURTHEME/images/flag/flag_FLAGNAME.jpg"..
Using firebug in mozilla find out the image name and place the image in apprpriate folder.

Thats it. You are done.

Tuesday, September 13, 2011

How to Add CMS page link to top links or footer links in Magento?

Use "<prepare>true</prepare>" to get correct url path.
customer-serviceCustomer Servicetrue1000

How to get Most Viewed products in Magento?

Here is the code to get most viewed Products in Magento
    /**
     * 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);
  
    print_r($products);

Monday, September 12, 2011

How to Show Language Switcher in Magento Header or Footer?

Step 1: Create a new phtml file "template/page/switch/stores-top.phtml" and write the following code in it:
<?php if(count($this->getGroups())>1): ?>
<div class="language-switcher" style="margin-left:15px">
    <label for="<span class="store" id="switcher">select</span>-store"><?php echo $this->__('Select Store') ?>: </label>
    <select id="select-store" onchange="location.href=this.value">
    <?php /*foreach ($this->getStores() as $_store): ?>
        <span class="IL_AD" id="IL_AD1">option value</span>="<?php echo $_store->getUrl('') ?>"<?php if($_store->getId()==$this->getCurrentStoreId()): ?> <span class="IL_AD" id="IL_AD4">selected</span>="selected"<?php endif; ?>><?php echo $_store->getName() ?></option>
    <?php endforeach;*/ ?>
    <?php foreach ($this->getGroups() as $_group): ?>
        <?php $_selected = ($_group->getId()==$this->getCurrentGroupId()) ? 'selected="selected"' : '' ?>
        <option value="<?php echo $_group->getHomeUrl() ?>" <?php echo $_selected ?>><?php echo $this->htmlEscape($_group->getName()) ?></option>
    <?php endforeach; ?>
    </select>
</div>
<?php endif; ?>
Step 2: Add store_switcher_top block after store_language block inside header block of "page.xml" present around line number 66.


    
    
    
    

step 3: Add getChildHtml('store_switcher_top') below getChildHtml('store_language') in "template/page/html/header.phtml" like below.
$this->getChildHtml('store_language');
$this->getChildHtml('store_switcher_top');

Configurable products options are empty after moving my cart side bar to header?

I have explained Moving Cart from Right Sidebar to Header in this tutorial. After moving my cart to header I have noticed configurable options are not shown up in header. To display configurable product options do the following.

Edit your "template/checkout/cart/sidebar/default.phtml" file.
Find the line if ($_options = $this->getOptionList()):

Replace with the following
$_product = Mage::getModel('catalog/product')->load($this->getProduct()->getId());
$config = new Mage_Catalog_Helper_Product_Configuration();  
if ($_options = $config->getConfigurableOptions($_item)): 
Thats it. You are done.

Saturday, September 10, 2011

How to create custom pagination in magento?

Edit your "template/catalog/product/list/toolbar.phtml" file. Place the below line to the top of the file.
$_productCollection = Mage::getModel('catalog/product')->getCollection();
$_productCollection->addAttributeToFilter('brand', array('in' => array(11)));
$_productCollection->addAttributeToSelect('*');
$_productCollection->load(); 
$this->setCollection($_productCollection);

How to get product collection based on attribute (manufacturer, brand) values in magento?

Here is the code to get products based on attribute values. For example here I used to show products based on attribute "brand". In brand attribute I have values nike, adidas. 11 is the code for nike. I here used to display only nike products.
$_productCollection = Mage::getModel('catalog/product')->getCollection();
$_productCollection->addAttributeToFilter('brand', array('in' => array(11)));
$_productCollection->addAttributeToSelect('*');
$_productCollection->load(); 

Friday, September 9, 2011

How to get magento skin url of images?

getSkinUrl() function is used to get the image location. For example, If you want to get your image location "skin/frontend/default/Your theme/images/image.jpg" use the below code.

$this->getSkinUrl('images/image.jpg');

What is the relation Block, Model, Controllers MVC in magento?

             A quick primer on MVC: When a page in Magento is called, the URL tells Magento what code to run. This is done via a “router” which calls upon a selected Controller to do it’s thing. The URL gets “routed” to a particular Controller, which in turns tells Magento what to do. The Catalog controller, for instance, is responsible for telling Magento to load a product collection and and then show those products to us. The Controller tells Magento which layout is to be used. This determines which modules are put into place, which in turn tells Magento what Views to output. The data from the Models are given to the Views to be displayed. In the scheme of things here, Blocks fit roughly between the View and the Model.

Thursday, September 8, 2011

How to Add Confirmation email field in magento registration form using class validate-cemail?

The following method allows you to add confirmation email address field in your customer registration or newsletter page.
Create a javascript file called validation.js under "js/email/validation.js"
Validation.addAllThese([

    ['validate-cemail', 'Please make sure your emails match.', function(v) {
                var conf = $('confirmation') ? $('confirmation') : $$('.validate-cemail')[0];
                var pass = false;
  var confirm;
                if ($('email')) {
                    pass = $('email');
                }
  confirm =conf.value;
  if(!confirm && $('email2'))
  {
  confirm = $('email2').value;
  }
                return (pass.value == confirm);
            }],
]); 
Add the new js file into your customer.xml file

    
 
On the register form add a new field to contain the email confirmation field "template/customer/form/register.phtml".

Thats all. You are done.

Custom Form Validation in Magento

List of validate class And error messages :

      Class => Error Message
      1. validate-select => Please select an option.
      2. required-entry => This is a required field.
      3. validate-number => Please enter a valid number in this field.
      4.validate-digits => Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.
      5. validate-alpha => Please use letters only (a-z or A-Z) in this field.
      6. validate-code => Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.
      7. validate-alphanum => Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.
      8. validate-street => Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.
      9. validate-phoneStrict => Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.
      10. validate-phoneLax => Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.
      11. validate-fax => Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.
      12. validate-date => Please enter a valid date.
      13.validate-email => Please enter a valid email address. For example johndoe@domain.com.
      14. validate-emailSender => Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.
      15. validate-password => Please enter 6 or more characters. Leading or trailing spaces will be ignored.
      16. validate-admin-password => Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.
      17. validate-cpassword => Please make sure your passwords match.
      18. validate-url => Please enter a valid URL. http:// is required
      19. validate-clean-url => Please enter a valid URL. For example http://www.example.com or http://www.example.com
      20. validate-identifier => Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page
      21. validate-xml-identifier => Please enter a valid XML-identifier. For example something_1, block5, id-4
      22. validate-ssn => Please enter a valid social security number. For example 123-45-6789.
      23. validate-zip => Please enter a valid zip code. For example 90602 or 90602-1234.
      24. validate-date-au => Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.
      25. validate-currency-dollar => Please enter a valid $ amount. For example $100.00.
      26. validate-one-required => Please select one of the above options.
      27. validate-one-required-by-name => Please select one of the options.
      28. validate-not-negative-number => Please enter a valid number in this field.
      29. validate-state => Please select State/Province.
      30. validate-new-password => Please enter 6 or more characters. Leading or trailing spaces will be ignored.
      31. validate-greater-than-zero => Please enter a number greater than 0 in this field.
      32. validate-zero-or-greater => Please enter a number 0 or greater in this field.
      33. validate-cc-number => Please enter a valid credit card number.
      34. validate-cc-type => Credit card number doesn\’t match credit card type
      35. validate-cc-type-select => Card type doesn\’t match credit card number
      36. validate-cc-exp => Incorrect credit card expiration date
      37. validate-cc-cvn => Please enter a valid credit card verification number.
      38. validate-data => Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.
      39. validate-css-length => Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%
      40. validate-length => Maximum length exceeded.

How To Set Default Store Currency Based On Visitor Country In Magento?

Installing php-geoip:

If you have full control over your server running Magento, then this task is really easy. Log in with a sudo account or root and just use your distro’s package manager to install php-geoip. On Ubuntu/Debian, all you need to do is:
sudo apt-get install php5-geoip
For other distros, you may need to google around a little.

Now we will create module.
Create file "/app/code/local/MageTalks/Custom/etc/config.xml"

    
        
            0.1
        
    
    
        
            
                
                    MageTalks_Custom_Model_Store
                
            
        
    


Then in "/app/code/local/MageTalks/Custom/Model/Store.php"
class MageTalks_Custom_Model_Store extends Mage_Core_Model_Store
{
    public function getDefaultCurrencyCode()
    {
        // by default we look for the configured currency code
        $result = $this->getConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_DEFAULT);
        // however, in our case we want to determine the default currency depending on the country/continent of the visitor
        $geoCountryCode = null;
        try {
                // we'll try to get the visitor country
            $geoCountryCode = geoip_country_code_by_name( $_SERVER['REMOTE_ADDR'] );
        } catch (Exception $e) {
            // prevent NOTICE error - for example we are running the code on a localhost
        }
        // first tier check is the specific countries to set the currency for
        // NOTE: you can roll your own logic here depending on your enabled/supported countries/currencies
        // this example assumes that AUD, GBP, JPY, USD, EUR and NZD are the supported currencies
        switch ($geoCountryCode) {
            case "AU":
                $result = "AUD";
                break;
            case "GB":
                $result = "GBP";
                break;
            case "JP":
                $result = "JPY";
                break;
            default:
                $geoContinentCode = null;
                // now grab the continent code and set further by general regions
                try {
                    $geoContinentCode = geoip_continent_code_by_name( $_SERVER['REMOTE_ADDR'] );
                                // You can debug here to check the continent codes...
                    Mage::log("GEOIP::CONTINENT::".$geoCountryCode);
                    } catch (Exception $e) {
                    Mage::log("EXCEPTION CAUGHT".$e->getMessage());
                    // prevent NOTICE error
                }
                        // Now decide what currency to set depending on broad regions
                switch ($geoContinentCode) {
                    case "EU": // we'll set EUR for European countries
                        $result = "EUR";
                        break;
                    case "NA": // North America
                    case "SA": // South America
                    case "AS": // Asia
                    case "AF": // Africa - all of them will see USD
                        $result = "USD";
                        break;
                    default:    // everything else uses the default store currency as set in config
                }
        }
        return $result;
    }
}
Then all we need is the module xml file in "/app/etc/modules/MageTalks_Custom.xml"

    
            
            true
            local
                
                     
                
            
    

Wednesday, September 7, 2011

Magento Convert price from One Currency to Another Currency

Here is a quick code to convert price amount from one currency to another currency. From the code below, you can convert any currency you desire. You just need the ‘From Currency Code’ and ‘To Currency Code’. Make sure you have imported exchange rate in your admin backend.
$fromCurrency = 'USD'; // currency code to convert from - usually your base currency
$toCurrency = 'EUR'; // currency to convert to
$price = Mage::helper('directory')->
    currencyConvert($_product->getFinalPrice(), $fromCurrency, $toCurrency);
// if you want it rounded:
$final_price = Mage::app()->getStore()->roundPrice($price);

How to add Terms and Conditions in magento customer registration form?

While customer registration sometimes we need to add Terms & Conditon page with checkbox. Here is the code to add terms & condition field to your registration form.
<?php echo $this->__('I have read and agreed to the ') ?><a href="#">Terms and Conditions</a> <input type="checkbox" name="terms" title="<?php echo $this->__('Terms and Conditions') ?>" value="1" id="terms" class="checkbox required-entry" />

How to add address field in magento customer registration form?

If you want to add address details in your form you are in luck. Those fields are already setup in the "template/customer/form/register.phtml" file, but they are disabled by an inactive if statement that so far has not actually been linked to anything else in Magento. Therefore to enable the address related fields you simply need to comment out or delete the following statements:

<?php if($this->getShowAddressFields()): ?>

and

<?php endif; ?>

Note that there are two occurrences of this if statement. One is around the area where the customer actually inputs their data  and the second statement is bottom of the file around some JavaScript code that sets up the State/Province select.

Tuesday, September 6, 2011

How to interchange the left and right column sidebar in magento?

Go to "app/design/frontend/{Your theme}/{Your theme}/layout/"
look in all the XML files for this text: reference="left" and reference="right" and interchange them.

For example Replace

    
        images/media/col_left_callout.jpg
        Our customer service is available 24/7. Call us at (555) 555-0123.
        checkout/cart
    

to

    
        images/media/col_left_callout.jpg
        Our customer service is available 24/7. Call us at (555) 555-0123.
        checkout/cart
    


How do I find which file this function is referencing in magento?

          Let's say you have in a phtml file this line of code. $object->method(); ($object can be anything including $this). And you don't know what class file the current object is referencing. To find the class name of the object use the get_class() method. echo get_class($object);
          Clear the cache (contents of var/cache) and reload the page. You should see the name of the class. For example Mage_Catalog_Model_Category. now all you have to do is to find the file. Because Magento is based on Zend Framework it uses the the same convention for class naming.
           So class Abc_Def_Ghi will be in the file "Abc/Def/Ghi.php" (for the example above the file is "Mage/Catalog/Model/Category.php").

           All the classes are placed in "app/code/core" or "app/code/local/" or "app/code/community" or "lib/" and after that follow the path like explained above. If you don't find a method in that specific class look in one of the parents. Check the class that the current class extends.

           You will not find all the methods in Magento. For example some of the methods that start with get, set, has, uns is possible that the methods are missing. For this take a look in Varien_Object class (that is the base class for most of the objects) lib/Varien/Object.php file (remember the convention above?) and look in the 'magic' method __call().
Mage::getSingleton('checkout/session')->setData(cart_was_updated, false); 
So basically any method that starts with ‘set’ and it’s not found in any model is equivalent with setData(’lower_case_key’, $value);
It works the same for methods that start with ‘get’, ‘has’, ‘uns’ (from unset).

Magento Get current site base url

Mage::getUrl();

Magento Add simple product to cart through query string

Here is the easiest way to add simple products to cart through query string.
http://www.demostore.com/checkout/cart/add?product=[id]&qty=[qty]

http://www.demostore.com/checkout/cart/add?product=[id]&qty=[qty]&options[id]=[value]

Get Magento Product image path

Here is the easy way to get products image path.
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::helper('catalog/image')->init($product, 'image')->resize(75, 75);

Newsletter Subscription Page in Magento

Magento has a nice inbuilt feature of Newsletter Subscription , but sometimes you may need to call it to a separate or CMS page. So, in order to do that, you can just use this code,

{{block type="newsletter/subscribe" template="newsletter/subscribe.phtml"}}

Just place it on your CMS page and clear your cache. Thats done.

Monday, September 5, 2011

Rewrite Magento Mage_Core_Model_App class?

We cant rewrite "Mage_Core_Model_App" class. Only classes that are instantiated using Mage::getModel('module/model') can be overloaded.

Mage_Core_Model_App is instantiated as a regular PHP class ($app = new Mage_Core_Model_App), because it is one of the first classes instantiated, before Magento configuration is available.

So, the only way to have custom Mage_Core_Model_App is the regular PHP way of doing it, meaning copying it to app/code/local/Mage/Core/Model/App.php and let include_path do its work.

Thursday, September 1, 2011

Magento You cannot define a correlation name more than once

I got the error when adding color option to the sorting dropdown "You cannot define a correlation name 'color_t1' more than once". Here is the solution which works fine.
Go to the file "/lib/Zend/Db/select.php"
Comment the below line
throw new Zend_Db_Select_Exception("You cannot define a correlation name '$correlationName' more than once");

Saturday, August 27, 2011

How to get the customer login, logout, register and checkout url?

Mage::getUrl('customer/account/login'); //login url 
Mage::getUrl('customer/account/logout'); //logout url
Mage::getUrl('customer/account'); //My Account url
Mage::getUrl('customer/account/create'); // Register url
Mage::getUrl('checkout/cart'); //Checkout url

Friday, August 26, 2011

Magento Pagination Without Toolbar?

Add the below code to your end of "template/catalog/product/list.phtml" file.
<?php 
   // manually get the toolbar block so we can do the page navigation
   $toolbar = $this->getToolbarBlock();
   $toolbar->setCollection($_productCollection);
   if($toolbar->getCollection()->getSize() > 0):
      echo $toolbar->getPagerHtml(); //Pager
      echo $toolbar->__('Items %s to %s of %s total', $toolbar->getFirstNum(), $toolbar->getLastNum(), $toolbar->getTotalNum());
   endif;
?>
Thats it. It will work perfectly.

Tuesday, August 23, 2011

How to show total shopping cart price in Header Magento?

Edit the template\page\html\header.phtml file and add the below code 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));
?>

How to move Cart from Right Sidebar to Header in Magento?

Find the below line in your page.xml file.
 //Near line 70
Add the below code inside to that block

Your new code will look like this

        
        
        
            
        
        
            
            top-container
        
	//new block 
	

Finally Add the below code in your "\template\page\html\header.phtml" file.
//place this where ever you want the cart to show up.
<?php echo $this->getChildHtml('topcart'); ?> 
Thats it. You can see the cart sidebar in your header section.

How to remove wishlist link url from top links in magento?

Comment the below line in your wishlist.xml file.

          
            wishlist_link

How to add customer register link to the top links in magento?

Add the below line in your customer.xml file.

	   Register11

Monday, August 22, 2011

Custom 'Sort by' drop-down menu options Lowest price, Higest price, Name A-Z, Name Z-A, Newest to Oldest & Oldest to Newest in magento

Edit "template/catalog/product/list/toolbar.phtml"
Original code:
<div class="sort-by">
            <label><?php echo $this->__('Sort By') ?></label>
            <select onchange="setLocation(this.value)">
            <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
                <option value="<?php echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>
                    <?php echo $this->__($_order) ?>
                </option>
            <?php endforeach; ?>
            </select>
            <?php if($this->getCurrentDirection() == 'desc'): ?>
                <a href="<?php echo $this->getOrderUrl(null, 'asc') ?>" title="<?php echo $this->__('Set Ascending Direction') ?>"><img src="<?php echo $this->getSkinUrl('images/i_desc_arrow.gif') ?>" alt="<?php echo $this->__('Set Ascending Direction') ?>" class="v-middle" /></a>
            <?php else: ?>
                <a href="<?php echo $this->getOrderUrl(null, 'desc') ?>" title="<?php echo $this->__('Set Descending Direction') ?>"><img src="<?php echo $this->getSkinUrl('images/i_asc_arrow.gif') ?>" alt="<?php echo $this->__('Set Descending Direction') ?>" class="v-middle" /></a>
            <?php endif; ?>
</div> 
Replace with:
<fieldset class="sort-by">
        <label><?php echo $this->__('Sort by') ?></label>
        <select onchange="setLocation(this.value)">
            <option value="<?php echo $this->getOrderUrl('position', 'asc') ?>"<?php if($this->isOrderCurrent('position') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>
                Featured
            </option>
            <option value="<?php echo $this->getOrderUrl('price', 'asc') ?>"<?php if($this->isOrderCurrent('price') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>
                Lowest Price
            </option>
            <option value="<?php echo $this->getOrderUrl('price', 'desc') ?>"<?php if($this->isOrderCurrent('price') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>
                Highest Price
            </option>
            <option value="<?php echo $this->getOrderUrl('name', 'asc') ?>"<?php if($this->isOrderCurrent('name') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>
                Name A-Z
            </option>
            <option value="<?php echo $this->getOrderUrl('name', 'desc') ?>"<?php if($this->isOrderCurrent('name') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>
                Name Z-A
            </option>
            <option value="<?php echo $this->getOrderUrl('entity_id', 'desc') ?>"<?php if($this->isOrderCurrent('entity_id') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>
                Newest to Oldest
            </option>
            <option value="<?php echo $this->getOrderUrl('entity_id', 'asc') ?>"<?php if($this->isOrderCurrent('entity_id') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>
                Oldest to Newest
            </option>
        </select>
</fieldset>  

How to move magento search bar from header to sidebar?

Edit "app/design/frontend/<your theme>/<your theme>/layout/catalogsearch.xml"

Fine the line:

    

Replace the reference name to left or right.

    

Friday, August 19, 2011

How to show all stores in magento top menu?

Edit "app/design/frontend/<your theme>/<your theme>/template/catalog/navigation/top.phtml".
Add the below code before the line <?php echo $_menu ?>
<li onmouseover="toggleMenu(this,1)" onmouseout="toggleMenu(this,0)" class="level0 first nav-store <?php if(strpos($_SERVER['REQUEST_URI'], '?___store') && !strpos($_SERVER['REQUEST_URI'], '?___store=default')): echo 'active'; else: echo ''; endif; ?>">
      <a href="<?php echo $this->getUrl() ?>"><span><?php echo $this->__('SHOP BY BRAND') ?></span></a>
          <?php $store_groups = Mage::app()->getStores(); ?>
           <?php if(count($store_groups)>1): ?>            
               <ul class="level0">
                <?php $level_counter = 1;?>
                <?php foreach ($store_groups as $_eachStoreId => $val): ?>  
                   <li class="level1 nav-home-<?php echo $level_counter;?>">
                      <a href="<?php echo Mage::app()->getStore($_eachStoreId)->getHomeUrl() ?>"><span><?php echo Mage::app()->getStore($_eachStoreId)->getName(); ?></span></a>
                   </li>
                   <?php $level_counter++;?>
                <?php endforeach; ?>
               </ul>
          <?php endif; ?>

How to get all store details in magento?

<?php 
$allStores = Mage::app()->getStores();
foreach ($allStores as $_StoreId => $val)
{
    $storeCode = Mage::app()->getStore($_StoreId)->getCode();
    $storeName = Mage::app()->getStore($_StoreId)->getName();
    $storeId = Mage::app()->getStore($_StoreId)->getId();
    $storeUrl = Mage::app()->getStore($_StoreId)->getHomeUrl();
}
?>

How to add home page link in magento top menu?

Edit "app/design/frontend/<your theme>/<your theme>/template/catalog/navigation/top.phtml".
Add the below line before the line <?php echo $_menu ?>

<li class="home<?php if (Mage::helper('core/url')->getCurrentUrl() === Mage::helper('core/url')->getHomeUrl()):?> active<?php endif;?>"><a href="<?php echo $this->getUrl('')?>"><?php echo $this->__('Home') ?></a></li>

Friday, August 12, 2011

How to change number of columns products fill in product list page?

Edit the below line in catalog/product/list.phtml
<?php $_columnCount = 4;//$this->getColumnCount(); ?>

Thursday, August 11, 2011

Bulk Emails import into Magento Newsletter Subscriber List

<?php
require_once 'app/Mage.php';
umask( 0 );
Mage :: app( "default" );
//$_helper = new Mage_Newsletter_Model_Subscriber();
//$_helper->subscribe("myemail@e-mail.co.uk");
$emails = array("myemail4@e-mail.co.uk","myemail5@e-mail.co.uk","myemail6@e-mail.co.uk");
foreach($emails as $email){
 $db = Mage::getSingleton('core/resource')->getConnection('core/write');
 $query = "SELECT * FROM newsletter_subscriber WHERE subscriber_email = '$email'";
 $result = $db->query($query);
 if($result->fetchAll()):
 echo "Email Not Added: $email<br/>";
 else:
 $db->query("INSERT INTO newsletter_subscriber (`subscriber_id` , `store_id` , `change_status_at` , `customer_id` , `subscriber_email` , `subscriber_status` , `subscriber_confirm_code`) VALUES (NULL,'1',NULL,'0','$email','1',NULL)");
 echo "Email Successfully Added: $email<br/>";
 endif;
}
?>

How to change the Magento Admin Panel Title?

Edit the main.xml file located at "/app/design/adminhtml/default/default/layout/main.xml"
On line 57 you will find:
Magento Admin
Just edit the text within the title tags to whatever you want the new title to be.

How to Disable admin Latest Messages Notification in magento?

Just goto:

System > Configuration > Advanced > Disable Module Output and disable Mage_AdminNotification

How to add Social Bookmarks link to Magento Product Page?

Add the below code into your view.phtml file located at "/app/design/frontend/base/default/your-template/catalog/product/view.phtml"

How to add Quantity Box in the Category Products Listing Page in magento?

Edit your list.phtml file located at "/app/design/frontend/default/your-theme/template/catalog/product/list.phtml".

Find the below code, line number at 61 for list mode and line number 103 for grid view:
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
replace it with,
<form action="<?php echo $this->getAddToCartUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
 <?php if(!$_product->isGrouped()): ?>
     <label for="qty"><?php echo $this->__('Qty') ?>:</label>
     <input type="text" name="qty" id="qty" maxlength="12" size = "3" value="<?php echo ($this->getMinimalQty($_product)?$this->getMinimalQty($_product):1) ?>" />
 <?php endif; ?>
</form>

Magento Search Showing All Products

If the search filter is not working as you need, then here is the solution :
-> Replace the catalogsearch folder under "app/design/frontend/default/your-theme/template" with "app/design/frontend/base/template/catalogsearch/".
-> Replace the catalogsearch.xml file under the "app/design/frontend/default/your-theme/layout/" with "app/design/frontend/base/layout/catalogsearch.xml".
-> Clear the cache.

CONNECT ERROR: Couldn't resolve host 'magento-community'

If you are trying to install any 3rd party extensions from your magento connect manager and getting such an error,

“CONNECT ERROR: Couldn't resolve host 'magento-community'”

Then the reason is the Magento Connect is not able to detect the download channel.

You will need to change the Magento Connect Version 1.0 to 2.0 when getting the extension key from magento extension page Or this can be installed using new connect manager by changing the extension key format.

For example: magento-community/Mage_myModule needs to be changed to http://connect20.magentocommerce.com/community/Mage_myModule

How to reindex manually using sql query?

Create a file called “reindex.php” inside your magento root folder and put the following code.
<?php
    require_once 'app/Mage.php';
    umask( 0 );
    Mage :: app( "default" );
    echo "Started Rebuilding Search Index At: " . date("d/m/y h:i:s");
//Locate the correct table. For example here im reindexing catalogsearch_fulltext table.
    $sql = "truncate catalogsearch_fulltext";
    $mysqli = Mage::getSingleton('core/resource')->getConnection('core_write');
    $mysqli->query($sql);
    /*
    Process_id     Indexer_code
        1     catalog_product_attribute
        2     catalog_product_price
        3     catalog_url
        4     catalog_product_flat
        5     catalog_category_flat
        6     catalog_category_product
        7     catalogsearch_fulltext
        8     cataloginventory_stock
        9     tag_summary
    */
    $process = Mage::getModel('index/process')->load(7);
    $process->reindexAll();
    echo "Finished Rebuilding Search Index At: " . date("d/m/y h:i:s");
?>
Then run this script by visiting www.yourdomain.com/reindex.php in your browser.
Then clear your cache.

Magento Product Thumbnail Image Switcher


This article which explains how to easily replace the default functionality of your product images (the pop-up window when you click on a thumbnail below the main image) with a image swapping functionality.

Step One

Edit the media.phtml file. It can be found at:
app/design/frontend/base/default/template/catalog/product/view/media.phtml
Assuming that you have the default Magento file structure.

Step Two

Locate the code that we will be editing (on or around line 73 in media.phtml) and replace it with the replacement code below. Thats it!

Original Code:
<a href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'width=300,height=300,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"><img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" width="56" height="56" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /></a> 
Replacement Code:
<a href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()); ?>" title="<?php echo $_product->getName();?>" onclick="$('image').src = this.href; return false;"><img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" width="56" height="56" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /></a>

Its tested with magento 1.5.1.0

Quick debug tips in magento

Mage::log() function is used to debug in magento. You can add items to magento’s system log and exception log in your code.
Here’s an example of it’s use:
1) Turn on your logging: Admin > Configuration > Developer > Log Settings > Enabled = Yes
2) Example code snippet where you might find this useful:
Mage::log(get_class_methods($this));
3) Watch your var/log/system.log and var/log/exception.log for raw information from this.

Tuesday, August 9, 2011

How to get SQL Query as a string in magento?

If you are using collections, There are two ways of getting SQL from the collection of Magento.
1. Echoing Query String.
	
/** If $collection is your collection**/
$collection->printlogquery(true);
/** Don't forget to write true in param**/
But by this method you cannot assign the query you get echoed to some variable.

2. Getting the query String
$query=$collection->getSelectSql(true);
echo $query;

Get ordered items and their details from ordered id in magento

$itemcount = 0;
$order = Mage::getModel('sales/order')->load($order_id);
$items = $order->getAllItems();
$itemcount=count($items);
$name=array();
$unitPrice=array();
$sku=array();
$ids=array();
$qty=array();
if($itemcount > 0){
	foreach ($items as $itemId => $item)
	{
	    $name[] = $item->getName();
	    $unitPrice[]=$item->getPrice();
	    $sku[]=$item->getSku();
	    $ids[]=$item->getProductId();
	    $qty[]=$item->getQtyToInvoice();
	}
}

Delete test products, categories, customers, products reviews and ratings in magento

//Delete 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`;
    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_link_type`;
    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`;
    TRUNCATE TABLE `cataloginventory_stock_item`;
    TRUNCATE TABLE `cataloginventory_stock_status`;

    insert  into `catalog_product_link_type`(`link_type_id`,`code`) values (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
    insert  into `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) values (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
    insert  into `cataloginventory_stock`(`stock_id`,`stock_name`) values (1,'Default');

//Delete categories
    TRUNCATE TABLE `catalog_category_entity`;
    TRUNCATE TABLE `catalog_category_entity_datetime`;
    TRUNCATE TABLE `catalog_category_entity_decimal`;
    TRUNCATE TABLE `catalog_category_entity_int`;
    TRUNCATE TABLE `catalog_category_entity_text`;
    TRUNCATE TABLE `catalog_category_entity_varchar`;
    TRUNCATE TABLE `catalog_category_product`;
    TRUNCATE TABLE `catalog_category_product_index`;

    insert  into `catalog_category_entity`(`entity_id`,`entity_type_id`,`attribute_set_id`,`parent_id`,`created_at`,`updated_at`,`path`,`position`,`level`,`children_count`) values (1,3,0,0,'0000-00-00 00:00:00','2009-02-20 00:25:34','1',1,0,1),(2,3,3,0,'2009-02-20 00:25:34','2009-02-20 00:25:34','1/2',1,1,0);
    insert  into `catalog_category_entity_int`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) values (1,3,32,0,2,1),(2,3,32,1,2,1);
    insert  into `catalog_category_entity_varchar`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) values (1,3,31,0,1,'Root Catalog'),(2,3,33,0,1,'root-catalog'),(3,3,31,0,2,'Default Category'),(4,3,39,0,2,'PRODUCTS'),(5,3,33,0,2,'default-category'); 
//Delete product reviews & ratings
    truncate table `rating_option_vote`;
    truncate table `rating_option_vote_aggregated`;

    truncate table `review`;
    truncate table `review_detail`;
    truncate table `review_entity_summary`;
    truncate table `review_store`;
//Delete Customers

  TRUNCATE TABLE `customer_address_entity`;
  TRUNCATE TABLE `customer_address_entity_datetime`;
  TRUNCATE TABLE `customer_address_entity_decimal`;
  TRUNCATE TABLE `customer_address_entity_int`;
  TRUNCATE TABLE `customer_address_entity_text`;
  TRUNCATE TABLE `customer_address_entity_varchar`;
  TRUNCATE TABLE `customer_entity`;
  TRUNCATE TABLE `customer_entity_datetime`;
  TRUNCATE TABLE `customer_entity_decimal`;
  TRUNCATE TABLE `customer_entity_int`;
  TRUNCATE TABLE `customer_entity_text`;
  TRUNCATE TABLE `customer_entity_varchar`;

How to delete test orders in magento?

SET FOREIGN_KEY_CHECKS=0;
 
TRUNCATE `sales_order`;
TRUNCATE `sales_order_datetime`;
TRUNCATE `sales_order_decimal`;
TRUNCATE `sales_order_entity`;
TRUNCATE `sales_order_entity_datetime`;
TRUNCATE `sales_order_entity_decimal`;
TRUNCATE `sales_order_entity_int`;
TRUNCATE `sales_order_entity_text`;
TRUNCATE `sales_order_entity_varchar`;
TRUNCATE `sales_order_int`;
TRUNCATE `sales_order_text`;
TRUNCATE `sales_order_varchar`;
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_item`;
TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;
 
ALTER TABLE `sales_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_varchar` 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 `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` 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;

How to setup unique prefix For Orders, Invoices, Shipments, Customers and Quotes in magento?

* Orders (set prefix to begin with “O″)
* Invoices (set prefix to begin with “I″)
* Shipments (set prefix to begin with “S″)
* Customers (set prefix to begin with “C″)
* quotes (set prefix to begin with “Q″)
//For Orders
update `eav_entity_store` set `increment_prefix`= 'O' where `entity_type_id`='4' and `store_id`='1';
update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='4' and `store_id`='1';
 
//For Invoice
update `eav_entity_store` set `increment_prefix`= 'I' where `entity_type_id`='18' and `store_id`='1';
update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='18' and `store_id`='1';
 
//For shipments
update `eav_entity_store` set `increment_prefix`= 'S' where `entity_type_id`='24' and `store_id`='1';
update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='24' and `store_id`='1';

//For Customers
update `eav_entity_store` set `increment_prefix`= 'C' where `entity_type_id`='1' and `store_id`='1';
update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='1' and `store_id`='1';

//For quotes
update `eav_entity_store` set `increment_prefix`= 'Q' where `entity_type_id`='11' and `store_id`='1';
update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='11' and `store_id`='1';

Monday, August 8, 2011

Show new product attribute on the category page list.phtml in magento

Update layout xml (catalog.xml)


  

      


        YourAttributeCode

      

  


  

      


        YourAttributeCode

      

  


also you can use
YourAttributeCode
instead of
YourAttributeCode
Update template (catalog/product/list.phtml)
add the below code in list.phtml file
 $_helper->productAttribute($_product, $_product->myAttribute(), 'my_attribute');

How change default Home page url to any page url in Magento?

Goto
System -> Configuration -> Web -> Default Pages
and change
Default Web URL From cms to catalog/category/view/id/your CATEGORY ID

Example:
Default Web URL = catalog/category/view/id/123
You can also use any other url.

Categories are not showing up in magento home page

- Make sure you created categories under Default root category.
- Make sure all the categories are active. Inactive ones will be grayed-out. If a toplevel category is inactive the ones below do not show.
- Make sure your category products are,
- status - enabled
- visibility - catalog,search
- Stock Availability - In stock
- websites - your website
- categories - select your category

- Go to System > Manage Stores
- Click the “Main Website Store” link under Store Name
- Make sure the dropdown for “Root Category *” is set to you top level catergory.
- Now clear the cache.

Thats it. Now you can see categories in your homepage.

How to show specific category products on home page magento?

Add the below lines in your homepage cms.
{{block type="catalog/product_list" category_id="123" template="catalog/product/list.phtml"}} 
where 123 is your category id.

Friday, August 5, 2011

Magento: Sort product by 'created date' and 'new from date'

$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
 
$collection = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
                    ->addAttributeToFilter('news_to_date', array('or'=> array(
                        0 => array('date' => true, 'from' => $todayDate),
                        1 => array('is' => new Zend_Db_Expr('null')))
                    ), 'left')
                    ->addAttributeToSort('news_from_date', 'desc')
                    ->addAttributeToSort('created_at', 'desc');

Magento get last login

$customer = Mage::getSingleton('customer/session')->getCustomer();
$log = Mage::getModel('log/customer')->load($customer->getId());
$lastVisited = $log->getLastVisitAt();

Magento find how long customer is inactive?

$customer = Mage::getSingleton('customer/session')->getCustomer();
$log = Mage::getModel('log/customer')->load($customer->getId());
$inctive_time = now() - $log->getLastVisitAt();

How to get magento date and time?

$now = Mage::getModel('core/date')->timestamp(time());
echo date('m/d/y h:i:s', $now);

Wednesday, July 27, 2011

How to crop images in magento?

Here is the easiest way to crop image in Magento.
Here goes the code:
$mainImage = Mage::getBaseDir('media') . DS . 'test' . DS . 'sample.jpg';
$image = new Varien_Image($mainImage);
// crop image
$image->crop(10, 10, 10, 10); // crop(top, left, $right, $bottom)
$image->save(Mage::getBaseDir('media'). DS . 'test' . DS . 'new.jpg');
Code Explanation:
In the code above, you can see that I have an image named sample.jpg inside media/test/ directory.

At first, I have cropped the image by 10px from top, left, bottom, and right side.
The new cropped image is saved inside media/test/ directory as new.jpg.

How to remove index.php from URL magento?

If you are using Magento and in your shop URL, if you see “index.php” and wanted to remove it then here is the solution.

- Login to Magento admin panel
- Go to System -> Configuration -> Web -> Search Engines Optimization -> Use Web Server Rewrites
- Select ‘Yes’ from the selection list and Save.
- Goto your site root folder and you can find the .htaccess file. Just edit that. Open it on a text editor and find this line, #Rewrite Base /magento/ . Just replace it with Rewrite Base / .
- Then goto your Cache Management page ( System > Cache Management) and refresh your Cache and also refresh the Web Redirects.

And, you are done. Now, index.php is gone from your Magento shop URL.

Tuesday, July 26, 2011

How to change the default welcome message in magento?

Here is the easier way to change the Default welcome message that appears in header of Magento shop.
When the user is not logged in, by default the message appears as ‘Default welcome msg!‘.

To change the message text, follow steps below:-

- Go to
System -> Configuration -> GENERAL -> Design -> Header -> Welcome Text = YOUR WELCOME TEXT

That’s all. Now, the default welcome message is changed with your custom welcome message.