Saturday 16 July 2011

Magento Load Product By Name / SKU / ID

// Load by name
$_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'Ruby Ring');
$_product = Mage::getModel('catalog/product')->loadByAttribute('name', 'emerald earring');

// Load by SKU
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'Eram18j4');

//Load by ID (just load):
$_product = Mage::getModel('catalog/product')->load($productID);

How To Upload File In Magento

if (isset($_FILES['logo']['name']) && $_FILES['logo']['name'] != '') {
    try {
        $uploader = new Varien_File_Uploader('logo');
        $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
        $uploader->setAllowRenameFiles(false);
        $uploader->setFilesDispersion(false);
        $path = Mage::getBaseDir('media') . DS;
        // $path = Mage::getBaseDir('media') . DS . 'logo' . DS;
        $logoName = $_FILES['logo']['name'];
        $uploader->save($path, $logoName);
  
    } catch (Exception $e) {
  
    }
}

Friday 15 July 2011

Magento Reindexing Problem Fixing programmability

When  ever  number of products  increased it get tuff to reindex all data it get more worse if you are on shared host. Now you can solve this issues with the code given below.

Create new file on your root i.e. reindex.php and copy all data given below and paste it in reindex.php
now you can start reindex data by just accessing URL like http://yourdomain.com/reindex.php

try{
 ob_implicit_flush(true);
 if(!ini_get('safe_mode')){set_time_limit(0);}
 ignore_user_abort(); 
 require_once("app/Mage.php");
 Mage::app('admin'); 
 Mage::setIsDeveloperMode(true);
 umask(0);
 
 
 $HM = 800; 
 $STOREID = '1'; 
 $HOWTORUN = 1; 
 
 
  $total = NULL;
  if($HOWTORUN == 1)
  {
  
   $prodCount = "cm_pd";
   if((file_exists($prodCount))&&(filesize($prodCount)>1)){
$fh = fopen($prodCount, 'r');
$total = fread($fh,filesize($prodCount)) + 1;
fclose($fh);
}
else
{
$fh = fopen($prodCount, 'w') or die("can't open file");

$tmpIDs = Mage::getModel('catalog/product')->getCollection()->getAllIds();

$total = $tmpIDs[sizeof($tmpIDs)-1]; //-1 Accounts for 0 in array.

fwrite($fh, $total);
fclose($fh);
}

}
else
{

if((!isset($_SESSION['pcount']))||($_SESSION['pcount']==NULL)){ 
$tmpIDs = Mage::getModel('catalog/product')->getCollection()->getAllIds();
$endValue[sizeof($tmpIDs)-1]; 
$_SESSION['pcount'] = $endValue;
$total = $_SESSION['pcount'];
}
else{ $total = $_SESSION['pcount']; }

}
if($total == NULL){ throw new Exception("Total Wasn't Captured"); }


echo("\n$total\n");

$countFile = "cm_cnt";
$count = null;
$store = Mage::app()->getStore($STOREID);


if((file_exists($countFile))&&(filesize($countFile)>1)){
$fh = fopen($countFile, 'r');
$count = fread($fh,filesize($countFile)) + 1;
fclose($fh);
if((int)$count == 0) $count = 1;
}
else
{
$fh = fopen($countFile, 'w') or die("can't open file");
$count = 0;
if((int)$count == 0) $count = 1;
fwrite($fh, $count);
fclose($fh);
}



if($count < 2)
 {
   Mage::app()->cleanCache();

$flag = Mage::getModel('catalogindex/catalog_index_flag')->loadSelf();
if ($flag->getState() == Mage_CatalogIndex_Model_Catalog_Index_Flag::STATE_RUNNING) $flag->delete();
}

$max = ($count+$HM);
$sx = Mage::app()->getStore('1');

ob_start();
for($i = $count; $i <= $max; $i++)
 {
 ob_end_flush();
 ob_start();
    if($i == $total)
    {
      echo "

Completed

"; @unlink($prodCount); @unlink($countFile); exit(1); } Mage::getSingleton('catalogindex/indexer')->plainReindex($i, null, $sx); echo("\n #Record $i#CURRENT MEMRY USAGE = ".memory_get_usage().";\n"); $fh = fopen($countFile, 'w') or die("can't open file"); fwrite($fh, $i); fclose($fh); ob_flush(); flush(); } }catch(Exception $e){ echo"

ERROR: $e

"; exit(1);} #EOF ?>

Saturday 9 July 2011

Magento 'Shop By Brand' in SideBar

First create the template file and name it productbrand.phtml place it in catalog/product folder

copy the code given below and paster it in you productbrand.phtml

Note: Please chnage 'yourdomain.com' with your site domain name

<div>
<div>
<h4>
<span>Product Brands</span></h4>
</div>
<div style="padding-left:8px;">

<?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="http://www.yourdomain.com/catalogsearch/advanced/result/?manufacturer[]=<?php echo $manufacturer['value'] ?>"><?php echo $manufacturer['label'] ?></a>
</li>
<?php endforeach; ?>   </ul>
</div>
<div>
</div>
</div>

Friday 8 July 2011

Create Customer By Code In Magento

Creating customer programmaticaly is easy just use the code below.

$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
 
//$customer = new Mage_Customer_Model_Customer();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId; 
$customer->setStore($store);
 
$customer->firstname = "vikram";
$customer->lastname = "singh";
$customer->email = "singh@yourdomain.com";
$customer->password_hash = md5("password");
$customer->save();

Wednesday 6 July 2011

Change Admin URL In Magento

Its easy to change admin URL in Magneto, open local.xml at location below,
/app/etc/local.xml
now search for the code below

now replace 'admin' with your desired name.

as you do so your admin URL will be changed to adminarea

Magento Display Category BestSellers

 $curr_categoryid = Mage::registry('current_category')->getId();
$cat_Id= $curr_categoryid; 
 
$category = Mage::getModel('catalog/category')->load($cat_Id);
 
$products = Mage::getResourceModel('reports/product_collection')
        ->addOrderedQty()
        ->addAttributeToSelect('*')
        ->setOrder('ordered_qty', 'desc')
        ->addCategoryFilter($category);

Monday 4 July 2011

Display GrandTotal Of Shopping Cart in Magento

getQuote();
$total = $quote->getGrandTotal();
$total = $this->helper('checkout')->formatPrice($total); 

Remove Compare Products From Magento Sidebar

It is easy to remove compare products from magento sidebar. Just browser to location given below.
app/design/frontend/default/default/layout/catalog.xml
then search the tag below and remove it, compare products will be removed from magento sidebar

Thursday 30 June 2011

Send Every Store Activity Email To Store Owner In Magento

We can do this by editiing Templete.php file at the location given below
app\code\core\Mage\Core\Model\Email
search for code below
$this->setSentSuccess($this->send($email, $name, $vars));
and just below the searched code paste the code given.
$this->setSentSuccess($this->send('owner@store.com', $name, $vars));
now every email that shoots from Magento store it will deliverd to owner also.

Get Customer GroupId in Magento

firstly you need to check if customer is loged in or not
$logged_in = Mage::getSingleton( 'customer/session' )->isLoggedIn();
now use the code below to check CustomerGroupID
$group = Mage::getSingleton('customer/session')->getCustomerGroupId();

Magento Custom Form With Notification

Step1: you need to creat a XML file same at location given below, if folder does not exist please create it
/app/etc/modules/MageWorks_Contact.xml
and paste the content below in MageWorks_Contact.xml
 
    
        
            true
            local
        
        

Step 2: Now create Confix.xml at the location below
app/code/local/MageWorks/Contact/etc/config.xml 
and paste the content below to config.xml file
 

    
        
            0.1.0
        
       
 
    
        
            
                standard
                
                    MageWorks_Contact
                    MageWorks_Contact
                
            
        
        

Step 3: Now create controller at the folloing location
app/code/local/MageWorks/Contact/controllers/IndexController.php
now paste the content below to controller
class MageWorks_Contact_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        //Get current layout state
        $this->loadLayout();   
 
        $block = $this->getLayout()->createBlock(
            'Mage_Core_Block_Template',
            'mageworks.contact',
            array(
                'template' => 'mageworks/contact.phtml'
            )
        );
 
        $this->getLayout()->getBlock('content')->append($block);
        //$this->getLayout()->getBlock('right')->insert($block, 'catalog.compare.sidebar', true);
 
        $this->_initLayoutMessages('core/session');
 
        $this->renderLayout();
    }
 
    public function sendemailAction()
    {
        //Fetch submited params
        $params = $this->getRequest()->getParams();
 
        $mail = new Zend_Mail();
        $mail->setBodyText($params['comment']);
        $mail->setFrom($params['email'], $params['name']);
        $mail->addTo('somebody_else@example.com', 'Some Recipient');
        $mail->setSubject('Test MageWorks_Contact Module for Magento');
        try {
            $mail->send();
        }        
        catch(Exception $ex) {
            Mage::getSingleton('core/session')->addError('Unable to send email. Sample of a custom notification error from MageWorks_Contact.');
 
        }
 
        //Redirect back to index action of (this) mageworks-contact controller
        $this->_redirect('mageworks-contact/');
    }
}
 
Step 4: Create view
app/design/frontend/default/default/template/mageworks/contact.phtml
paste content below to contact.phtml

MageWorks_Contact module sample












  •  



* Required Fields

Tuesday 28 June 2011

Get Nicely Formated Final Price In Magento


$_coreHelper = $this->helper('core');
$_taxHelper = $this->helper(’tax’);
$_finalPriceInclTax = $_taxHelper->getPrice($_product, $_product->getFinalPrice(), true);
$_finalPriceFormated = $_coreHelper->currency($_finalPriceInclTax,true,false);
echo $_finalPriceFormated;

Magento Image Switcher On MouseOver

Step1. open file on location given below

app/design/frontend/default/default/template/catalog/product/view/media.phtml

Step2. Search the code in media.phtml file
<a href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'width=300,height=300,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;">
   <!--nested img tag stays the same-->
</a>

Step 3. Replace searched code with code below.

<a href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()); ?>" title="<?php echo $_product->getName();?>" onmouseover="$('image').src = this.href; return false;">
   <!--nested img tag stays the same-->
</a>

Sunday 26 June 2011

How To Set Magento Base Currency Programmatically

open index.php on root and paste the code
Mage::app()->getStore()->setCurrentCurrencyCode('USD');

just above this code

Mage::run($mageRunCode, $mageRunType);

Magento LogIn with Facebook Account extension

Step 1.

Create Facebook App.

For Facebook Connect to work you need to Setup Application on Facebook and obtain its API Key and Application Secret.

Use your store name as application name and read and accept terms of service. On second screen switch to Web Site tab and set Site URL to the store domain where you plan to implement Facebook Connect. Save Changes. Other Connect settings are optional, but you might want to add store logo for example.

Step 2.
Download extension from link below:
Works_Facebook_Login
unzip folder and copy app folder from Works_Facebook_Login and paste it to you magento folder it will ask to overwrite click ok.

Step 3.
Magento Setup

Once you obtain two keys navigate to Magento Administration, copy/paste them to appropriate fields under Configuration->Customer->Facebook Connect, set Enabled to Yes and you’re good to go. If you’re updating from previous releases, you also need to Enable it to work.

Default template files (frontend/default/default/template/facebook/*) and layout (layout/facebook.xml) makes Facebook Connect work out of the box with default theme, but we tried to make customizations as easy as possible so all you need to do is add button or link with “facebook-connect” rel attribute set anywhere in the theme, static block or cms page, for example:

<button rel=”facebook-connect” class=”form-button” type=”submit”><span>Connect with Facebook</span></button>
<a rel=”facebook-connect”>Connect with Facebook</a>

Friday 24 June 2011

Fixing Magento Catalog Price Rules Issue

To solve this issue, edit Cron.php (in the root installation directory).

try {
Mage::getConfig()->init()->loadEventObservers(’crontab’);
Mage::app()->addEventArea(’crontab’);
Mage::dispatchEvent(’default’);
$observ = Mage::getModel(’catalogrule/observer’);
$observ->dailyCatalogUpdate("0 1 * * *");

Moving Magento From One Host To Another

1. take buckup of your database
2. take backup of your files.
3. create new database on your new host
4. save your database and password of your database
5. open local.xml in magento folder on path app\etc change infomation of  previous database with new.

         <connection>
                    <host><![CDATA[localhost]]></host>
                    <username><![CDATA[username]]></username>
                    <password><![CDATA[password]]></password>
                    <dbname><![CDATA[databasename]]></dbname>
                    <active>1</active>
                </connection>
6. upload all your files to you new host.
7. go to you new host database open table `core_config_data` change the value of your old host name with new host name

example:

Before Changing Host

               config_id     scope  scope_id    path                           value
    Edit     Delete     2     default     0     web/unsecure/base_url     http://localhost/oldhost/
    Edit     Delete     3     default     0     web/secure/base_url     http://localhost/oldhost/

After Changing Host

               config_id     scope  scope_id    path                           value
    Edit     Delete     2     default     0     web/unsecure/base_url     http://localhost/newhost/
    Edit     Delete     3     default     0     web/secure/base_url     http://localhost/newhost/

Thursday 23 June 2011

Running Custom SQL Query in Magento.

As i explained previously that magento works on EAV model so, when ever custom sql query has been executed, It must be checked that the result must be combination of one to more tables.
<?php
// fetch read database connection that is used in Mage_Core module
$read= Mage::getSingleton('core/resource')->getConnection('core_read');
$value=$read->query("SE...");
$row = $value->fetch();

print_r($row); // As Array

// For Write

// fetch write database connection that is used in Mage_Core module
$write = Mage::getSingleton('core/resource')->getConnection('core_write');

// now $write is an instance of Zend_Db_Adapter_Abstract
$write->query("insert into tablename values ('magento','cool','work')");

?>

Wednesday 22 June 2011

Display All Product Attribute in Mageto Shopping Cart

Open the location given below
note: path can differ according to templete

app\design\frontend\base\default\template\checkout\cart\item\default.phtml


use the Code below in default.phtml.

<?php
     $product = Mage::getModel('catalog/product')->load($this->getProduct()->getId());
    $attributes = $product->getAttributes();
   
    foreach ($attributes as $attribute) {
        if ($attribute->getIsVisibleOnFront() && $attribute->getIsUserDefined()) {
            $value = $attribute->getFrontend()->getValue($product);
            if (strlen($value) && $product->hasData($attribute->getAttributeCode())) {
                $data[$attribute->getAttributeCode()] = array(
                    'label' => $attribute->getFrontend()->getLabel(),
                    'value' => $value //$product->getData($attribute->getAttributeCode())
                );
?>
    <span style="font-weight:bold;"><?php echo $data[$attribute->getAttributeCode()]['label']; ?></span>: <span><?php echo $data[$attribute->getAttributeCode()]['value']; ?></span>
<?php
            }
        }
    }
?>

Magento Methods getModel(), getData()

getModel()

The getModel() function is used to create an instance of a Model class.
For example: $Product = Mage::getModel(’catalog/product’);
this tells magento to create instance of  Mage_Catalog_Model_Product class
Some useful methods include getName, getPrice, getTypeId, getStatus which we can execute like
<?php echo ‘Name: ‘. $Product->getName();?>
<?php echo ‘Price: ‘ . $Product->getPrice();?>
getData()



This function is used to get relevant data from the object instance. Let’s say you want to retrieve the SKU value. You can use some other method for that like getSku() method that needs to be executed on object of Product type or you can:

Example:
$min_sale_qty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct())->getData('min_sale_qty');

Change Color of “Availability :In stock” Product Page In Magento

There are different type of view type available in magneto for every type of products in my case i am using default type you can get all view type file at one location path given below.

Note: path and file may vary according to product type

app/design/frontend/base/default/template/catalog/product/view/type/default.phtml

Find the line below:
<p class="availability in-stock"><?php echo $this->__('Availability:') ?> <span><?php echo $this->__('In stock') ?></span></p>

and change class with inline css as given below

<p style="color:#00ff00"><?php echo $this->__('Availability:') ?> <span><?php echo $this->__('In stock') ?></span></p>

Tuesday 21 June 2011

Magento Single Page Checkout Extension

EasyCheckout is an extension which will convert your checkout page as you see in image you can download it from a link:

https://rapidshare.com/files/341090454/EasyCheckout.zip

Installation steps are given in install.txt file inside zip.

Contact this blog if you have any query...

Display Featured Product Radomly on Magento HomePage


Create new file homepage.phtml and copy content from list.phtml to homepage.phtml, log in to your magento admin go to cms pages click home page
paste step1 to contect area. click save.

strp 1.

{{block type="catalog/product_list"  category_id="93" template="catalog/product/homepage.phtml"}}


now open  hopepage.phtml use the code below to randomly display 4 product at once

step 2.
<?php
$_productCollection=$this->getLoadedProductCollection();
$_helper = $this->helper('catalog/output');
    if ($_productCollection->count()):
    $_productCollection = $_productCollection->getItems();
    shuffle($_productCollection);
    $i = 0;
             foreach ($_productCollection as $_product):
        if ($i < 4):
                             // Product Data With CSS
        endif;
    $i++;
     endforeach;
    endif;

?>

Monday 20 June 2011

Get All Products Reviews On CMS Page In Magento

Create on phtml file in catalog/product/review.phtml, Place the code below in review.phtml
$collection = Mage::getModel('catalog/product')->getCollection();
foreach ($collection as $product)
{
        //var_dump($product);
$storeId    = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')
->setStoreId($storeId)
->load($product->getData('entity_id'));
}

Now create CMS Page in mageto backend and call it as shown below in content section of your CMS page

{{block type="core/template" name="review"  template="catalog/product/review.phtml"}}
and you are done just check it http://yoursite/review.html

Speedup Your Magento Site

its possible to make your magento site fast by following steps below

1. first  we need to update .htaccess file on root. this code below activate Gzip compression.

## http://developer.yahoo.com/performance/rules.html#gzip
    
    # Insert filter
    SetOutputFilter DEFLATE
    
    # Netscape 4.x has some problems_
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    
    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4.0[678] no-gzip
    
    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch bMSIE !no-gzip !gzip-only-text/html
    # Don’t compress images
    SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
    
    # Make sure proxies don’t deliver the wrong content
    Header append Vary User-Agent env=!dont-vary
    
    # enable resulting html compression
    php_flag zlib.output_compression on

2. secoundly we need to save all products and category as 'FLAT RESOURCE'

    a. go to system->configration->catalog->frontend
    b. Use Flat Catalog Category, Use Flat Catalog Product you will see these 2 option at the end, Select Both to Yes.
    c. reindex all data from Index Management.

Display Magento Available Quantity in DropDown on list.phtml

 <select name="qty">
  <?php $i = 1 ?>
  <?php do { ?>
    <option value="<?php echo $i?>">
      <?php echo $i?>
      <?php $i++ ?>
    </option>
    <?php } while ($i <= (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()) ?>
</select>

Or try this


Set min_sale_qty of a product in backend, go to product inventory tab and find 'Minimum Qty Allowed in Shopping Cart' put desarable quantity there, we have to do this because we have to give equal interval between quantity in dropdow.

note: path can differ according to templete

app\design\frontend\base\default\template\checkout\cart\item\default.phtml

found quantity text box in that file and replace it with code below.

<?php $min_sale_qty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct())->getData('min_sale_qty');
    $total_qyt = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct())->getQty();
     ?>
    <select name="cart[<?php echo $_item->getId() ?>][qty]">
    <?php for($i = $min_sale_qty; $i <= $total_qyt; $i = $i + $min_sale_qty)
      {
      ?>
    <option value="<?php echo $i?>">
      <?php echo $i?>
    </option>
   <?php }?>
   </select>

Sunday 19 June 2011

Magento Flat Table Option Of Saving Products

Magento stores product data in EAV model i.e. entity attribute value model, This make the magento site slow as in EAV model single table is divided in parts which makes data fetching slow, now in magento 'Magento ver. 1.5.0.1' we have option to save product as Flat resource.

Magento Advance Layer Navigation

Magento Extension to convert magento layerd navigation to ajax layer navigation, download it from the link below, this is free version.
Features:
              1. multiple select filter with ajax layer navigation
              2. SEO link .
              3. Back end Configuration
              4. three option to display price
Installation:
              1. copy app and skin folder and paste it to you magento folder it will ask to overwrite all file select ok, it will not replace your existing file but it will create requried files for AdvLay extension.
              2. remove all cache from var folder.
and you are done with it.

https://rapidshare.com/files/817619639/AdvLay.rar

Saturday 18 June 2011

Disabling Magento Extension Manually

Some time we need to disable extension manually, its easy to do as as every magento extension create its XML file in 'app\etc\modules' folder like our extension name is 'AdvLay_Nav' so it will create file named AdvLay_Nav.xml when u open it you will see code like this

<?xml version="1.0"?>
<config>
    <modules>
        <AdvLay_Nav>
            <active>true</active>
            <codePool>local</codePool>
            <self_name>Advance Layed Navigation</self_name>
            <priority>10120</priority>
        </AdvLay_Nav>
    </modules>
</config>

go to <active> tag edit it to 'false' and clear your magento cache in var folder and you are done.

Friday 17 June 2011

Get Current Category In Magento

<?php Mage::registry('current_category')->getName();?>

Running script out side Magento Folder and Updating Project Database

Place this script 'image.php' out side magento folder and run this with http://yoursite/image.php, this will update all product images if there is no small or thumbnail image.
 It will make first image as thumb and small image.

An example to run script out side magento folder.

<?php
require 'app/Mage.php';
Mage::app();

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
foreach ($products as $product) {
 if (!$product->hasImage()) continue;
 if (!$product->hasSmallImage()) $product->setSmallImage($product->getImage());
 if (!$product->hasThumbnail()) $product->setThumbnail($product->getImage());
 $product->save();
}

Creating Product Maually in Magento

<?php

//$product = Mage::getModel('catalog/product');
$product = new Mage_Catalog_Model_Product();

// Build the product
$product->setSku('sku');
$product->setAttributeSetId('Attribute_id');
$product->setTypeId('simple');
$product->setName('product name');
$product->setCategoryIds(array(9)); # category id's
$product->setWebsiteIDs(array(1)); # Website id
$product->setDescription('Long description');
$product->setShortDescription('Short description');
$product->setPrice(19.99); # producte price   

# Custom created and assigned attributes
$product->setHeight('custom_attribute1_val');
$product->setWidth('custom_attribute2_val');
$product->setDepth('custom_attribute3_val');
$product->setType('custom_attribute4_val');

//Default Magento attribute
$product->setWeight(2.0000);

$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0); # My default tax class
$product->setStockData(array(
    'is_in_stock' => 1,
    'qty' => 20
));

$product->setCreatedAt(strtotime('now'));

try {
    $product->save();
}
catch (Exception $ex) { 
    //Handle the error
}

?>

How to Edit Thank you message for Contact page in Magento

Some time we need to change message on magento contact success, we can do so by following steps go to
'app\code\core\Mage\Contacts\controllers'

search for 'Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));'

or go to line no 112. and change it to according to your requirment...

Limit Number of Images Per Product In Magento

Some time we need to limit number of images for a product in our magento project we can do it
easily with some lines of code. Go to 'app\code\core\Mage\Adminhtml\controllers\Catalog\ProductController.php' and in saveAction find $data = $this->getRequest()->getPost(); under it put these line. and you are done.

$images = Mage::helper('core')->jsonDecode($data['product']['media_gallery']['images']);
       
        if($totalImages = count($images)) {

        $maxPhotoPerProduct = 3;

        if($totalImages > $maxPhotoPerProduct) {
            Mage::getSingleton('core/session')->addError($this->__('Max. number of images per product reached, extra images have been removed'));
        }

        $_allowedImages = array_slice($images, 0, $maxPhotoPerProduct);
        $_POST['product']['media_gallery']['images'] = Mage::helper('core')->jsonEncode($_allowedImages);
    }

Thursday 16 June 2011

Display Static .phtml page from cms backend

First u need to create .phtml file in the folder like 
in example 'catalog/product' then go to magento backend 
and create CMS page set title set layout then in 
content paste the following code "replace your .phtml file path" .
 
{{block type="catalog/product_featured" name="product_featured"
 as="product_featured" template="catalog/product/featured.phtml"}}

Display Image in Magento From Skin Folder

<img src="<?php echo $this->getSkinUrl('images/sitelogo.jpg');?>" 
alt="sitename" />

Magento Check if Customer Loged in or Not

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

if ($_customer) {
// do stuff
}
?>

Remove SID from Magento URL

Open file "app\code\core\Mage\Core\Model\Session\Abstract.php"
find this code 'protected $_skipSessionIdFlag = true;'
replace it with this 'protected $_skipSessionIdFlag = false,'

Get The productID On The Frontend In Magento

<?php echo $_helper->productAttribute($_product$_product->getId(), \'id\'?>

Wednesday 15 June 2011

Displaying Currency in magento with php number_format()

<?php echo number_format($_product->getFinalPrice(),2);?>

Get productID from specific order in Magento

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

base url in magento

we can get the base url of magento site with the code below, 
just place this code anywhere in .phtml file and you will 
get the base url of your magento site.
<?php echo Mage::getBaseUrl(); ?>

Friday 10 June 2011

Magento addAttributeToFilter

Get all product collection with the below code:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('*');
 
Add different types of filters  on collection. example shown below
//  Equal To (eq)
$collection->addAttributeToFilter('status', array('eq' => 1));

//  Not Equal To (neq)
$collection->addAttributeToFilter('visibility', array('neq' => 1));

// Greater Than (gt)
$collection->addAttributeToFilter('price', array('gt' => 3.99));

// Less Than (lt)
$collection->addAttributeToFilter('price', array('lt' => 3.99));

// Greater Than or Equal To (gteq)
$collection->addAttributeToFilter('price', array('gteq' => 4.99));

// Less Than or Equal To (lteq)
$collection->addAttributeToFilter('price', array('lteq' => 4.99));

// Contains (like) - also uses % wildcards
$collection->addAttributeToFilter('sku', array('like' => 'DVD%'));

// Does Not Contain (nlike) - also uses % wildcards
$collection->addAttributeToFilter('sku', array('nlike' => 'ABC%'));

// In Array (in)
$collection->addAttributeToFilter('id', array('in' => array(1,3,12)));

// Not In Array (nin)
$collection->addAttributeToFilter('id', array('nin' => array(1,2,12)));

// Is NULL (null)
$collection->addAttributeToFilter('description', 'null');

// Is Not NULL (notnull)
$collection->addAttributeToFilter('description', 'notnull');

Thursday 9 June 2011

Magento Product Thumbnail Image Switcher

Step:1

go to file media.phtml
'app/design/frontend/default/default/template/catalog/product/view/media.phtml'


step:2
Find the code below
<a href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'width=300,height=300,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;">
  </a>
Replace it with
<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;">
   <!--nested img tag stays the same-->
</a>

Saturday 4 June 2011

getting all top and sub categories in magento


place this code in you top.phtml (\app\design\frontend\base\default\template\catalog\navigation)


<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<div id="navMainWrap">
<?php if (count($_categories) > 0): ?>
<ul id="navMain"><?php foreach($_categories as $_category): ?>
<li class="navLevel1" id="navJewelry">
<a class="navLevel1Link" href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?>
</a>
<?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<div class="navSubWrap">
            <div class="navSub clearFix">
                <ul class="col1 clearFix">
<li><p class="colHead">
Shop by Category</p>
</li>
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>           </ul>
<div class="navSubBnr">
                    <!--<img>-->
</div>
</div>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>   </ul>
<?php endif; ?>
</div>

Wednesday 9 March 2011

Add a CMS Static Block to a page with php in Magento

you can use this code to display content of any cms page Just in place of 'identifier' give the name of the page your want to display.
<?php echo $this->getLayout()->
createBlock('cms/block')->setBlockId('identifier')->toHtml() ?>

Saturday 5 March 2011

get collection of customer all address in magento


Use the following code to retrieve all address of customer with the help of its email id.


<?php
$websiteid = Mage::app()->getwebsite->getid();
$store = Mage::app()->getStore();

$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteid;
$customer->setStore($store);
$customer->loadByEmail("dexte@yahoo.com");
$address = Mage::getModel("Customer/Entity_Address_Collection");
$address->setCustomerFilter($customer);
$addtess->load();
?>

Thursday 3 March 2011

display product in magento with sql in list.phtml file

Place this following code in your  phtml file where you want to display particular category products this will return array of products and you can use this array to display product of particular category.
$sql = “SELECT product_id  FROM catalog_category_product WHERE category_id=57″;
$data = Mage::getSingleton(‘core/resource’) ->getConnection(‘core_read’)->fetchAll($sql);

Happy Coding...