Sunday, September 25

Magento : Image Upload Problem/Issue Magento 1.6

Hi Guys,

I figured out problem occurred with Magento image upload in version 1.6, for that I am posting a thread which can easily short the problem.

1. Download prototype.js version 1.6.0.3

2. Go to Magento/js/prototype – here rename prototype.js with prototype.js.BKP

3. Then copy downloaded prototype.js in Magento/js/prototype

4. In the /app/etc/config.xml file change the initStatements node from:

SET NAMES utf8

to:

SET NAMES utf8; SET FOREIGN_KEY_CHECKS=0; SET UNIQUE_CHECKS=0;

Flush the cache and then you can upload image for products.

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

Hope it Helps... Thanks....

Magento Free shipping on orders over $50

Magento has some stint functionality which are optionally used just like enable free shipping module method on grant total of the order such like free shipping on orders over $50.

1. Login to Admin page go to System > Configuration
2. Under “Sales” on the left, select “Shipping Methods”
3. Select the Free Shipping Tab to open it
4. Set “Enabled” to “Yes”
5. Set “Minimum Order Amount” to the subtotal that must be reached before the “Free Shipping” option is available
6. Click “Save Config” in the upper right.

That’s it. No “Shopping Cart Price Rules” necessary.

Hope it Helps.. Thanks....

How to create an attribute in Magento?

If you need to add a new product attribute in a Magento store you should follow the next steps:

1. Log in to the Magento admin panel
2. Open the “Attributes” page.
3. Click the “Catalog” tab in the Magento admin main menu.
4. Select “Attributes” and click the “Manage Attributes” button. Here you can see all the attributes used in the Magento store. You can click any of them to see their attribute options and change some if needed.
5. Let’s add a new attribute. Click the “Add New Attribute” button. You can see the attribute options page:

- “Attribute Code” field. It is the name of the attribute used by the system. The drop-down menu determines the level at which the values of this attribute are shared.
- “Global” means that the value of this attribute for a given product must be the same throughout your site.
- “Website” option means that the value of this attribute for a given product can vary in different Websites.
- “Store View” means that the value of this attribute for a given product can differ in all Websites and all store views.

Each new product created with this attribute will automatically have this attribute pre-populated with the value you enter here. However, you will always be able to edit the pre-populated value. If you designate the attribute to be a unique value, the value selected or entered for this attribute for each product must be different.
If you require values, you should select a value for this attribute for each product you create. You will not be able to save a product if this attribute is left blank.

Decide which product types will include this attribute. You can specify if this attribute is available in the quick search and in the advanced search. If you opt for “Yes”, a row for this attribute will be created in the “Compare Products” pop-up window. If you select “Filterable” (with results), only the values that correspond to products in that category page will display in the menu.

You can also see the position of the attribute in the layered navigation menu against other filterable attributes.

6. Ok, we’re done with attribute properties and now we can proceed to the “Manage Options” page. Click the “Manage Label/Options” button.

- You can specify the attribute title for each language and for the admin page
- You can add attribute options

7. Specify which attribute value is default
8. Set the attribute options order.
9. When you are done, click the “Save Attribute” button.

Hope it Helps... Thanks....

How to Change the Admin Password in Magento?

For changing the administrator password you should:

1. Log in to your Magento admin panel
2. Select the “System” tab
3. click the “My Account” menu item
4. Here you can see the fields where you can enter your admin password

In case you are not able to log in to your Magento admin panel at all, the admin password can be changed in the database directly.

1. Open your database with the “phpMyAdmin” tool or any other database management tool. And open the “admin_user” table
2. Click the edit icon
3. With that done, type your new password in the value field
4. Note that in the function drop-down menu you should select “MD5″
5. Save the changes

Hope it Helps... Tanks....

How to Add Multiple Products To The Cart Simultaneously

Adding Multiple Products To The Cart Simultaneously

In a previous post I looked at creating a product on the fly and adding it to the cart automatically. However, if you are using Magento without the catalog then when you transfer customers from your catalog to the cart and checkout you may need to create and add multiple products to the cart.

Creating multiple products is fairly straightforward if you use my methodology for creating a single product from the previous post. To add multiple products to the cart, create the products and add the product objects to an array, here I have named it $products.

To then add all of these products to the cart simultaneously use the following code:

<?php
equire_once (‘app/Mage.php’);
Mage::app();
$session = Mage:getModel(‘core/session’, array(‘name’ => ‘frontend’);

// create products here and add the objects to the array $products
$ids = array();

foreach ($products as $product)
{

$ids[] = $product->getID();

}

$cart = Mage::getModel(‘checkout/cart’);
$cart->addProductsByIDs($ids);
$cart->save();

// change to relevant URL for your store!
header(“location: http://localhost/magento/checkout/cart/”);
?>

Hope it Helps... Thanks...

Tips to Creating Magento Products On-The-Fly

Sometimes it’s necessary to create products on-the-fly, typically in situations where there are so many product possibilities that even a configurable product isn’t flexible enough! In such situations the need arises to create products dynamically.

Below is the PHP code to produce a single Magento product and add it to the cart.

<?php
require_once ‘app/Mage.php’;
Mage::app();
[/php] [php]
// instatiate Product
$product = Mage::getModel(‘catalog/product’);

$product->setWebsiteIds(array(1));
$product->setSku(‘rand-sku-’ . rand());
$product->setPrice(rand(100,2000));
$product->setAttributeSetId(4);
$product->setCategoryIds(array(3));
$product->setType(‘Simple Product’);
$product->setName(‘Product Name’.rand(1,200000));
$product->setDescription(‘The Product Description’);
$product->setShortDescription(‘Brief Description’);
$product->setStatus(1);
$product->setTaxClassId(‘2′);
$product->setWeight(0);
$product->setCreatedAt(strtotime(‘now’));

/* ADDITIONAL OPTIONS

$product->setCost();
$product->setInDepth();
$product->setKeywords();

*/

$product->save();

// "Stock Item" still required regardless of whether inventory
// control is used, or stock item error given at checkout!

$stockItem = Mage::getModel(’cataloginventory/stock_item’);
$stockItem->assignProduct($product);
$stockItem->setData(’is_in_stock’, 1);
$stockItem->setData(’stock_id’, 1);
$stockItem->setData(’store_id’, 1);
$stockItem->setData(’manage_stock’, 0);
$stockItem->setData(’use_config_manage_stock’, 0);
$stockItem->setData(’min_sale_qty’, 0);
$stockItem->setData(’use_config_min_sale_qty’, 0);
$stockItem->setData(’max_sale_qty’, 1000);
$stockItem->setData(’use_config_max_sale_qty’, 0);

$stockItem->save(); 
?>

hope it helps... thanks...

How to Use SQL Queries in Magento

Most of time I have spend in finding proper sql queries for magento. And I have come to know that, its very good idea to not to use your personal sql query but use the magento syntax for doing such. Let me give you a good example to do this. We all are aware that we can use normal “is equal” query but have you ever tried to use “not null” ????

Try this syntax with your customization

$yourvariable = $layer->getProductCollection()->addAttributeToFilter(’special_price’,array(‘notnull’=>”));

I have used this to get only those products which has some special price assigned.

Hope it Helps... Thanks

How to upgrade magento to latest version

Magento is vast eCommerce online shopping cart development tool, and magento community and official peoples are keep upgrading with the new version of magento in eCommerce market with new structured development, and everybody wants their should be upgraded with the latest version of magento, and i can say this is not a big job to upgrade if everything is professionally installed.

But you need to aware of few things before upgrading your online store with latest one.

1. Backup your source files.

2. Go to magento backend – Systems >> Tools >> Backup and create backup.

3. You can also create backup using phpmyadmin but it is often getting failed due to time limit in php.ini so just go with System >> tools >> Backup only or else you can dump the magento database using ssh command.

4. Verify the code.

5. You need to confirm if you have done any core hacks in php files of magento MVC structure because on upgradation it will override all the core files of magento and clear your changes and will override with new code.

6. Download all the source code via FTP or control panel.

7. Truncate(remove) cache from /var/cache.

8. Truncate(remove) session from /var/session.

After clearing all above steps just follow below steps to upgrade your magento web store.

1. Just go to you browser and open http://www.yourwebstorename.com/downloader/
2. Access above URL with the user who have all the access over store in nutshell use Administrator.
3. Then just paste the “magento-core/Mage_All_Latest” in the extension install box and just press enter.
4. It will upgrade all the magento core modules automatically.
5. After successfully upgradation just clear your cache and session again.
6. hurrey you are done, :)

Now what if somebody wants to upgrade specific core modules with the latest code.

just use below commands in the extension installation box in http://www.yourmagentostore.com/downloader

>> magento-core/Interface_Adminhtml_Default
>> magento-core/Interface_Frontend_Default
>> magento-core/Interface_Install_Default
>> magento-core/Mage_Core_Adminhtml
>> magento-core/Mage_Core_Modules

Hope it Helps... Thanks....

How to upgrade magento from admin control panel

Magento is a confusing piece of software sometimes, and it’s always best to make backups of anything before you make changes, so that’s the first step in the process.

Go ahead and back up your files and database(s) before you begin. This step is mandatory just in case something goes awry.

You should be able to upgrade via the Magento Connect Manager. This can be found in the System menu in the Magento admin panel.

First, login to your Magento admin panel, then navigate to

System > Magento Connect > Magento Connect Manager

. You’ll need to re-login using the admin account here.

If this is the first time you’re logging into Magento Connect, you’ll need to prepare the downloader by typing

“magento-core/Mage_All_Latest”

in the Extension Key field, and then click on the Install button. Once the initial setup procedure has completed, click on Refresh. This will update a list of currently installed Magento packages.

Next, click the ‘Check for Upgrades’ button. Once complete, any modules available to be upgraded will be highlighted in yellow. Select the “Upgrade to ..” option in the dropdown menu next to each package you are upgrading, OR, to upgrade the entire Magento store, only select Mage_All_Latest,.

I strongly recommend that ‘Clear all sessions after successful install or upgrade’ is enabled to help with the process.

Click on Commit Changes to begin the upgrade. This may take some time, so keep an eye on it. The console with green text at the bottom will display the output of pear. It will let you know when the upgrade is complete. You should simply need to refresh the page to confirm the changes have been made.

To ensure you are running the upgraded version, go back to your Magento admin panel and scroll to the bottom of any page. The version number should be displayed in the middle.

Good luck with the upgrade!

Hope it Helps.. Thanks

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

Here is the detailed steps to move the cart from right sidebar to header

Find the below line in your page.xml file.
<block as="header" name="header" type="page/html_header"> //Near line 70
</block>

Add the below code inside to that block
<block as="topcart" name="cart_sidebar" template="checkout/cart/sidebar.phtml" type="checkout/cart_sidebar">
</block>

Your new code will look like this
<block as="header" name="header" type="page/html_header">
        <block as="topLinks" name="top.links" type="page/template_links">
        <block as="store_language" name="store_language" template="page/switch/languages.phtml" type="page/switch">
        <block as="topMenu" name="top.menu" translate="label" type="core/text_list">
            <label>Navigation Bar</label>
        </block>
        <block as="topContainer" name="top.container" translate="label" type="page/html_wrapper">
            <label>Page Header</label>
            <action method="setElementClass"><value>top-container</value></action>
        </block>
 //new block 
 <block as="topcart" name="cart_sidebar" template="checkout/cart/sidebar.phtml" type="checkout/cart_sidebar">
</block>
</block></block></block>

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

Thats it. You can see the cart sidebar in your header section.

Hope it Helps... Thanks....

How to add 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.

Hope it Helps... Thanks

Saturday, September 17

How to Describing Flat Catalog in Magento

Difference between EAV and Flat Catalog

In EAV database model, data are stored in different smaller tables rather than storing in a single table.

Like,
product name is stored in catalog_product_entity_varchar table
product id is stored in catalog_product_entity_int table
product price is stored in catalog_product_entity_decimal table

EAV database model is used by Magento for easy upgrade and development as this model gives more flexibility to play with data and attributes.

When flat catalog is enabled in Magento then all the above product attributes (id, name, price) are kept in one table named like catalog_product_flat. Then Magento fetches product data from the flat table rather than joining all the other smaller tables.

There are two types of Flat Catalog:
1) Flat Catalog Product
2) Flat Catalog Category

- Flat Categories are recommended for any Magento installation for improved performance.
- Flat Products is designed and recommended for catalogs that have over 1000 SKU’s.

Enable Flat Catalog Category:

- Go to Admin Panel->System->Cache Management->Rebuild Flat Catalog Category
- Go to Admin Panel->System->Configuration->Catalog->Frontend->Use Flat Catalog Category = Yes

Enable Flat Catalog Product:

- Go to Admin Panel->System->Cache Management->Rebuild Flat Catalog Product
- Go to Admin Panel->System->Configuration->Catalog->Frontend->Use Flat Catalog Product = Yes

Remember that, initially the selection list of

Admin Panel->System->Configuration->Catalog->Frontend->Use Flat Catalog Product
OR,
Admin Panel->System->Configuration->Catalog->Frontend->Use Flat Catalog Product

is non-editable. You have to rebuild Flat Catalog from Cache Management. Only then the selection list becomes editable.

Hope it Helps... Thanks...

Tuesday, September 13

How to Change Decimal Point for Price Format in Magento

Sometime you need to play with the price format. magento default add 2 precision format for the price. now if you want to remove precision or want to keep 3 decimal point for price then you need to do following

1) Open /lib/zend/Currency.php file

2) Find 'precision' => 2 near line no. 78

here is the place, you need to change precision decimal

Change 'precision' => 0 if you want to keep 0 decimal


Hope it Helps... Thanks.....

How to Read and Write to the Database in Magento

Here is the script to read and write to the database in magento

READ QUERIES

// Prepare the SQL
$sql = "SELECT * FROM mytable";
// Execute the SQL and return the results in to $getData
$getData = Mage::getSingleton('core/resource')->getConnection('core_read')->fetchAll($sql);
// Parse the results
for($i=0; $i < count($getData); $i++){
    /* your code */
}
WRITE/UPDATE Queries
// $write is an instance of Zend_Db_Adapter_Abstract
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
// Prepare the SQL statement
$sql  = "insert into tablename values (?, ?, ?)";
// Execute the SQL
$write->query($sql);
 
while ($row = $write->fetch() ) {
  /* your code */
}

Hope it Helps.. Thnaks....

How to Add a javascript file to your magento page templates

Customising your magento store can be a good way to set your store apart from the competition so adding features that require javascript files is a common task when building a project. Learn how to include a javscript file into your magento page templates with this quick how to.The default layout template load is made primarily through the page.xml file located at the following url for custom themed installs /app/design/frontend/your-instance-name/your-theme-name/layout/page.xml , or for the default theme at /app/design/frontend/default/default/layout/page.xml.

Find the following block encapsulator and simply add the following command inside the block



Then upload you updated page.xml file.

With that done, you need to now upload your javascript file to /skin/frontend/your-instance-name/your-theme-name/js/yourscriptname.js, or for the default theme /skin/frontend/default/default/js/yourscriptname.js

Hope it Helps... Thanks....

Thursday, September 8

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.


for example
foreach ($cartItems as $item)
{
    if($item->getId()== 2)
    {
        $quote->removeItem($item->getId())->save();
    }
} 

Hope it Helps... Thanks...

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



    
        
            true
            local
        
    
 

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



    
        
            0.1.0
        
    
    
        
            
                standard
                
                    Anjan_Systab
                    systab
                
                                    
        
        
            
                
                    systab.xml
                
            
        
    
    
        
            
                admin
                
                    Anjan_Systab
                    systab
                
            
        
    
    
        
            
                My Tab
                71
                
                    
                        Manage Profile
                        0
                        systab/adminhtml_systab
                    
                
            
        
        
            
                
                    Allow Everything
                
                
                    
                        
                            
                                
                                    
                                        
                                            System Configuration Tab
                                        
                                    
                                
                            
                        
                        
                            System Configuration Tab
                            10
                        
                    
                
            
        
        
            
                
                    systab.xml
                
            
        
    
    
        
            
                Anjan_Systab_Model
                systab_mysql4
            
            
                Anjan_Systab_Model_Mysql4
                
                    
                        systab
Anjan_Systab core_setup core_write core_read Anjan_Systab_Block Anjan_Systab_Helper

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

Hope it Helps... Thanks....

How to add new tab under system configuration in magento

n 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



    
        
            
            200
        
    
    
        
            separator-top
            
            systab
            100
            1
            1
            1
            
                
                    
                    text
                    10
                    1
                    1
                    1
                    
 
                            select
                            adminhtml/system_config_source_yesno
                            1
                            1
                            1
                            1
                        

                            
                            select
                            adminhtml/system_config_source_yesno
                            1
                            1
                            1
                            1
                        

                            
                            select
                            adminhtml/system_config_source_yesno
                            1
                            1
                            1
                            1
                        
                    

            
        
    
 

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.

Hope it Helps... Thanks....

How to create Special Product & 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

    $val) { $productobject = Mage::getModel('catalog/product'); $productmodel = $productobject->load($val); echo "
  • ";
    echo "

    ".$productmodel->getName()."

    ";
    echo "";
    echo "

    ".$productmodel->getDescription()."

    ";
    echo "

    ".$productmodel->getFinalPrice()."

    ";
    ?>

    ";
    ?>

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

Hope it Helps.. Thanks....

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)



Hope it Helps... Thanks....

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


















 

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


Hope it Helps... Thanks....

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.


Hope it Helps... Thanks....

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 15

$id=15; //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');
} 


Hope it Helps... Thanks.....

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;
}



Hoep it Helps... Thanks.....

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

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 "url)." alt='' />";
//For gallery Image
$resizeimage = $obj->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->backgroundColor(242,242,243)->resize(400,300);
echo "";
}
} 


Hope it Helps... Thanks....

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

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 "

".$subcatname."

"; } } ?>


Hope it helps... Thanks.....

How to get all list of country in magento

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



Hope it Helps... Thanks.....

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 script to send mail using magento function

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('');
}
?> 

Hope it Helps... Thanks.....

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


Hope it Helps... Thanks....

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.



Hope it Helps... Thanks....

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 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

 

Hope it Helps.. Thanks...

How to get contact us email address in magento

Here’s the script to get Contacts 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


Hope it Helps.. Thanks....

Wednesday, September 7

How to Remove the Coupon Code on the Shopping Cart in Magento

On Magento, on the Shopping Cart page, just before the checkout, by default, you have an area where customers can enter a coupon code. Obviously, if you’re running some kind of discount scheme, this is a vital area – however, if you’re not, it can actually take up a lot of much needed room during the checkout! For this reason, you might want to simply get rid!

Well, here’s how… just navigation through your FTP folders to: app/design/frontend/default/default/layout and in there you should see a file called checkout.xml.

Simply open it up and comment or delete the following line:



Problem solved!

Hope it Helps... Thanks....

How to Show Product Description on Magento Shopping Cart Page

Last week I was speaking to a Magento user, and he said he wanted to not only have the Product Title listed in the Magento Checkout, but also the short Product Description there. Most people would perhaps not have the neccessity to do so, however, for those that do want it done, there is a solution about.

If you go into FTP and navigate to /app/design/frontend/default/default/template/checkout/cart/item/default.phtml, you simply need to add the following around Line 27…

load($_item->getProductId());
            echo $custom->getShortDescription(); 
?>
this will successfully echo the short description for each product purchased.

Hope it Helps.. Thanks....

How to Use a Coupon Code for Specific Products or Categories in Magento

So, your web-site sells all sorts of home furniture, and you have a Christmas section. It is two weeks until Christmas Day, and you realise you’ve got quite a lot of seasonal stock that you need to shift – as you don’t want to be left with a warehouse full of Christmas Trees, Christmas Wreaths and Garlands do you?

Well, offering discounts on those products is probably an idea, and why not do it via a coupon code – that way, you can send a lovely email out to all your customers informing them that if they type in XMAS15 on your checkout, they’ll get a whopping 15% off their order.

With some E-Commerce platforms you might have a few problems with trying to offer money off for specific products or categories – however, with Magento, thankfully this is childs play – and it only takes a couple of seconds to set up.

In your Magento Admin system, simply click on Promotions, and then click on Shopping Cart Price Rules – and then click Add New Rule.

On the left you’ll see three tabs, in the uppermost one you’ll have to name your Price Rule, choose which website it will be activated on and what customers will see it, and also name the actual coupon code itself.

It is then the followed tab (entitled “Conditions”) which is the important one, as this area specifies which products/categories will be available for the promotion. So, click the little green plus, and then select “Product Attribute Combination” – this will create a rule which says “[Do this] If an item is found in the cart with all of these conditions true”…

On this occasion we want to select products from certain categories, so click the green plus again and select “Categories”. Then you can select which of the categories that you’ll like to be enabled – simply click the drop down box and save it.

At this point your rule will say “Category IS 167, 168, 171, 174, etc”. You’ll need to click on the “IS” and change it to “IS ONE OF”.

Subsequently, as long as you save it all and apply the rules, you have now successfully made sure that certain products within your store are now available at 15% off. Furthermore, you can do these reductions based on a plethora of rules including SKU, Colour, Price, nearly any attribute you can think of. You could have a “Blue Monday” if you wanted, offering money off on every product that is blue – that is how random and deep you can go with this amazing piece of E-Commerce software!

Hope it Helps.. Thanks....

how to Change Default Quantity on Magento Product Page

I find it a tad annoying how on Magento, you’ve got this empty quantity box next to the Buy Now/Add to Basket button. Although clicking the button alone will add an item to the cart, some users may experience doubt in this motion, and enter the quantity required AS WELL as press the button.

But why even have any doubt? Why not just make the default quantity set to 1 – well this something that a lot of people have required, and fortunately, I have got the answer!

In app\design\frontend\default\default\template\catalog\product\view\type\Simple.phtml

Just change..



to



Hope it Helps.. Thanks..

Tuesday, September 6

How to get current currency and currency symbol in Magento

here is the script to get current currency & Currency symbol in Magento

for current currency
$currency_code = Mage::app()->getStore()->getCurrentCurrencyCode(); 

for currency symbol
Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

Hope it helps... Thanks....

How to get Order Increment ID in Magento

Here is the script to increment the order id in magento

$order = Mage::getModel('sales/order');
$order->load(Mage::getSingleton('sales/order')->getLastOrderId());
$lastOrderId = $order->getIncrementId();

Last real order id

Mage::getSingleton('checkout/session')->getLastRealOrderId();

Hope it helps.. Thanks...

How to Re-Index manually using SQL query in Magento

Here is the script to reindex the data in magento

getConnection('core_write');
    $mysqli->query($sql);
    /*
    Process_id     Indexer_code
        1     catalog_product_attribute
        2     catalog_product_price
        3     catalog_url
        4     catalog_product_flat
        5     catalog_category_flat
        6     catalog_category_product
        7     catalogsearch_fulltext
        8     cataloginventory_stock
        9     tag_summary
    */
    $process = Mage::getModel('index/process')->load(7);
    $process->reindexAll();
    echo "Finished Rebuilding Search Index At: " . date("d/m/y h:i:s");
?>

Hope it helps... Thanks...

How to get Product Image path in Magento

Here is the script to get product image path in magento

$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::helper('catalog/image')->init($product, 'image')->resize(75, 75);


Hope it Helps... Thanks

Monday, September 5

How to change Admin URL Path in Magento

Here is a quick guide on how to change admin url path in Magento. This need to be done for security reason to be safe from hacking/cracking issue. Basically, this is done not to let any general user to access the admin page.

Generally, we do have ‘admin‘ as the administrator path for Magento. So, the admin URL will be http://www.example.com/admin/

This article will show you, how you can change the admin url. Let’s say from ‘admin‘ to ‘backend‘. So, the new admin URL will be http://www.example.com/backend/

Here is how we do it:-

- Open app/etc/local.xml
- Find the following:-

<admin>
    <routers>
            <adminhtml>
                <args>
                    <frontName><![CDATA[admin]]></frontName>
                </args>
            </adminhtml>
        </routers>
</admin>

- Change

<frontName><![CDATA[admin]]></frontName>

to your desired name. Like below:-

<frontName><![CDATA[backend]]></frontName>

- Save the file
- Refresh the Cache from Magento Admin (System -> Cache Management)

Now, you should be able to access admin panel from http://www.example.com/backend/ instead of http://www.example.com/admin/
Important Note

If you just need to change the admin base URL then the proper way I find is by doing the change in local.xml like explained above, instead of editing configuration setting from admin like said below.

I tried to change the Admin Base URL from Magento admin panel. But, I ran into problem and could not access the admin after that. Here is what I did:-

- System -> Configuration -> ADVANCED -> Admin -> Admin Base URL
- Changed Use Custom Admin URL = Yes
- Changed Custom Admin URL (Once I tried with ‘backend/’ and then with ‘http://www.example.com/backend/’)

To solve the problem, I had to make some change in database. If you had similar problem then here is a workaround:-

- Open your database
- Browse table ‘core_config_data‘
- Search in path field for ‘admin/url/use_custom‘ and set its value to ’0′
- Search in path field for ‘admin/url/custom‘ and set its value to empty

- Search in path field for ‘web/secure/base_url‘
- You will find two row result. One with scope = default and another with scope = stores.
- Edit the value of row with scope = stores with the value of the row with scope = default

- Similarly, repeating the process for ‘web/unsecure/base_url‘:-

- Search in path field for ‘web/unsecure/base_url‘
- You will find two row result. One with scope = default and another with scope = stores.
- Edit the value of row with scope = stores with the value of the row with scope = default

- Now, you will be able to login to Magento admin with your old admin base URL.

Ref : http://blog.chapagain.com.np/magento-how-to-change-admin-url-path/

How to Sort latest product by ‘created date’ and ‘new from date’ in Magento

Here is a quick tip to sort/order latest product by both created date and new from date.

Created At date is automatically added when you add a new product. However, you have to set New from Date manually while adding or editing product.

You may have product with same new from date. And, then you need created at date to sort the latest product.

Here is the code to sort/order product by both created date and new from date:-

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

Thanks to Mukesh Chapagain's Blog
Reference : http://blog.chapagain.com.np/magento-sort-latest-product-by-created-date-and-new-from-date

How to disable / remove Secret Key from Admin URL in Magento

A new secret key is created every time you login to Magento Admin. So, there will be a unique key (32 chars long) for each session of your Magento admin login. This key is appended to the admin URL as http://your-admin-url/key/743c37b1…adf6588/

This is basically added for security reason. In their release note, Magento say that they added secret key to URL for CSRF (Cross-site request forgery) Attack Prevention.

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.

You can learn more about CSRF here:- http://en.wikipedia.org/wiki/Cross-site_request_forgery

Sometime you may want to access admin URL without the secret key. For this, you can disable the secret key from admin URL.

Here is how you do it:-

- Login to admin
- Go to System -> Configuration -> ADVANCED -> Admin -> Security -> Add Secret Key to URLs
- Select No
- Save Config

You are done. You will not see the secret key in admin URL nowonwards.

Thanks to Mukesh Chapagain's Blog
Reference : http://blog.chapagain.com.np/magento-how-to-disable-remove-secret-key-from-admin-url

Can’t send header. Header is already sent” in Magento - Tips to solve the problem

In this article I will show you quick tip that will help you solve common problems in Magento: “Can’t send header. Header already sent” in Magento.

I got this error when I have managed to bring back the client store. Basically, this error happens when there is an extra space or character outside the the php tag . Thanks to the help of excellent Magento users, I have been able to solve it. I think it will be useful if I explained steps by steps what I personally have done so that you can reference it later. When this error happens, you should try the following things.

Open the file that has the problem. In my case, this file is index.php in the site root of Magento.

Open the file with some text editors that supports the encoding. I prefer Notepad++ because its great support in multi languages as well as encoding.

If you open it by Notepad++, click on the menu Encoding, click on UTF-8 without BOM. Save it and then re-upload it to the server.

We just save the error file in the UTF-8 encoding to make sure that everything extra space, line is wiped out. Encoding without BOM ensures you will not have any extra, unwanted characters in the file that prevent it from being executed properly.

Hope it Helps... Thanks..