Latest Entries »

Force customer login

I had a requirement like customer support will able to login as any customer. Here is the code snippet i used to force customer support to login as normal user.

  $customerId = (int) $this->getRequest()->getParam('id');
  $customer   = Mage::getModel('customer/customer')
                    ->load($customerId);

  $userSession = Mage::getSingleton('customer/session');
  $userSession->setCustomer($customer);
  Mage::dispatchEvent('customer_login', array('customer'=>$customer));

  $this->getResponse()->setRedirect(Mage::getUrl('customer/account'));
Advertisements

what is magento sql/setup?

While you are writing a new module or customizing existing ones’ you may need to do some tweaking in your db. Magento gives you facility to write sql insaltaller/updater which will run exactly once in its lifetime , do the tweaking for you need and then instantiate you module. In case of complete new module you have to write installer sql and in case of customizing module updater sql.

How does module installer works ?

At the time of instantiating magento looks all Xml files inside the forder /app/etc/module/ to get primiry information about it’s all active module. Then for each module it read the module’s etc/config.xml for is there any sql setup handler available or not. If any sql setup handler declared in config.xml, it looks for the current version number of the module in db core_resource table. The core_resource table contains list of setup handler’s and their corresponding version number.

If no sql handler is listed in the core_resource table then magento runs the installer, if version number in config.xml is greater then the version number in the core_resource table, magento runs the proper updater sql file. For example core_resource table version number is 0.1.0 and in your config.xml you give version number 0.2.0, then magento run the mysql4-upgrade-0.1.0-0.2.0.php.

Writing installer/updater php

Writing an installer/updater is very simple. Get the installer instance, startup installation, run the desired query , and then stop the setup process. For you better understanding I am giving a simple example :-

i)Declare you module and its code pool in
/app/etc/modules/mymodulename.xml

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

ii)Define the setup handler in
/app/code/local/Mypackagename/Mymodulename/etc/config.xml

<?xml version="1.0"?>
<config>

  <modules>
    <Mypackagename_Mymodulename>
      <version>0.1.0</version>
    </Mypackagename_Mymodulename>
  </modules>

  <global>
    <resources>

      <!-- Declaring module setup handler -->
      <!-- &#91;start&#93; -->
      <mymodulename_setup>
        <setup>
          <module>Mypackagename_Mymodulename</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </mymodulename_setup>
      <!-- &#91;End&#93; -->

      <mymodulename_write>
        <connection>
          <use>core_write</use>
        </connection>
      </mymodulename_write>

      <mymodulename_read>
        <connection>
          <use>core_read</use>
        </connection>
      </mymodulename_read>

    </resources>
  </global>
</config>

iii)Write the installer php
Mymodulename/sql/mymodulename_setup/mysql4-install-0.1.0.php

<?php

  $installer = $this;

  $installer->startSetup();

  $installer->run("

    DROP TABLE IF EXISTS {$this->getTable('securityquestion')};

    CREATE TABLE {$this->getTable('securityquestion')} (
      `securityquestion_id` int(11) unsigned NOT NULL auto_increment,
      `title` varchar(255) NOT NULL default '',
      `status` smallint(6) NOT NULL default '0',
      `created_time` datetime NULL,
      `update_time` datetime NULL,
      PRIMARY KEY (`securityquestion_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    INSERT INTO {$this->getTable('securityquestion')}(
    `securityquestion_id` ,
    `title` ,
    `status`
    )
    VALUES ('1', 'Mother\'s maiden name', '1') ,
    ('2', 'Father\'s middle name', '1') ,
    ('3', 'My first car', '1') ,
    ('4', 'High School name', '1');

  ");

  $installer->endSetup();

Ok, we are done !!! Please leave your comments here 🙂 .

Sending Email in Magento

Couple of days back I had to work with mail sending in magento e-commerce. Here I am giving a complete example of how to do that:-

Magento sends mails with it’s model “core/email_template”. Here is an example code for your understanding:-

/**
  * $templateId can be set to numeric or string type value.
  * You can use Id of transactional emails (found in
  * "System->Trasactional Emails"). But better practice is
  * to create a config for this and use xml path to fetch
  * email template info (whatever from file/db).
  */
  const EMAIL_TEMPLATE_XML_PATH = 'customer/testemail/email_template';
  $templateId = Mage::getStoreConfig(EMAIL_TEMPLATE_XML_PATH);

  $mailSubject = 'HI this is a test mail.';

  /**
  * $sender can be of type string or array. You can set identity of
  * diffrent Store emails (like 'support', 'sales', etc.) found
  * in "System->Configuration->General->Store Email Addresses"
  */
  $sender = Array('name'  => 'S. M. Asad Rahman',
                  'email' => 'asad.dk.bd@gmail.com');

  /**
  * In case of multiple recipient use array here.
  */
  $email = 'smasadrahman@yahoo.com';

  /**
  * If $name = null, then magento will parse the email id
  * and use the base part as name.
  */
  $name = 'Asad Rahman';

  $vars = Array();
  /* An example how you can pass magento objects and normal variables*/
  /*
  $vars = Array('customer'=>$customer,
                'address' =>$address,
                'varification_data'=>'fake data for example');*/

  /*This is optional*/
  $storeId = Mage::app()->getStore()->getId(); 

  $translate  = Mage::getSingleton('core/translate');
  Mage::getModel('core/email_template')
      ->setTemplateSubject($mailSubject)
      ->sendTransactional($templateId, $sender, $email, $name, $vars, $storeId);
  $translate->setTranslateInline(true);

Now lets put email template information in config.xml of the corresponding module.

<?xml version="1.0"?>
<config>
<!-- Other config infos 
goes here
 .
 .
 .-->
   <global>
    <!-- Other config infos 
    goes here
    .
    .
    .-->
    <template>
      <email>
        <customer_testemail_email_template translate="label" module="mymodulename">
          <label>Test email sending</label>
          <file>test_email_template.html</file>
          <type>html</type>
          </customer_testemail_email_template>
        </email>
      </template> 
    </global>
 </config>

This config xml says there is a email template in “app/locale/en_US/template/email” there is a email template named “test_email_template.html”, so lets create the template file:-

<div style="font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;">
  <table cellspacing="0" cellpadding="0" border="0" width="98%" style="margin-top:10px; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif; margin-bottom:10px;">
    <tr>
      <td align="center" valign="top">
        <!-- &#91; header starts here&#93; -->
          <table cellspacing="0" cellpadding="0" border="0" width="650">
            <tr>
              <td valign="top">
                <p>
                  <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="Magento" border="0"/></a>
                </p>
              </td>
            </tr>
          </table>

          <!-- &#91; middle starts here&#93; -->
          <table cellspacing="0" cellpadding="0" border="0" width="650">
            <tr>
              <td valign="top">
                <p>
                <strong>Dear {{var customer.name}}</strong>,<br/>
                This is a test mail.:-)
                </p>
              </td>
            </tr>
          </table>

      </td>
    </tr>
  </table>
</div>

In config.xml we set values for “customer_testemail_email_template”, but in code we use Mage::getStoreConfig(“customer/testemail_email/template”) to set $templateId. So we need to create a relation in between two. To do so we will create a installer to insert a data in db config.

<?php

$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */

$configValuesMap = array(
  'customer/testemail_email/template' =>
  'customer_testemail_email_template',
);

foreach ($configValuesMap as $configPath=>$configValue) {
    $installer->setConfigData($configPath, $configValue);
}

That’s it. Now this code snippet is good enough to send a customized mail. If you want the facility to set email template from admin panel, use the following system.xml in your module.

<?xml version="1.0"?>
<config>
  <sections>
    <customer>
      <groups>
        <testemail translate="label">
          <label>Apply Non-Profit Account Options</label>
          <sort_order>100</sort_order>
          <show_in_default>1</show_in_default>
          <show_in_website>1</show_in_website>
          <show_in_store>1</show_in_store>
          <fields>
            <email_template translate="label">
              <label>Email Template</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>
            </email_template>
          </fields>
        </testemail>
      </groups>
    </customer>
  </sections>
</config>

That’s it !!! I hope this post will help you sending emails from magento. Please leave comments 🙂 .