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");