Monday, May 28, 2012

How to send Email in magento

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

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


To send mail with attached file, prefer use of Zend_Mail

try{
            $mail = new Zend_Mail();
            $mail->setFrom("fromemail","fromname");
            $mail->addTo("toemail","toname");
            $mail->setSubject("subject");
            $mail->setBodyHtml(" body text"); // here u also use setBodyText options.

            // this is for to set the file format
            $at = new Zend_Mime_Part($content);

            $at->type        = 'application/csv'; // if u have PDF then it would like -> 'application/pdf'
            $at->disposition = Zend_Mime::DISPOSITION_INLINE;
            $at->encoding    = Zend_Mime::ENCODING_8BIT;
            $at->filename    = $filename;
            $mail->addAttachment($at);
            $mail->send();

        }catch(Exception $e)
        {
            echo $e->getMassage();

        }

Saturday, May 26, 2012

How to remove index.php from magento URL

There are the following steps

step 1: Goto to your site root folder and you can find the htaccess file there.Open it on text editor and find the line #Rewrite Base/ magento. Just replace it with Rewrite Base/

step 2: Then goto your admin panel and enable the Rewrites. You can find it at System->Configuration->Web->Search Engine Optimization

step 3: Then goto Cache management page (system cache management ) and refresh your cache and refresh the Web Rewrites.

Sunday, May 20, 2012

How to set up a Magento store for Australia


Running Magento stores in Australia differs very little from any other country, but there are a few things that you need to do for compliance with ATO requirements and to ensure that Magento calculates taxes correctly. The following is an outline of the necessary configuration and settings you may need to consider when setting up Magento for an Australian store.

First, the basic information for the store must be configured for Australia:
System → Configuration → General
Countries options

    * Default country = Australia
    * Allow countries = ensure Australia is selected

Locale options

    * Timezone = AUS Eastern Standard Time (Australia/Sydney) (as appropriate)
    * Locale = English (Australia)

Next, the currency must be configured for Australian Dollars:
System → Configuration → Currency Setup
Currency Options

    * Base currency = Australian Dollar
    * Default display currency = Australian Dollar
    * Allowed currencies = ensure Australian Dollar is selected

Shipping settings are important for shipping, and also for tax calculation. You should enter information appropriate for your shipping location, which must be in Australia for shipping and tax calculations to work correctly.
System → Configuration → Shipping Settings
Origin

    * Country = Australia

To set tax correctly for Australia (prices shown include GST) and to apply discounts correctly, the following should be set:
System → Configuration → Tax
Tax Classes

    * Tax Class for Shipping = Shipping

Calculation Settings

    * Tax Based On = Shipping Address
    * Catalog prices include tax = Yes
    * Shipping prices include tax = Yes
    * Apply Tax After Discount = Yes
    * Apply Discount On Prices Including Tax = Yes
    * Apply Tax On = Custom price if available

Default Tax Destination Calculation

    * Default Country = Australia

Display

    * Display Cart/Order Prices = Including tax
    * Display full tax summary = No
    * Display Shipping Prices = Including tax
    * Display Product Prices = Including tax

These settings will instruct Magento that all prices entered into the system already include GST (which is most common for Australian retailers) and that prices displayed to the customer should be displayed including tax. You may need to adjust the settings for shipping appropriately, depending on whether your chosen shipping method should include GST or not.

Please note that the upcoming release has some changes to these settings. For Community Edition 1.4 (and Enterprise Edition 1.6), use the following instead:
System → Configuration → Tax
Tax Classes

    * Tax Class for Shipping = Shipping

Calculation Settings

    * Tax Calculation Method Based On = Total
    * Tax Calculation Based On = Shipping Address
    * Catalog prices = Including tax
    * Shipping prices = Including tax
    * Apply Customer Tax = After Discount
    * Apply Discount On Prices = Including tax
    * Apply Tax On = Custom price if available

Default Tax Destination Calculation

    * Default Country = Australia

Price Display Settings

    * Display Product Prices In Catalog = Including tax

Shopping Cart Display Settings

    * Display Prices = Including tax
    * Display Subtotal = Including tax
    * Display Shipping Amount = Including tax
    * Include Tax in Grand Total = No

Order, Invoices, Creditmemos Display Settings

    * Display Prices = Including tax
    * Display Subtotal = Including tax
    * Display Shipping Amount = Including tax
    * Include Tax in Grand Total = No

The easiest way to meet the ATO requirements for ABN and contact number on invoices is to add these details to your address information:
System → Configuration → Sales
Invoice and Packing Slip Design

    * Address = your address + ABN and phone number

You might also choose to add this information to the transactional email template for invoices. If you want to use the PDF invoices however you will need to alter the address above or modify the PDF rendering, which we may cover in another post.

To set up the 10% GST to be applied on products and shipping, Magento requires the addition of an appropriate tax rate and rule:
Sales → Tax → Manage Tax Zones & Rates

Here we add a tax rate for GST so that Magento will know how much tax to calculate.

To add a rate, click Add New Tax Rate in the top right and fill out the following information:

    * Tax Identifier = GST
    * Country = Australia
    * State = *
    * Zip/Post Code = *
    * Rate = 10.00

Save the rate and proceed to set up a rule for GST.
Sales → Tax → Manage Tax Rules

Tax rules determines when rates should be applied. In this case we want to set it up to apply GST anywhere in Australia.

Click Add New Tax Rule in the top right and fill out the following information:

    * Name = GST
    * Customer Tax Class = Retail Customer
    * Product Tax Class = Taxable Goods | Shipping
    * Tax Rate = GST

Save the rule and GST will be completely set up. It's a good idea to remove any other tax rules that are present by default, unless they will also be relevant for you.
Rename Tax to GST

Something that is often overlooked is that you must include a line in your invoices specifically indicating the amount of GST that has been applied. This can be done in a few ways but a simple method is to use the translation files included as part of the locale. This allows for easy replication across websites by copying the files from one site to another.

To modify the translation, creating an app/locale/en_AU directory and copy the Mage_Sales.csv file from the en_US locale into it. Open this file as a spreadsheet (such as in Excel or OpenOffice.org) and find the line with the word "Tax". Modify the value in the right column to be "GST". This will appropriately change the text that is displayed to the customer.
Rename Invoice to Tax Invoice

Similar to the above, you can edit the translation files to change the text "Invoice" to "Tax Invoice". This is left as an exercise for the reader.

After applying all of these changes you'll have addressed the essentials for running a Magento store in Australia. We recommend also installing our Magento Australian extension, which adds Australian regions, Australia Post shipping, direct deposit and BPAY payment methods. Also be sure to watch out for Magento Community Edition 1.4 as it includes several key improvements to the tax system to make working with discounts easier.

Thursday, May 3, 2012

Design and Template


The first step in any magento customization is design changes (both CSS and HTML Changes). Magento comes with a default theme, but usually people require some changes in their theme depending on their websites. Minor text add/edits, layout changes and other changes are usually required.

Magento template system is very powerfully, it gives you the ability to change almost anything. The template system consists of layout xml files, css files and phtml files. In a typical PHP application, we have HTML/PHP and CSS files where we create/edit the design/layout of the website.  But in magento we have .phtml files to do the job html files. Magento follows MVC architecture and .phtml file do the job of VIEW. phtml are meant only for creating the structure of a page through html/php. They can be used to write complex php codes as well, but generally magento doesn’t follow this standard.

The default folders in magento which contain css and phtml files are:

CSS: skin\frontend\default\default\
PHTML:  app\design\frontend\base\default\template\
Layout: app\design\frontend\base\default\layout\
Before going into magento development we need to remember few things (general good practices to follow, not compulsory):

1. We should never to change magento core files. The reason being, whenever magento is updated all core files are overwritten. So if you make changes in core files those changes will be lost. Core files means, files that come with default magento package. All php, xml and .phtml files where magento code is written.

2. Always remember to turn of magento cache before starting development work. If cache is Turned On, your latest change might not show up in magento. To turn off cache you need to go to magento admin. From top menu go to System -> Cache Management.  Then select all cache types and disable them.


Now let’s start with a very simple task: We will simple remove the default magento logo from the header.

To do this, first we need to know which file to make the changes. For this, magento has a system called Template Path Hints. After enabling temple path hints, you need to refresh your magento home page, you see red color boxes, with paths of phtml files in them. Basically, magento tell you from which file has the current content on the page is coming from. So as you can see from the hints, that header comes from the phtml frontend/base/default/template/page/html/header.phtml , we can simply edit this file and remove the logo.
But, since as a general we should not edit any magento core files, we will create our new theme. In this theme we will do our edits and tell magento to use our theme instead of default theme.

To create a new theme in magento, open magento admin and go to System->Configuration->General->Design->Themes

Follow steps below to create a new theme

1. Let say our new theme name is “newtheme”.

2. Next need to first create folders for our theme. For the PHTML files, create folder named “newtheme” in app/design/frontend/default/ and copy the contents of app/design/frontend/base/default into it.

3. And for CSS files, create a folder name “newtheme” in skin/frontend/default/newtheme and copy the content of skin/frontend/default/default into.

To test your new theme, enable template path hints again and see if files from your theme are shown there or not. You can now make changes to your theme instead of default theme.
So to remove the magento logo, go to the header.phtml file in your new theme and remove the HTML for the logo.


Thursday, April 26, 2012

Magento: Sort latest product by ‘created date’


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

Magento : Set Random Order in Collection


we can select random rows from MySQL table using Zend_Db_Expr(‘RAND()’),
here we have to create a new function in module collection class
(Namespace/Module/Model/Mysql4/Module/Collection.php)
public function setRandomOrder()
{
    $this->getSelect()->order(new Zend_Db_Expr('RAND()'));
    return $this;
}
And use it as
$collection = Mage::getModel('test/test')
                    ->getCollection()
                    ->setRandomOrder();

Collection in magento


Here, I am going to explain some database interaction functions present in the class Mage_Eav_Model_Entity_Collection_Abstract. These collection functions are very useful to select data from Magento database. We need them almost all the time for filtering collection object.


Below are some of the useful functions that we use most often.

Class: Mage_Eav_Model_Entity_Collection_Abstract

addAttributeToFilter: adds WHERE clause on $attribute specified by $condition

/**
* Add attribute filter to collection
*
* If $attribute is an array will add OR condition with following format:
* array(
* array(‘attribute’=>’firstname’, ‘like’=>’test%’),
* array(‘attribute’=>’lastname’, ‘like’=>’test%’),
* )
*
* @see self::_getConditionSql for $condition
* @param Mage_Eav_Model_Entity_Attribute_Interface|integer|string|array $attribute
* @param null|string|array $condition
* @param string $operator
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
addAttributeToFilter($attribute, $condition=null, $joinType=’inner’)

addAttributeToSelect: gets the value for $attribute in the SELECT clause; specify * to get all attributes (i.e. to execute SELECT *)

/**
* Add attribute to entities in collection
*
* If $attribute==’*’ select all attributes
*
* @param array|string|integer|Mage_Core_Model_Config_Element $attribute
* @param false|string $joinType flag for joining attribute
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
addAttributeToSelect($attribute, $joinType=false)

If an array is passed but no attribute code specified, it will be interpreted as a group of OR conditions that will be processed in the same way.
If no attribute code is specified, it defaults to eq.

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

// select all attributes
$collection->addAttributeToSelect('*');

// select specific attributes
$collection->addAttributeToSelect(array('name', 'url_key', 'type_id'));

// select only those items whose status = 1
$collection->addAttributeToFilter('status', 1);

// alternative to select only those items whose status = 1
$collection->addAttributeToFilter('status', array('eq' => 1));

// using LIKE statement
$collection->addAttributeToFilter('sku', array('like' => '%CH%'));

// using IN statement,
// i.e. selecting only those items whose ID fall in the given array
$collection->addAttributeToFilter('id', array('in' => array(1, 14, 51, 52)));

// selecting only those items whose ID is greater than the given value
$collection->addAttributeToFilter('id', array('gt' => 5));

// select by date range
$collection->addAttributeToFilter('date_field', array(
    'from' => '10 September 2010',
    'from' => '21 September 2010',
    'date' => true, // specifies conversion of comparison values
    ));

// Add OR condition:
$collection->addAttributeToFilter(array(
    array(
        'attribute' => 'field_name',
        'in'        => array(1, 2, 3),
        ),
    array(
        'attribute' => 'date_field',
        'from'      => '2010-09-10',
        ),
    ));
Below is the full filter condition codes with attribute code and its sql equivalent

eq : =
neq : !=
like : LIKE
nlike : NOT LIKE
in : IN ()
nin : NOT IN ()
is : IS
notnull : IS NOT NULL
null : IS NULL
moreq : >=
gt : >
lt : <
gteq : >=
lteq : <=
finset : FIND_IN_SET()
from : >= (for use with dates)
to : <= (for use with dates)
date : optional flag for use with from/to to specify that comparison value should first be converted to a date
datetime : optional flag for use with from/to to specify that comparison value should first be converted to a datetime

addFieldToFilter: alias for addAttributeToFilter(). This filters the database table fields.

/**
* Wrapper for compatibility with Varien_Data_Collection_Db
*
* @param mixed $attribute
* @param mixed $condition
*/
addFieldToFilter($attribute, $condition=null)

addAttributeToSort: adds ORDER BY clause on $attribute

/**
* Add attribute to sort order
*
* @param string $attribute
* @param string $dir
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
addAttributeToSort($attribute, $dir=’asc’)

addExpressionAttributeToSelect: adds SQL expression $expression, using $alias, to SELECT clause (typically containing aggregate functions such as SUM(), COUNT()); when $attribute specifies a single attribute as a string, $expression can reference the attribute as simply {{attribute}}, but when passing an array of attributes, each attribute must be referenced in $expression by the name of the specific attribute;

/**
* Add attribute expression (SUM, COUNT, etc)
*
* Example: (‘sub_total’, ‘SUM({{attribute}})’, ‘revenue’)
* Example: (‘sub_total’, ‘SUM({{revenue}})’, ‘revenue’)
*
* For some functions like SUM use groupByAttribute.
*
* @param string $alias
* @param string $expression
* @param string $attribute
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
addExpressionAttributeToSelect($alias, $expression, $attribute)

groupByAttribute: adds $attribute to GROUP BY clause

/**
* Groups results by specified attribute
*
* @param string|array $attribute
*/
groupByAttribute($attribute)

joinAttribute: joins another entity and adds attribute from joined entity, using $alias, to SELECT clause.

Here are the parameters for joinAttribute function:-

$alias = selected field name. You can keep it’s name whatever you want.

$attribute = joined entity type code and attribute code = entity_type_code/attribute_code
entity_type_code is present in eav_entity_type table
attribute_code is present in eav_attribute table
attribute_code is attribute of the corresponding entity you want to select out.

$bind = attribute code of the main entity to link to the joined entity.

$filter = primary key for the joined entity (entity_id default)

/**
* Add attribute from joined entity to select
*
* Examples:
* (‘billing_firstname’, ‘customer_address/firstname’, ‘default_billing’)
* (‘billing_lastname’, ‘customer_address/lastname’, ‘default_billing’)
* (‘shipping_lastname’, ‘customer_address/lastname’, ‘default_billing’)
* (‘shipping_postalcode’, ‘customer_address/postalcode’, ‘default_shipping’)
* (‘shipping_city’, $cityAttribute, ‘default_shipping’)
*
* Developer is encouraged to use existing instances of attributes and entities
* After first use of string entity name it will be cached in the collection
*
* @todo connect between joined attributes of same entity
* @param string $alias alias for the joined attribute
* @param string|Mage_Eav_Model_Entity_Attribute_Abstract $attribute
* @param string $bind attribute of the main entity to link with joined $filter
* @param string $filter primary key for the joined entity (entity_id default)
* @param string $joinType inner|left
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
joinAttribute($alias, $attribute, $bind, $filter=null, $joinType=’inner’, $storeId=null)

joinTable: joins table $table

Here are the parameters of the function joinTable:-

$table = table name to join
$bind = ( parent_key = foreign_key )
$fields = array of fields to select
$cond = where condition
$joinType = join type

/**
* Join a table
*
* @param string|array $table
* @param string $bind
* @param string|array $fields
* @param null|array $cond
* @param string $joinType
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
joinTable($table, $bind, $fields=null, $cond=null, $joinType=’inner’)

Using joinAttribute and joinTable

In the code below, all order invoice items are selected, i.e. all products that have been invoiced.
joinTable is used to join sales_order_entity table to fetch increment_id and store_id of the invoice for each product.
joinAttribute is used to fetch order_id, product_name, and store_id.
joinTable is used again to fetch the order status of each invoice item.

$collection = Mage::getModel('sales/order_invoice_item')
                    ->getCollection()
                    ->joinTable('sales_order_entity', 'entity_id=parent_id', array('invoice_id'=>'increment_id', 'store_id' => 'store_id'), null , 'left')
                    ->joinAttribute('order_id', 'invoice/order_id', 'parent_id', null, 'left')
                    ->joinAttribute('product_name', 'invoice_item/name', 'entity_id', null, 'left')
                    ->joinAttribute('store_id', 'invoice/store_id', 'parent_id', null, 'left')

                    ->joinTable('sales_order', 'entity_id=order_id', array('order_status'=>'status'), null , 'left')
                    ;
joinField: joins regular table field using an attribute as foreign key

/**
* Join regular table field and use an attribute as fk
*
* Examples:
* (‘country_name’, ‘directory/country_name’, ‘name’, ‘country_id=shipping_country’, “{{table}}.language_code=’en’”, ‘left’)
*
* @param string $alias ‘country_name’
* @param string $table ‘directory/country_name’
* @param string $field ‘name’
* @param string $bind ‘PK(country_id)=FK(shipping_country_id)’
* @param string|array $cond “{{table}}.language_code=’en’” OR array(‘language_code’=>’en’)
* @param string $joinType ‘left’
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
joinField($alias, $table, $field, $bind, $cond=null, $joinType=’inner’)

removeAttributeToSelect: removes $attribute from SELECT clause; specify null to remove all attributes

/**
* Remove an attribute from selection list
*
* @param string $attribute
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
removeAttributeToSelect($attribute=null)

setPage: sets LIMIT clause by specifying page number (one-indexed) and number of records per page; equivalent to calling setCurPage($pageNum) and setPageSize($pageSize)

/**
* Set collection page start and records to show
*
* @param integer $pageNum
* @param integer $pageSize
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
setPage($pageNum, $pageSize)

importFromArray: imports 2D array into collection as objects

/**
* Import 2D array into collection as objects
*
* If the imported items already exist, update the data for existing objects
*
* @param array $arr
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
importFromArray($arr)

exportToArray: returns collection data as a 2D array

/**
* Get collection data as a 2D array
*
* @return array
*/
exportToArray()

setOrder: alias for addAttributeToSort() q.v., identical except that it can accept array of attributes, and default $dir is desc

/**
* Set sorting order
*
* $attribute can also be an array of attributes
*
* @param string|array $attribute
* @param string $dir
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
setOrder($attribute, $dir=’desc’)