12/28/2011

How to override catalogsearch model class in magento

In magento if you wish to override some controller then definately you will get lots of site which will describe how to do that but for model class, you will have some result. So I think to share my knowledge here. I am going to override default catalog search Model of magento. For that I will create an module with name space name Mage and module name Searchby. I hope you people know how to create an module so I will show you how to override model class only

Go to config.xml of your custom module then write the below code to override the catalogsearch model class

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Mage_Searchby>
            <version>0.1.0</version>
        </Mage_Searchby>
    </modules>
    <frontend>
        <routers>
            <searchby>
                <use>standard</use>
                <args>
                    <module>Mage_Searchby</module>
                    <frontName>searchby</frontName>
                </args>
            </searchby>
        </routers>        
    </frontend>
    <global>
        <models>
            <catalogsearch>
                <rewrite>
                    <layer>Mage_Searchby_Model_Layer</layer>
                </rewrite>
            </catalogsearch>
        </models>
    </global>
</config>

Now create an Layer.php file inside yourmodulename/Model then write the below code

<?php
class Mage_Searchby_Model_Layer extends Mage_CatalogSearch_Model_Layer
{
    public function prepareProductCollection($collection)
    {
        //Code to be executed
    }
}?>

That's all thanks

11/25/2011

How to add search by category in magento mini search


There is no free extension in magento commerce which will help you to search your store with particular category. I tried from myself and able to do, I am sharing my exprerience here with.

First create the drop down list of all category in form.mini.phtml

<select name="category" id="category_search_field">
<option value="">-- Any Category --</option>
<?php foreach ($catalog->getStoreCategories() as $_category): ?>
<?php if($_category->hasChildren()): ?>
<option class="parent-cat" value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
<?php foreach ($_category->getChildren() as $subcategory):
if($subcategory->getIsActive()) : ?>
<option value="<?php echo $subcategory->getId(); ?>"<?php echo ($this->getRequest()->getQuery('category') == $subcategory->getId() ? ' selected="selected"': "") ?>><?php echo $subcategory->getName(); ?></option>
<?php endif; endforeach; ?>
<?php elseif($_category->getIsActive()): ?>
<option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
<?php endif; ?>
<?php endforeach ?>
</select>

Now go to app/code/core/Mage/CatalogSearch/Helper and open the Data.php and add the below code

public function getStoreCategories()
{
$helper = Mage::helper('catalog/category');
return $helper->getStoreCategories();
}
public function getSelectedCategory()
{
$catid = (int)addslashes($_REQUEST['category']);
$cat="";
if($catid>1)
$cat = Mage::getModel('catalog/category')->load($catid);
return $cat;
}

Now go to app/code/core/Mage/CatalogSearch/Model and open the Layer.php

replace

public function prepareProductCollection($collection)
{
$collection
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())
->setStore(Mage::app()->getStore())
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addStoreFilter()
->addUrlRewrite();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);
return $this;
}

with

public function prepareProductCollection($collection)
{
if(Mage::helper('catalogsearch')->getSelectedCategory()!="")
{
$collection
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())
->setStore(Mage::app()->getStore())
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addStoreFilter()
->addCategoryFilter(Mage::helper('catalogsearch')->getSelectedCategory())
->addUrlRewrite();
}
else
{
$collection
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())
->setStore(Mage::app()->getStore())
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addStoreFilter()
->addUrlRewrite();
}
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);

return $this;
}

save and Enjoy.

11/17/2011

cache is not generating in magento

Magento stores cache inside the cache folder which resides under Var folder of your root magento ,But if your cache folder or var folder have not correct file permisson that is 777 then magento will not be able to generate any cache. So change Var folder permission to 777 , you will see the effect.

10/31/2011

How To Display Best Selling Products On Magento Store

To promote best selling products on your site Magento use so many way to show bestseller product, One of them I am going to show. Below code will fetch the all the list of all product which have already sell.
<?php
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->setOrder('ordered_qty', 'desc');
?>

This is the collection of all the product which already have sell.

Now use foreach loop to show some number of product and it details. I wish to show only the name of the product which has sell most. And I will show on the left sidebar of the page.
<div class="block best-seller">
<div class="right-title-bg"><h3>Best Selling Product</h3></div>
<div class="block-content">
<ul class="best-selling-item">
$count = 0;
foreach($_productCollection as $product):
$id = $product->getId();
$prod = Mage::getModel('catalog/product')->load($id);?>
<li><a href="<?php echo $prod->getProductUrl();?>" title="<?php echo $prod->getName();?>"><?php echo $prod->getName();?></a></li>
<?php
$count++ ;
if($count==$totalPerPage)
break;
endforeach;
?>
</ul>
</div>
</div>

If you wish to show all the details of the product then you also can do that as you will get the product Id from $prod->getId(); and from product Id you can fetch each and every details of the product

10/29/2011

How to print product collection query in magento

Let you have write a product collection with some attribute to select some product, but you are not getting proper result then you must need to print the sql query to see whether you have write the correct syntax in magento default collection. then write the below code to get the sql query .

<?php
$productcollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('bestseller', array('eq' => 1))
->addAttributeToSelect('*');
echo $productcollection->getSelect()->assemble();
?>

9/27/2011

How to delete all sales order in magento

In Magento Connect you will find some extension which will delete all cancel order and Pending Order, But it never delete all processed order. To delete all orders following code snippet can be used.

<?php
require 'app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);                                                                              
$sales_orders = Mage::getModel('sales/order')->getCollection()->getData();
foreach($sales_orders as $sales_order){
    $id = 0;
    $id = $sales_order['increment_id'];
    try{
        Mage::getModel('sales/order')->loadByIncrementId($id)->delete();
        echo "order #".$id." is removed".PHP_EOL;
    }catch(Exception $e){
        echo "order #".$id." could not be remvoved: ".$e->getMessage().PHP_EOL;
    }
}
echo "complete."
?>

9/26/2011

How to use or mysql condition in $collection data of magento

Magento provide  addAttributeToFilter to use and operator in $collection, But using of OR operator is little bit different . I was guess that there must be and OrAttributeToFilter , But I was wrong I think magento forgot to write this function, Lastly I found the solution to use mysql OR in magento . In addAttributeToFilter we have to write the condition in the form of array.
protected function _prepareCollection()
{
   $collection = Mage::getModel('catalog/product')->getCollection();
   $collection->addAttributeToFilter(
      array(
          array('attribute'=>'category_ids','finset'=>2),
          array('attribute'=>'category_ids','finset'=>3)
      )
   );
}


use your own attribute name and value to get the data

9/16/2011

How to upload and read csv file in magento

To upload CSV file and to read that file line by line , Please write the below code in magento

if(isset($_FILES['import_file']['name']) && $_FILES['import_file']['name'] != '')
{
    $uploaderFile = new Varien_File_Uploader('import_file');
    $uploaderFile->setAllowedExtensions(array());
    $uploaderFile->setAllowRenameFiles(false);
    $uploaderFile->setFilesDispersion(false);
    $uploaderFilepath = Mage::getBaseDir('media') . DS . 'importcsv' . DS ;
    $uploaderFile->save($uploaderFilepath, $_FILES['import_file']['name'] );
    $file = $_FILES['import_file']['name'];
    $filepath = $uploaderFilepath.$file;
    $i = 0;
    if(($handle = fopen("$filepath", "r")) !== FALSE) {
        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){            
            if($i>0 && count($data)>1){
                updateData($data);
            }          
            $i++;
        }
    }
    else{
        Mage::getSingleton('adminhtml/session')->addError("There is some Error");
        $this->_redirect('*/*/index');
    }
}
    function updateData($data)
    {
        //Write your code here and Update it to magento tables
    }

8/30/2011

How to get contact us email address in magento

Here’s the code to get Contacts email:

<?php echo Mage::getStoreConfig('contacts/email/recipient_email');?>

Or you can change it from admin -> System-> Configuration. From the left tab select Contacts then On the right side you will see Email Options Tab. From that tab you can see there is a field for send Emails To.Change th evalue to your require email address

8/04/2011

How to uncheck Radio button by jquery

Write the Below code to Unchecked Radio Button by Jquery

<script type="text/javascript">
    $(document).ready(function(){
        $("#btn").click(function(){ 
           $('input[name="rd"][type="radio"]:checked').each(function(){ 
               $(this).attr("checked", false); 
            }); 
        });
    });
</script>



<form action="" name="aa" method="post">
    <input type="radio" name="rd" value="1"/>
    <input type="radio" name="rd" value="2"/>
    <input type="radio" name="rd" value="3"/>
    <input type="button" id="btn" value="Click" />
</form>

How to change value and fetch value of Minimum Order Amounts of free shipping in magento

First of all to make Minimum Order Amounts of Free Shipping to [STORE VIEW] instead of [WEBSITE] then Go to app->code->core->Mage->Shipping->etc->System.xml
then change the value of <show_in_store> to 1 under carriers -> groups -> freeshipping ->free_shipping_subtotal.

Now to fetch the value of the Minimum Order Amount according to store view write the below code

<?php echo Mage::getStoreConfig('carriers/freeshipping/free_shipping_subtotal'); ?>

7/30/2011

How to remove validation on zip code in magento checkout page

In the World some of the country has no zip code like Ireland, But magento has default zip code validation to make that optional for specific country magento has added a new feature in admin panel. To make Zip code optional please follow the following steps.

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. To be more clear on this please see the below screenshot.

7/17/2011

How to change default quantity on Magento Product Page

By default magento shows zero in the place of quantity text field in product details page, if you wish to change then just login to your admin panel go to System->Configuration->Catalog->inventory.

There, add your minimal quantity from Minimum Qty Allowed in Shopping Cart

See the below screenshot to make it more clear

6/16/2011

How to change css padding property using javascript dynamically

Using Javascript we can change css value. Here I have written how to change the value of padding top, padding bottom, padding left, padding right differently. var ab = 20;
//To change Padding-top value write document.getElementById("div_Id").style.paddingTop = ab.toString()+"px" //To change Padding-left value write document.getElementById("div_Id").style.paddingLeft = ab.toString()+"px" //To change Padding-right value write document.getElementById("div_Id").style.paddingRight = ab.toString()+"px" //To change Padding-bottom value write document.getElementById("div_Id").style.paddingBottom = ab.toString()+"px"

5/17/2011

How to send Email in magento

Any body can send mail using php mail() function.But in magento all the functionality has wriiten you need to just send argument inside those functions. See the following code to send mail using magento function

<?php
$mail = Mage::getModel('core/email');
$mail->setToName('Your Name');
$mail->setToEmail('Youe Email');
$mail->setBody('Mail Text / Mail Content');
$mail->setSubject('Mail Subject');
$mail->setFromEmail('Sender Mail Id');
$mail->setFromName("Msg to Show on Subject");
$mail->setType('html');// YOu can use Html or text as Mail format

try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
$this->_redirect('');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
?>

How to get all list of country in magento

Write the following code to any phtml file or template file you will get list of all the Country

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

How to get category or subcategory postioned by the admin panel in magento

When we load a category it shows his subcategory according to the product id. If you wish to show category according to the order which you have in you admin panel then you have to fetch your category with little bit different style.See the below code in which I have fetched all subcategory with proper order

<?php
$obj= new Mage_Catalog_Block_Navigation();
$category = $obj->getStoreCategories();
foreach($category as $_category)
{
$catid = $_category->getId();
$parentCategory = Mage::getModel('catalog/category')->load($catid);
$childrenIdArray = explode(',',$parentCategory->getChildren());
if ($key = array_search($parentCategory->getId(),$childrenIdArray)) {
unset($childrenIdArray[$key]);
}
$collection = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('entity_id', array('in' => $childrenIdArray))
->addAttributeToSelect('*');

$sortedcategory = $collection->addOrderField('position')->getData();
foreach($sortedcategory as $sorted)
{
$_subcat = Mage::getModel('catalog/category')->load($sorted['entity_id']);
$subcatname = $_subcat->getName();
echo "<h3>".$subcatname."</h3>";
}
}
?>

5/04/2011

How to get all gallery image with resize of a product in magento

In product page you can get gallery image of the current product, But if you think to fetch all gallery image of a product in other page like cms page, then you have to write the code with little bit modification. The code should looks like below

<?php
$obj = new Mage_Catalog_Block_Product_View_Media();
$_product = new Mage_Catalog_Model_Product();
// Load all product information of a particular product
$Products_one = Mage::getModel('catalog/product')->load($id);
// Use your Product Id instead of $id
$countt = count($Products_one->getMediaGalleryImages());
if($countt>0){
foreach ($Products_one->getMediaGalleryImages() as $_image)
{
// For the Original Image
echo "<img src=".Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).str_replace(Mage::getBaseUrl('media'),"",$_image->url)." alt='' />";
//For gallery Image
$resizeimage = $obj->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->backgroundColor(242,242,243)->resize(400,300);
echo "<img src=".$resizeimage."alt='' />";
}
}

5/03/2011

CSS Hack for Google Chrome and Safari

If you are developing any site or designing any website, having design problem in chrome and safari you can write the below css, It only works on Google chrome and Safari Browser

@media screen and (-webkit-min-device-pixel-ratio:0)
{
.classname{ background:#ccc; } /*It will works on Google chrome and safari */
}

4/28/2011

How to upload file in magento

If you are making your custom module in magento and if you unable to use default magento file upload then you can use magento custom file uploading code to upload file.

// If you want to upload files under media folder
$absolute_path = Mage::getBaseDir('media') . DS ;
$relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
// File Upload
$files = $_FILES['file_upload']['name'];
if(isset($files) && $files != '')
{
try
{
if(file_exists($absolute_path.DS.$files))
{
$var = rand(0,99);
$files = $var.'_'.$files;
}
// Starting upload
$uploader = new Varien_File_Uploader('file_upload');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
//false -> get the file directly in the specified folder
//true -> get the file in the product like folders /media/catalog/product/file.gif
$uploader->setFilesDispersion(false);
//We set media as the upload dir
$uploader->save($absolute_path, $files);
}
catch(Exception $e)
{
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
// Your uploaded file Url will be
echo $file_url = $relative_path.$files;
}

How to fetch all associative product of a configurable product in magento

Configurable product is the product which is created by some Associated product, If you have an configurable product and you want to get list of all associated product and it's attribute then just write the below

You must have your configurable product Id, My configurable product Id is 11 $id=11; //Use your Configurable product Id
$_product = new Mage_Catalog_Model_Product();
$childIds = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($id);
foreach($childIds[0] as $key=>$val)
{
   $associatedProduct = Mage::getModel('catalog/product') ->load($val);
   echo $associatedProduct ->getName();
//Let you have a color attribute in each associated product then you can fetch by
   $colorids[] = $associatedProduct ->getColor();
   $colorname[] = $associatedProduct ->getAttributeText('color');
}

How to and where to change default product image in Magento

If you forgot to upload any product image then Magento always show a default image,If you think to change default image then login to admin panel then goto System -> Configuration then click on Catalog tab. From Product Image Placeholders change your Base Image , Small Image and Thumbnail . Now click on Save Config button to make changes.


4/20/2011

How to Add option to select box by jquery

I have write the below code to add option to select drop down by jquery. Add value to the below input box then click on add button.You can see the effect.That option will be added to the below selectbox

The code you need to write is

$('#selectbox').append($("<option></option>").attr("value",option_value).text(text_to_display));

4/01/2011

How to add new order status in magento admin panel

To add New Status in magento admin panel, you need to write your own custom module , then in your config.xml file write the below code to add new Status

<config>
<global>
<sales>
<order>
<statuses>
<custom_status translate="label"><label><![CDATA[Custom Status]]></label></custom_status>
</statuses>
<states>
<new><!-- order state where you want to assign your custom status e.g:- New, Onhold, Canceld etc-->
<statuses>
<custom_status/>
</statuses>
</new>
</states>
</order>
</sales>
</global>
</config>

It will work upto 1.4.2 , But in Magento 1.5.0 or above there is Special Option to do this. To make own Custom status above magento 1.5 version go to System->Order Statuses. Then Click on Create New Status. After creating new status click on Assign Status to State to assign that status

3/28/2011

How To Create a custom url redirect in Magento using URL Rewrite Management

To make magento more SEO friendly, It needs to redirect to a custom url, By default magento have this feature but if you have created any module whose url like modulename/id/3, then you needs to redirect it to a SEO friendly url. To redirect the url to a "301 Permanent redirect" you just login to your admin panel, then go to -> Catalog -> URL Rewrite Management, from the drop down select Custom ,follow the below screenshot to make it more easy.

1) In the Id path give your current url (e.g: review/product/list/id/14/category/3)
2) In Request Path write same as Id path (e.g: review/product/list/id/14/category/3)
3) In Target Path give oyu custom Url with domain name (e.g:- http://www.mysite.com/mobile.html)

3/25/2011

How to create Special Product or Hot Product or Feature Product in magento

This is what I used many times while developed magento sites. I have made Feature products , Special Producst, Hot products etc by the custom attribute. To do so I am going to make some Special Product which will show on frontend, for this I will create a custom attribute Special Product whose code name will be special. First Log in to admin panel then Catalog->Attributes -> Manage Attributes . Now click on Add new Attribute, I n the Attribute Code field write special and from Catalog Input Type for Store Owner select Yes/No from the drop down, Choose NO from the Default Value .Now click on Manage Label / Options then in the Admin field write Special Product then click on Save Attribute button to save the attribute.

Now go to Catalog-> Attributes -> Manage Attribute Sets . Click on your Attribute set (e.g : - I choose Default attribute set) then add the Special attribute from Unassigned Attributes to Groups by drag and drop. Now go to any products which have same attribute set in which the Special Attribute is assign, There you can see that Special Product Option has came with yes/no drop down. Now make some product Yes as Special product.

Now go to frontend and write the below code where you want to fetch the Special Product.

$storeId = Mage::app()->getStore()->getId();
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
$categoryProductTable = $resource->getTableName('catalog/category_product');
$productEntityIntTable = (string)Mage::getConfig()->getTablePrefix() . 'catalog_product_entity_int';
$eavAttributeTable = $resource->getTableName('eav/attribute');
// Query database for special product
$select = $read->select()
->distinct()
->from(array('cp'=>$categoryProductTable),'cp.product_id')
->join(array('pei'=>$productEntityIntTable), 'pei.entity_id=cp.product_id', array())
->joinNatural(array('ea'=>$eavAttributeTable))
->where('pei.value=1')
->where('ea.attribute_code="special"');// Write your attribute code instead of Special
$rows = $read->fetchAll($select);
// Save all product Id which have the Special Product Yes
foreach($rows as $row)
{
$product[] =$row['product_id'];
}

Inside the $product variable you have all product Id which are Special Product . Now write the Below code to get Details of the Each product

<ul>
<?php foreach($product as $key=>$val)
{
$productobject = Mage::getModel('catalog/product');
$productmodel = $productobject->load($val);
echo "<li>";
echo "<h2>".$productmodel->getName()."</h2>";
echo "<a href=".$productmodel->getProductUrl()."><img src=".$productmodel->getImageUrl()."title=".$productmodel->getName()."/></a>";
echo "<p>".$productmodel->getDescription()."</p>";
echo "<p>".$productmodel->getFinalPrice()."</p>";
?>
<input type="button" value="<?php echo $this->__('Add to Cart') ?>" onclick="setLocation('<?php echo Mage::getUrl('checkout/cart/add', array('product'=>$val,'qty'=>1)) ?>')" />
<?php
echo "</li>";
?>
</ul>

You can see all the Special Product has come to your frontend. By this way you can make Feature Product or Hot Product . Enjoy..............

3/20/2011

How to add new tab under system configuration in magento

In the last post I have showned , how to add new Tab in magento admin panel. Now in this post I will add new Tab under System->Configuration.To add so, You need to create a new module. Click here to create an admin Module then make some changes which is written here.

create a system.xml file inside etc folder of your module, Then write the following code to add a tab


<?xml version="1.0"?>
<config>
    <tabs>
        <systab translate="label" module="systab">
            <label>System Configuration Tab</label>
            <sort_order>200</sort_order>
        </systab>
    </tabs>
    <sections>
        <systab translate="label" module="systab">
            <class>separator-top</class>
            <label>My system Configuration Tab</label>
            <tab>systab</tab>
            <sort_order>100</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <systab_option translate="label">
                    <label>sysem Tab Options</label>
                    <frontend_type>text</frontend_type>
                    <sort_order>10</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
<registration_mode translate="label"> <label>On New User Signup</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </registration_mode>
<forget_mode translate="label">
                            <label>Send Email on Forget Password</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </forget_mode>
<purchase_mode translate="label">
                            <label>Send Email On Product Purchase</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </purchase_mode>
                    </fields>
</systab_option>
            </groups>
        </systab>
    </sections>
</config>

Now important things which needs to do. Go to your System->Cache Management then clear your all cache. Now go to System->Permissions->Roles. Clcik on Administrators, from Role Resources Tab select Resource Access All from the drop down and save. Now go to System ->Configuration .You can see a new tab has added in the left side.

3/19/2011

How to adding new menu in magento admin panel

Here I have Created a new Module to Add new tab in admin panel of magento.
My Namesapce Name is Anjan and My Module name is Systab
As you know to make a module first we need to make a .XML file with Namespace_Module name under app/etc/modules/ folder. So My File name will be Anjan_Systab.xml

Now I will write the following code inside this xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Anjan_Systab>
            <active>true</active>
            <codePool>local</codePool>
        </Anjan_Systab>
    </modules>
</config>

As My CodePool is local which is written in Anjan_Systab.xml I will create a Folder with name Anjan inside app/code/local/, then again will create another folder with name Systab inside Anjan Folder.Now I will create an etc folder inside the Systab Folder. Inside the etc folder I will create config.xml and will write the following code

<?xml version="1.0"?>
<config>
    <modules>
        <Anjan_Systab>
            <version>0.1.0</version>
        </Anjan_Systab>
    </modules>
    <frontend>
        <routers>
            <systab>
                <use>standard</use>
                <args>
                    <module>Anjan_Systab</module>
                    <frontName>systab</frontName>
                </args>
            </systab>                        
        </routers>
        <layout>
            <updates>
                <systab>
                    <file>systab.xml</file>
                </systab>
            </updates>
        </layout>
    </frontend>
    <admin>
        <routers>
            <systab>
                <use>admin</use>
                <args>
                    <module>Anjan_Systab</module>
                    <frontName>systab</frontName>
                </args>
            </systab>
        </routers>
    </admin>
    <adminhtml>
        <menu>
            <systab module="systab">
                <title>My Tab</title>
                <sort_order>71</sort_order>
                <children>
                    <items module="systab">
                        <title>Manage Profile</title>
                        <sort_order>0</sort_order>
                        <action>systab/adminhtml_systab</action>
                    </items>
                </children>
            </systab>
        </menu>
        <acl>
            <resources>
                <all>
                    <title>Allow Everything</title>
                </all>
                <admin>
                    <children>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <systab>
                                            <title>System Configuration Tab</title>
                                        </systab>
                                    </children>
                                </config>
                            </children>
                        </system>
                        <Anjan_Systab>
                            <title>System Configuration Tab</title>
                            <sort_order>10</sort_order>
                        </Anjan_Systab>
                    </children>
                </admin>
            </resources>
        </acl>
        <layout>
            <updates>
                <systab>
                    <file>systab.xml</file>
                </systab>
            </updates>
        </layout>
    </adminhtml>
    <global>
        <models>
            <systab>
                <class>Anjan_Systab_Model</class>
                <resourceModel>systab_mysql4</resourceModel>
            </systab>
            <systab_mysql4>
                <class>Anjan_Systab_Model_Mysql4</class>
                <entities>
                    <systab>
                        <table>systab</table>
                    </systab>
                </entities>
            </systab_mysql4>
        </models>
        <resources>
            <systab_setup>
                <setup>
                    <module>Anjan_Systab</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </systab_setup>
            <systab_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </systab_write>
            <systab_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </systab_read>
        </resources>
        <blocks>
            <systab>
                <class>Anjan_Systab_Block</class>
            </systab>
        </blocks>
        <helpers>
            <systab>
                <class>Anjan_Systab_Helper</class>
            </systab>
        </helpers>
    </global>
</config>

Now Clear your magento cache and login to you admin panel You can see one Tab Named My Tab has been successfully created.

3/15/2011

How to get customer First Name, Last Name , Email Address or Details in magento

Before geting the details of a customer you must to have check whether Customer is Logged in or not, If a customer is logged in then only you can get details fo the customer. To check whether user logged in or not click here or you can go to http://xhtmlandcsshelp.blogspot.com/2010/11/magento-check-if-user-logged-in-or-log.html to get the code. Then write the code below to get customer details

$customer = Mage::getSingleton('customer/session')->getCustomer();
$email = $customer->getEmail();// To get Email Id of a customer
$firstname = $customer->getFirstname();// To get Firstname of a customer
$lastnam e= $customer->getLastname();// To get Last name of a customer

3/09/2011

How to Remove Product from cart on checkout page or by coding in magento

From magento cart you can delete product by clicking on delete button from cart page , but if you wish to delete any cart item in checkout page or by coding then you have write

$session= Mage::getSingleton('checkout/session');
$quote = $session->getQuote();

$cart = Mage::getModel('checkout/cart');
$cartItems = $cart->getItems();
foreach ($cartItems as $item)
{
    $quote->removeItem($item->getId())->save();
}

By writing the above code your all cart item will be delete.If you wish to delete a particular product from the cart session then instead of writing $item->getId() pass your Id of the product.

e.g: - foreach ($cartItems as $item)
{
    if($item->getId()== 2)
    {
        $quote->removeItem($item->getId())->save();
    }
}

How to get all cart items from cart session in magento

This is one of the most usefull features for all magento developers.As it's very necessary while anybody working on Magento cart or checkout page.To get all cart item from cart session write the below code

$session= Mage::getSingleton('checkout/session');
foreach($session->getQuote()->getAllItems() as $item)
{
   $productid = $item->getProductId();
   $productsku = $item->getSku();
   $productname = $item->getName();
   $productqty = $item->getQty();
}

How to get shopping cart session in magento

While working on Cart page or checkout page, if you want to get the cart session value then You have to use this code in magento

$session= Mage::getSingleton('checkout/session');

2/28/2011

How to get Magento Format Price with default currency symbol

Whenever we fetch all data of a product by using either product sku or by using product id, Price also we need . But if we fetch product price then it display price as number format without any currency . So if you want to fetch price like magento price format then you have to pass your price variable in the following code then you can get the dynamic currency also.

Let you got your price by

$price = $_Pdetails->getPrice();
// To fetch price like magento format price write
$magento_style_price = Mage::helper('core')->currency($price);

How to get product details using product sku in magento

If you know your product SKU you can get details of that products, e.g- you can get Product Id, Product Name, Product Description, Product Price etc.
To get details fo the product by sku please write the below code

$products = Mage::getModel('catalog/product')
$_Pdetails = $product->loadByAttribute('sku', 'product-sku');

or

$_Pdetails =
Mage::getModel('catalog/product')->loadByAttribute('sku','product-sku');

echo $_Pdetails->getName();
echo $_Pdetails->getDescription();
echo $_Pdetails->getPrice();
echo $_Pdetails->getProductUrl();

2/21/2011

How to get absolute path of base directory in magento

While uploading a file in magento It's necessary to write the absolute path of your magento path, otherwise it will not upload. you can get your site absolute path from php.ini file, You can place this path by hardcording but later if you think to move your site to another host then the path will be change, So to make your absolute path dynamic or get the proper path in which your magento Installed, write the following code

<?php echo Mage::getBaseDir('media') . DS ;?>

It will definately work,

2/18/2011

How to get access of magento core functions from outside the magento directory

This is the very important thing in magento while accessing data from outside of the magento, You also can use it to set cron job of any magento function, as cron job doen't work properly in magento.


require_once 'app/Mage.php'; // if your are not root folder then write the proper path like publichtml/magento/app/Mage.php
Mage::app('default');

Now you can create object of any classes and can access methods of those classes also.
Like the Below example

$obj = new Mage_Checkout_Model_Observer();
echo $obj->salesQuoteSaveAfter();

2/17/2011

Fix for Magento Admin Login not working on Localhost

When you want to install magento in your local machine by either wamp server or by Xamp server then you will face a problem, while logging into magento admin panel, after successfull install.
Here are the fix to logging into magento.This fix work above Magento version 1.4.1
Go to the location app/code/core/Mage/Core/Model/Session/Abstract/ and open Varien.php then go to line number 86. There you will find the below code. if (!$cookieParams['httponly']) {
unset($cookieParams['httponly']);
if (!$cookieParams['secure']) {
unset($cookieParams['secure']);
if (!$cookieParams['domain']) {
unset($cookieParams['domain']);
}
}
}
if (isset($cookieParams['domain'])) {
$cookieParams['domain'] = $cookie->getDomain();
}

Comment this code, then your code will look like this


/* if (!$cookieParams['httponly']) {
unset($cookieParams['httponly']);
if (!$cookieParams['secure']) {
unset($cookieParams['secure']);
if (!$cookieParams['domain']) {
unset($cookieParams['domain']);
}
}
}

if (isset($cookieParams['domain'])) {
$cookieParams['domain'] = $cookie->getDomain();
}*/

Save the file and Refresh your admin panel page and try to login once again , Now you will be able to login to your Admin Dashboard

2/15/2011

How to configure multiple websites with multiple domain in a single magento

This is One of Magento's best and popular features of magento which allows to run Multiple website with multiple domain name in a single magento.To conigure multiple website or multiple domain Follow the below process.

Create 2 or more website, Store and storeview from System-> Manage Stores

See the below screenshot

Now go to System->Configuration->Web
From Current Configuration Scope: Select your first website i.e website1. Then from Unsecure tab change your Base URL from {{base_url}} to your domain name (e.g http://www.n2ndevelopers.com/)
Do the same for Website2 and website3 by selecting website2 and website3 From Current Configuration Scope:
Below 3 screenshot shows how to do this








Now open your magento Index.php file which you will found in your magento rrot folder. open it and comment the below code

$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';
Mage::run($mageRunCode, $mageRunType);

And paste the below code

switch($_SERVER['HTTP_HOST']) {
case 'website1.com':
Mage::run('website1', 'website');
/* website1 is the code you wrote in the admin when created the website */
break;
case 'website2.com':
Mage::run('website2', 'website');
break;
case 'website3.com':
Mage::run('website3', 'website');
break;
default:
Mage::run();
break;
}

and Enjoy

How to get all product details or product Id's with respect to individual or each store view in magento

To get all product Id's with respect to each store view, write the below code. $storeId    = Mage::app()->getStore()->getId();
$product    = Mage::getModel('catalog/product');
$products   = $product->getCollection()->addStoreFilter($storeId)->getData();
This will fetch all product details of current store. If u change store it will show different product

1/12/2011

How to generate google sitemap.xml manually in magento

To generate Sitemap.xml in magneto ,Login to your admin panel of your site. Then goto Catalog -> Google Sitemap. Click on Add sitemap then give sitemap.xml in the field of Filename then in the field of Path give your path foldername ( If you wish to save the sitempa.xml in your root folder then use " / " sign). Then click on Save&Generate button to generate your sitemp.xml . then type www.yoursite.com/sitemap.xml to see your sitemap(If you have not use any folder).Submit this sitemap to Google or Bing to see your site in search engines.

1/06/2011

how to remove .html from category and product url in magento

By Default magento's all category url and product url comes with .html extension.If you want to remove the .html extension from all category url and product url, then Follow the below step.

Login to your magento admin panel then Go to System->Config ->Catalog. From Search Engine Optimizations tab delete ".html" from Product URL Suffix and Category URL Suffix, and save config. Now goto System->Index Management and Reindex All data. Now clear your cache. You can see that all .html has been removed.

1/05/2011

How to get sub category list of a particular category in magento

To get all subcategory list under a particular category you need to know the category id of that particular id, then you can get the subcategory .In the below example I have taken My category id is 69.

<?php
$category = Mage::getModel('catalog/category')->getCategories(69);
foreach($category as $_category){
$currentCat = Mage::getModel('catalog/category')->load($_category->getId());
?>
<li><a href="<?php echo $currentCat->getUrl()?>"><?php echo $currentCat->getName();?></a></li>
<?php
}
?>

How to get all Sub-category list by a main category Id in magento

How to see all category and subcategory menu in Magento

By default there is a top.phtml file in magento which show all category and subcategory .To modify menu display style it needs to modify in core file whcih will create problem to Update magento in future,So without touching the core file we can access all category and subcategory in magento.
For that we will write the code in top.phtml file

<?php foreach ($this->getStoreCategories() as $_category): ?>
<li>
<a href="<?php echo $this->getCategoryUrl($_category) ?>"><?php echo $this->htmlEscape($_category->getName()) ?></a>
<?php
$_catid=$_category->getId();
$category = Mage::getModel('catalog/category')->load($_catid);
$subcategory = $category->getAllChildren(true);
array_shift($subcategory);
if($subcategory!=null)
{?>
<ul>
<?php
foreach ($subcategory as $sub)
{
$sub1 = Mage::getModel('catalog/category')->load( $sub);
?>
<li><a href="<?php echo $sub1->getUrl();?>"><span>
<?php echo $sub1->getName(); ?>
</span></a></li>
<?php } ?>

</ul>
<?php }?>

</li>
<?php endforeach ?>

1/03/2011

How to get Current currency code or symbol in magento

To get Current currecy code in magento, write the following code.

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

To get Current currecy symbol in magento , write the following code.

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