Monthly Archives: July 2012

Magento 2 will Release at the End of this Year

Magento have announced the Magento 2 project  which will be realsing at the end of this year.
Magento 2 is the result of the Magento team’s learning curve in the world of ecommerce application development since its inception back in 2001.

Magento 2. Much in the way of improved functionality and performance has been promised. Some of the new features set to be included are:

  1. Clearer processes and transparency
  2. Improved product quality
  3. Improved performance and scalability
  4. Improved product security
  5. Truly Modular Product
  6. Enhanced Modular architecture
  7. Improved coverage of Web (APIs SOAP ,XML,JSON,REST)
  8. Support of Multiple RDBMS (MySQL,ORACLE,MSSQL,PostgreSQL)
  9. Simplified customization processes
  10. Adding New functionality
  11. Extend or Replace or Disable functionality
  12. Improve Multi-language support(Data Entry for Each language)
  13. Improve education and product documentation
  14. GUI Design Editor
  15. Safe Upgrade between version
  16. Improvement in Module Structure
  17. Module Coupling ,Themes ,Routing and many more….
  18. Automated Testing 
  19. Continuous Integration
  20. Change in File System Structure 
  21. Change in the Configuration (Class path declaration ,Table name Declaration)
  22. Auto Load and MAny more
Standard Code files can been seen here  and some Reference site 

Magento send Custom Email

Magneto have default some of the already made Email Template .Now we also can make the Custom email Template used as per our need ,for standard of sending the Email.let’s take an example of adding the Custom Email

First in our module create a system.xml file and write the following code

<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <sections>
        <customer translate="label" module="mymodule">
            <groups>
                <custom_email translate="label">
                    <label>Custom Emails</label>
                    <frontend_type>text</frontend_type>
                    <sort_order>5</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>0</show_in_website>
                    <show_in_store>0</show_in_store>
                    <fields>
                            <exist_user_template translate="label">
                                <label>Existing User Custom Email</label>
                                <frontend_type>select</frontend_type>
                                <source_model>adminhtml/system_config_source_email_template</source_model>
                                <sort_order>3</sort_order>
                                <show_in_default>1</show_in_default>
                                <show_in_website>1</show_in_website>
                                <show_in_store>1</show_in_store>
                            </exist_user_template>
                    </fields>
                </custom_email>
            </groups>
        </customer>
    </sections>
</config>

In this the only point to notice is this

<source_model>adminhtml/system_config_source_email_template</source_model>

which will store the data once saved in the core_config_data Table

This indicates our drop down will show a list of all our email templates.

Next we need to make add config.xml. Here will add our new template file. Inside our >global< tab in config.xml

<template>
            <email>
                <customer_custom_email_exist_template translate="label" module="mymodule">
                    <label>Existing User Custom Template</label>
                    <file>custom/mytemplate.html</file>
                    <type>html</type>
                </customer_custom_email_exist_template>
            </email>
        </template>

The above xml basically adds an entry into Magento Transactional Email.

This >customer_custom_email_exist_user_template< should be same as the entire path written is system.xml. New we need to add a file at folder app/locale/en_US/template/email/custom/mytemplate.html and put your default email content there if any. This file is mentioned in the >file< above.

After doing the above steps go to Admin -> System -> Transactional Email and you should be able to see your email template created in the Load Template drop down .

You can put in the content and subject of the email in admin. Also, when you go to Admin -> System -> Configuration -> Customer -> Quote Email, the drop down we just created, you will see our new email already selected there. Just save the configuration again at this point.

Next, to send the email from your module this the function to use

const XML_PATH_EMAIL_ADMIN_QUOTE_NOTIFICATION = 'customer/custom_email/exist_template';

public function _sendNotificationEmail($to, $templateConfigPath = self::XML_PATH_EMAIL_ADMIN_CUSTOM_NOTIFICATION)
    {
        if (! $to) return;
        $translate = Mage::getSingleton('core/translate');
        /* @var $translate Mage_Core_Model_Translate */
        $translate->setTranslateInline(false);
        $mailTemplate = Mage::getModel('core/email_template');
        /* @var $mailTemplate Mage_Core_Model_Email_Template */
        $template = Mage::getStoreConfig($templateConfigPath, Mage::app()->getStore()->getId());
        $sendTo = array();
        foreach ($to as $recipient)
        {
            if (is_array($recipient))
            {
                $sendTo[] = $recipient;
            }
            else
            {
                $sendTo[] = array(
                    'email' => $recipient,
                    'name' => null,
                );
            }
        }
        foreach ($sendTo as $recipient) {
            $mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>Mage::app()->getStore()->getId()))
            ->sendTransactional(
            $template,
            Mage::getStoreConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_IDENTITY,Mage::app()->getStore()->getId()),
            $recipient['email'],
            $recipient['name'],
            array(
                    'customer'  => $customer,
                     'quote' => $quote
            )
            );
        }
        $translate->setTranslateInline(true);
        return $this;
    }

You need to call this function and call the correct parameters. $to is an array of recipient name and email id, $templateConfigPath is the path of our system.xml drop down.

Call this function from your model or controller, and this would send the email. The mail function used here is sendTransactional()

sendTransactional(
            $template,
            Mage::getStoreConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_IDENTITY,Mage::app()->getStore()->getId()),
            $recipient['email'],
            $recipient['name'],
            array(

                    'customer'  => $customer,
                    'quote' => $quote
            )
            )

The definition of this function is

public function sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)

Passing Parameters to Email Template

As you can see above we have passed an array with $customer and $quote variable in the sendTransactional() function. These parameters passed can access in our email template. Like if we want to show the show the customer name and email in our template we need to put this in our template

{{htmlescape var=$customer.name}}

So, this is how we can pass variables to our email templates and access them.

Magento upgrading the MYSQL SCRIPT for Module

Every Module in Magento have the Sql folder in which all the insert script is written but some time we need to add new field in  some tables so we need to upgrade the script .You don’t need to change or run the query directly in databse it’s wrong way

You can upgrade your module to make your necessary database changes. To do so,

1) You need to create a new mysql upgrade file inside yourmodule/sql/mymodule_setup folder.

Let us suppose that you are going to change the version of your module from 0.1.0 to 0.1.1.

The mysql upgrade file name should be mysql4-upgrade-0.1.0-0.1.1.php

The upgrade format is like mysql4-upgrade-current_version-upgraded_version.php

2) Write necessary sql statements in the newly added mysql upgrade file.

3) You have to change the version in yourmodule/etc/config.xml as well.

Change the version like 0.1.1. 0.1.1 is the new version for our module.

4) That’s it reload the website and refresh the database

Note : But some time new script not get upgraded then you can check in “core_resource” table which will help to identify

Magento Add to cart in Upsell Product

Magento by default doesn’t show the “Add to CART” Button in Upsell productjust need to add the following code u will get the Add to Cart Button

<button type="button" onclick="window.location='<?php echo $this->getAddToCartUrl($_link) ?>';"> <?php echo $this->__('Add to Cart') ?> </button>

Magento – Limit Displayed Characters From Product Short Description

Magento by default showing more word in the Short Description ,But some time we want to reduce the length of Short description 

We can use this code wherever we required the Short Description should come with limit words

getShortDescription();
$sdesc = trim($sdesc);
$limit = 40;
if (strlen($sdesc) > $limit) {
$sdesc = substr($sdesc, 0, strrpos(substr($sdesc, 0, $limit), ' '));
} ?>

This script helps you limit characters form Product Short Description.

Magento Observer and Dispatching Events

What is Event?
An Event is something that occurs in a certain place during a particular sequence flow. Say once a customer completes an order, the flow sequence would be to1. Save the order details 2. Send e-mail confirmation to customermay be more like before loading a database model, after loading a database model, before saving the cart object and many more

Events may be emitted before or after each of these flow points to introduce custom logic.

What is Observer?

Observer An Observer is an event handler. It listens to any event it is attached to and accordingly reacts to the event.

 

So how do you hook into this event that is dispatched?

When you want to use Magento event-driven architecture you must know basically two things – how to dispatch an event and how to catch it.

 

Within Magento you can dispatch an event as simple as by calling Mage::dispatchEvent(…) method, for example:

Mage::dispatchEvent(‘custom_event’, array(‘object’=>$this));

For example:

Mage::dispatchEvent('catalog_controller_product_init_before', array('controller_action'=>$this));

Mage::dispatchEvent('catalog_product_get_final_price', array('product'=>$product, 'qty' => $qty));

Mage::dispatchEvent('adminhtml_catalog_category_tabs', array('tabs'  => $this));


This methods accepts two parameters – event unique identifier and associative array of data that is set as Varien_Event_Observer object data, so in fact passed to event observers.

 

Register a new custom local module under name ‘tech’. For this create file ‘Xyz.xml’ under directory ‘app/etc/modules/’. File contents are –

 

Create a New custom Module name ‘Xyz’ .For this create file ‘Xyz.xml’ under directory “app/etc/modules/”.

<?xml version="1.0"?>
<config>
  <modules>
    <Xyz_ACustomModul>
      <codePool>local</codePool>
      <active>true</active>
    </Xyz_ACustomModul>
  </modules>
</config>

Register the event with its Observer. Create file ‘config.xml’ under directory ‘app/code/local/Xyz/ custommodule/etc/’ with contents as

<config>
  <global>
    <models>
        <xyzacustommodule>
             <class>Xyz_ACustomModule_Model</class>
        </xyzacustommodule>
    </models>
    <events>
      <custom_event>
        <observers>
          <xyz_acustommodule_model_observer>
            <type>singleton</type>
            <class>Xyzacustommodule/Observer</class>
            <method>customObserverAction</method>
          </xyz_acustommodule_model_observer>
        </observers>
      </custom_event>   
    </events>
  </global>
</config>

 

Parameter Explanation

<global> – If you want your observer to listen no matter where the event is dispatched from, put it here. You can also put it in “frontend” or “adminhtml”.

<events> – This is the element that stores all of the events that are registered.

<custom_event> – This is the “event” that you are listening to.

<observers> – This is the type of event. I don’t think there are others.

<xyz_acustommodule_model_observer> – This is a unique string that defines this configuration. It can be anything, and just needs to be unique.

<type> – I have always used singleton, but other options can be “model” or “object”. The “singleton” will create the object as Mage::getSingleton() while both “object” and “model” will use Mage::getModel() when creating the observer object.

<class> – This is the observer class.

<method> – This is the function to be called in the observer class.

 

Creating the Observer. Create the directory structure – app/code/local/Xyz/ACustomModule/Model. Place the php code below in a file by name ‘Observer.php’ in the directory just created.

class Xyz_ACustomModule_Model_Observer
{
  public function customObserverAction(Varien_Event_Observer $observer)
  {
    $object = $observer->getEvent()->getObject(); // we are taking the item with 'object' key from array passed to dispatcher
    $object->doSomething();
    return $this;
}

List of Dispacth Events can be found here

Magento Debugging tips

Here are some Debugging tips which will help to debug magneto code.As some of the tools are also available which will help to debug the code easily There is one free extension available for the Debugging the code ,files,DB …..click on the following link
1) If variable is object and of which class

<?php Zend_Debug::dump(get_class($this), 'get_class') ?>

 

2) If variable to see its content/value

<?php Zend_Debug::dump($this->debug(), 'debug') ?>

 

3) If read the value of object properties/attributes

For example we will use $_product

 <?php Zend_Debug::dump($_product->getData('attribute_name')) ?>

 

4) If Loop trough Magento collection object

(Check if something is a collection, if we can iterate trough it)

<?php if($var instanceof Varien_Data_Collection): ?>
    <ul>
    <?php foreach($var as $k => $v): ?>
        <li>Some value: <?php echo $v ?></li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

 

5) If to get the files which are included in that page

print_r(get_included_files());

 

6) If to get the full list of methods available

get_class_methods

hope this will help you

Magento Maximum Length of Attribute

In Magento By default maximum length of an attribute is less than 30 synbols

we can upgrade to new value just need to edit one file

app/code/core/Mage/Eav/Model/Entity/Attribute.php copy to

app/code/local/Mage/Eav/Model/Entity/Attribute.php and

Find  CONST ATTRIBUTE_CODE_MAX_LENGTH = 30; and

Replace CONST ATTRIBUTE_CODE_MAX_LENGTH = 50;

Hope this will help you

Magento Condition based on the Layout

Sometime we require to place the condition for particular layout  you can use this two methods

1) It will give the page name like view,list,cart etc.. based on the action 

getRequest()->getActionName(); ?> 

2) It will give the module name like catalog,checkut etc..

getRequest()->getModuleName(); ?>

so using both we can get our work done