Category Archives: Miscellaneous

Miscellaneous

How to start Magento ecommerce development ? – for Beginner

Dear Beginner, here I will mention few easy steps to start magento development. Just for your smooth and comfortable starting. After completed this you will gain confidence to move forward. HappYYY Starting ………

One of my junior asked me, I wanna learn magento development, how can I start? Question was very simple, but it was hard for me to give him right answer. Because magento is not same as other other open-sources. Magento development is a bit tricky. Magento uses EAV based database architecture which is totally different than others, xml based layout and coding convention also different. Also you have to follow right convention and Object Oriented Programming (OOP) style, though magento is built on PHP with Zend framework.

Step 1: know about magento?
————————————-
I will give you answer in one line. World most popular eCommerce open-source 🙂 Right now Magento is owned by eBay.

Step 2: Download magento
————————–
1. Go to this link http://www.magentocommerce.com/download and download latest version from “Full Release”.
2. Then download sample data from same page.

Step 3: Install magento
————————–
1. At first install sample data. See this link http://www.magentocommerce.com/knowledge-base/entry/installing-sample-data-archive-for-magento-1610
2. Then install magento in your localhost. Goto: http://localhost/magento/install (replace the above “magento” with where your installation was extracted.). Follow the on screen instructions. Database name will be where you installed sample data at step 3.1. Few helpful urls.

http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/magento_installation_guide
http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/installing_on_windows_with_xampp_and_wamp
http://www.magentocommerce.com/knowledge-base/entry/magento-installation-cheat-sheet

Step 4: Browse Magento backend and build your dummy store
———————————————————-
Before start development, I will suggest you to check all of the magento features thoroughly. Check all of the admin setting and options as much as possible. It will give u better idea about magento features and capabilities.
1. Catalog setting
2. Static CMS pages, block, Widget etc
3. Design things like Theme/package change
4. Shipping, Tax, Payment etc
5. Promotion, price rule etc
6. Email setting
7. Configuration
8. …..
etc

Try to build your dummy store. Here is link where u will get help. http://www.magentocommerce.com/knowledge-base/categories/category/build-your-store/

At least spend 3 days (20 hours) to explore magento features. Continue exploring until you get a clear cut idea about magento.

Step 5: Check magento file/directory structure
————————————————
Go to below links and check. Just check. No need to spend too much time.
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/basic_magento_directory_overview
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento-folder-structure

Step 6: Check magento database structure
————————————————
Just take a look and read that article once. No need to be worried 🙂
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento_database_diagram
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/catalog_database_tables

Step 7: Create a simple new package/theme
————————————————
Here you will learn how to change frontend design stuffs. Just follow below link. Also you will know more about magento design structure means design template. How to add new css, js, layout etc will be discussed here.
http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/0_-_theming_in_magento/package

Step 8: Extend magento features – Create a New “Helloworld” module
——————————————————————
Now you have idea about magento file structure, template, features and database. Create a new module means extend magento, customize existing functionality. It is pure programming. Go to below link and follow steps.

Create new module “HelloWorld” – in Magento

Here is the end !!!

Now you have total idea about magento!! So you can play with magento as you wish.

For your next step, you can take help from magento wiki and forum.
http://www.magentocommerce.com/wiki/
http://www.magentocommerce.com/wiki/index/categories/
http://www.magentocommerce.com/wiki/index/pages/
http://www.magentocommerce.com/boards/

For more conceptual idea see below link. Here u will get Conceptual Schema structure.
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento_conceptual_schema

Thanks for your patience. Question welcome. Your success is my pleasure.

HappY Programming ….

Add Security Question/Answer for Forgotten Password – magento

To ensure high security and CPNI Compliance of your magento shop, if customer forget password, then required to provide security answer credentials in order to retrieve a new password. This protects customer information and ensures that the original creator of the account will always have a way of getting their account back (if their account had been hacked/stolen).

In this tutorial, I’m going to explain how to add those two fields to the registration page and require them to be provided on the forgot password page – where they the information will be validated.

[For best practice create new module as usual but I am referring core file name here.]
Please open the following files, as we will be working with them:
**/app/code/core/Mage/Customer/controllers/AccountController.php** – This controls all of the functions that we need to edit.
**/app/design/frontend/default/yourtheme/template/forgotpassword.phtml** – This is the template file for the forgot password page.
**/app/design/frontend/default/yourtheme/template/customer/form/register.phtml** – this is the template file for the register page.
**/app/design/frontend/default/yourtheme/template/customer/form/edit.phtml** – this is the template file for the customer dashboard page.

Alright, first things first. We will start by adding the Security Question and Answer fields to the registration page. We will also have to create a new attribute for the two fields.

At the top of register.phtml, add the following code:

<?php
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
// Set up the Security Question Attribute
$AttrCode = 'squestion';
$settings = array (
'position' => 1,
'is_required'=> 1
);
// Set up the Security Answer Attribute
$AttrCode2 = 'sanswer';
$settings2 = array (
'position' => 1,
'is_required'=> 1
);
// Adds both attributes
$setup->addAttribute('1', $AttrCode, $settings);
$setup->addAttribute('1', $AttrCode2, $settings2);
?>

Now, navigate your browser to  http://www.yoursite.com/customer/account/create/
By navigating to this page, you have executed the php code we just added to the register.phtml file. Your attributes are now added to database. Please remove or comment out the code we previously added to the register.phtml file (it is no longer needed).

In register.phtml, add the following block of code:

<ul>
        <li>
                <div class="input-box">
                    <label for="squestion"><?php echo $this->__('Security Question') ?> <span class="required">*</span></label><br />
                    <select id="squestion" name="squestion" title="<?php echo $this->__('Security Question') ?>" class="required-entry validate-select">
            <option value="What is the name of your dog?">What is the name of your dog?</option>
                        <option value="What is the name of your favorite teacher?">What is the name of your favorite teacher?</option>
            <option value="What is your maiden name?">What is your maiden name?</option>
            <option value="In what city were you born?">In what city were you born?</option>
            <option value="What is your favorite food?">What is your favorite food?</option>
                    </select>
                </div>
                <div class="input-box">
                    <label for="sanswer"><?php echo $this->__('Security Answer') ?> <span class="required">*</span></label><br />
                    <input type="text" name="sanswer" id="sanswer" value="<?php echo $this->htmlEscape($this->getFormData()->getSecurityAnswer()) ?>" title="<?php echo $this->__('Security Answer') ?>" class="required-entry input-text" />
                </div>
            </li>
        </ul>

Now, in your forgotpassword.phtml file, find this block of code (around line 25):

<fieldset>
                <legend><?php echo $this->__('Retrieve your password here') ?></legend>
        <p><?php echo $this->__('Please enter your email below and we will send you a new password.') ?></p>
        <ul class="form-list">
            <li>
                <div class="input-box"><label for="email_address"><?php echo $this->__('Email Address') ?> <span class="required">*</span></label><br/>
                <input name="email" alt="email" type="text" id="email_address" class="required-entry validate-email input-text" value="<?php echo $this->htmlEscape($this->getEmailValue()) ?>" /></div></li>
        </ul>
    <div class="button-set">
        <p class="required"><?php echo $this->__('* Required Fields') ?></p>
        <a href="<?php echo $this->helper('customer')->getLoginUrl() ?>" class="left">&laquo; <?php echo $this->__('Back to Login') ?></a>
        <button type="submit" class="form-button right"><span><?php echo $this->__('Submit') ?></span></button>
    </div>
        </fieldset>

Replace this block of code with this:

<fieldset>
                <legend><?php echo $this->__('Retrieve your password here') ?></legend>
        <p><?php echo $this->__('Please enter your email below and we will send you a new password.') ?></p>
        <ul class="form-list">
            <li>
                <div class="input-box"><label for="email_address"><?php echo $this->__('Email Address') ?> <span class="required">*</span></label><br/>
                <input name="email" alt="email" type="text" id="email_address" class="required-entry validate-email input-text" value="<?php echo $this->htmlEscape($this->getEmailValue()) ?>" /></div>
        </li>
        <li>
        <div class="input-box">
        <?
        if(strlen($this->htmlEscape($this->getSquestionValue()))>0){
        ?>
        <label for="squestion"><?php echo $this->__('Security Question') ?> <span class="required">*</span></label><br />
        <input name="squestion" alt="squestion" type="text" id="squestion" class="required-entry input-text" style="border:0; background:none; font-weight:bold;" value="<?php echo $this->htmlEscape($this->getSquestionValue()) ?>" readonly /></div>
                <? } else { ?>
        <label for="squestion"><?php echo $this->__('Security Question') ?> <span class="required">*</span></label><br />
                    <select id="squestion" name="squestion" title="<?php echo $this->__('Security Question') ?>" class="required-entry validate-select">
            <option value="What is the name of your dog?">What is the name of your dog?</option>
                        <option value="What is the name of your favorite teacher?">What is the name of your favorite teacher?</option>
            <option value="What is your maiden name?">What is your maiden name?</option>
            <option value="In what city were you born?">In what city were you born?</option>
            <option value="What is your favorite food?">What is your favorite food?</option>
                    </select>
        </div>
        <? } ?>
        </li>
        <li>
        <div class="input-box">
        <label for="sanswer"><?php echo $this->__('Security Answer') ?> <span class="required">*</span></label><br />
        <input name="sanswer" alt="sanswer" type="text" id="sanswer" class="required-entry input-text" /></div>
        </div>
        </li>
        </ul>
    <div class="button-set">
        <p class="required"><?php echo $this->__('* Required Fields') ?></p>
        <a href="<?php echo $this->helper('customer')->getLoginUrl() ?>" class="left">&laquo; <?php echo $this->__('Back to Login') ?></a>
        <button type="submit" class="form-button right"><span><?php echo $this->__('Submit') ?></span></button>
    </div>
        </fieldset>

Alright, your template files are finished. Now we need to edit the AccountController.php code.
Find this block of code:

public function loginAction()
    {
        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $this->getResponse()->setHeader('Login-Required', 'true');
        $this->loadLayout();
        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
        $this->renderLayout();
    }

Add this line of code immediately before “$this->getResponse()->setHeader(‘Login-Required’, ‘true’);”

if(!$this->_getSession()->getUsername()){$this->_getSession()->unsForgottenEmail();}

Now, find this block of code within the **loginPostAction** function:

if (!$session->login($login['username'], $login['password'])) {
                    $session->addError($this->__('Invalid login or password'));
                    $session->setUsername($login['username']);
                }

Replace it with this:

if (!$session->login($login['username'], $login['password'])) {
                    $session->addError($this->__('Invalid login or password'));
                    $session->setUsername($login['username']);
                    $session->setForgottenEmail($login['username']);
                }

Now, find this block of code within the **createPostAction** function:

$customer = Mage::getModel('customer/customer')
                ->setFirstname($this->getRequest()->getPost('firstname'))
                ->setLastname($this->getRequest()->getPost('lastname'))
                ->setEmail($this->getRequest()->getPost('email'))
                ->setPassword($this->getRequest()->getPost('password'))
                ->setConfirmation($this->getRequest()->getPost('confirmation'))
                ->setId(null);

Add these lines immediately after the line containing setEmail:

->setSquestion($this->getRequest()->getPost('squestion'))
                ->setSanswer($this->getRequest()->getPost('sanswer'))

Now we need to edit the forgotPasswordAction() function. So find this block of code:

public function forgotPasswordAction()
    {
        $this->loadLayout();

        $this->getLayout()->getBlock('forgotPassword')->setEmailValue(
            $this->_getSession()->getForgottenEmail()
        );
        $this->_getSession()->unsForgottenEmail();

        $this->_initLayoutMessages('customer/session');
        $this->renderLayout();
    }

And replace it with this:

public function forgotPasswordAction()
    {
        $this->loadLayout();

        $this->getLayout()->getBlock('forgotPassword')->setEmailValue(
            $this->_getSession()->getForgottenEmail()
        );

        if((strlen($this->_getSession()->getForgottenEmail())>0)){
            $customer = Mage::getModel('customer/customer')
                    ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
                    ->loadByEmail($this->_getSession()->getForgottenEmail());
            //$this->_getSession()->unsForgottenEmail();
            if ($customer->getId()) {
                $this->getLayout()->getBlock('forgotPassword')->setSquestionValue(
                    $customer->getSquestion()
                );
            } else {
                $this->_getSession()->addError($this->__('This email address was not found in our records'));
            }
        }

        $this->_initLayoutMessages('customer/session');
        $this->renderLayout();
    }

Alright, finally we can edit the forgotPasswordPostAction() function. Find this large block of code:

public function forgotPasswordAction()
    {
        $this->loadLayout();

        $this->getLayout()->getBlock('forgotPassword')->setEmailValue(
            $this->_getSession()->getForgottenEmail()
        );
        $this->_getSession()->unsForgottenEmail();

        $this->_initLayoutMessages('customer/session');
        $this->renderLayout();
    }

    /**
     * Forgot customer password action
     */
    public function forgotPasswordPostAction()
    {
        $email = $this->getRequest()->getPost('email');
        if ($email) {
            if (!Zend_Validate::is($email, 'EmailAddress')) {
                $this->_getSession()->setForgottenEmail($email);
                $this->_getSession()->addError($this->__('Invalid email address'));
                $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
                return;
            }
            $customer = Mage::getModel('customer/customer')
                ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
                ->loadByEmail($email);

            if ($customer->getId()) {
                try {
                    $newPassword = $customer->generatePassword();
                    $customer->changePassword($newPassword, false);
                    $customer->sendPasswordReminderEmail();

                    $this->_getSession()->addSuccess($this->__('A new password was sent'));

                    $this->getResponse()->setRedirect(Mage::getUrl('*/*'));
                    return;
                }
                catch (Exception $e){
                    $this->_getSession()->addError($e->getMessage());
                }
            }
            else {
                $this->_getSession()->addError($this->__('This email address was not found in our records'));
                $this->_getSession()->setForgottenEmail($email);
            }
        } else {
            $this->_getSession()->addError($this->__('Please enter your email.'));
            $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
            return;
        }

        $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
    }

And replace it with this:

public function forgotPasswordPostAction()
    {
        $email = $this->getRequest()->getPost('email');
        $squestion = $this->getRequest()->getPost('squestion');
        $sanswer = $this->getRequest()->getPost('sanswer');
        if ($email) {
            if (!Zend_Validate::is($email, 'EmailAddress')) {
                $this->_getSession()->setForgottenEmail($email);
                $this->_getSession()->addError($this->__('Invalid email address'));
                $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
                return;
            }
            $customer = Mage::getModel('customer/customer')
                ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
                ->loadByEmail($email);

            if ($customer->getId()) {
                if(($customer->getSquestion()==$squestion)&&($customer->getSanswer()==$sanswer)) {
                    try {
                        $newPassword = $customer->generatePassword();
                        $customer->changePassword($newPassword, false);
                        $customer->sendPasswordReminderEmail();

                        $this->_getSession()->addSuccess($this->__('A new password was sent'));

                        $this->getResponse()->setRedirect(Mage::getUrl('*/*'));
                        return;
                    }
                    catch (Exception $e){
                        $this->_getSession()->addError($e->getMessage());
                    }
                } else {
                    $this->_getSession()->addError($this->__('Your security Q&A credentials were incorrect.'));
                    $this->_getSession()->setForgottenEmail($email);
                }
            }
            else {
                $this->_getSession()->addError($this->__('This email address was not found in our records'));
                $this->_getSession()->setForgottenEmail($email);
            }
        } else {
            $this->_getSession()->addError($this->__('Please enter your email.'));
            $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
            return;
        }

        $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
    }

If you navigate to your account login page and the login fails, you will be redirected to the same page telling you that your password/username was incorrect. Now, click on the Forgot Password link that should already be there. You will notice that the username and security question will automatically be filled in for the username you attempted to login to. From here, put in your security answer and your password will be sent to you. If you type in the wrong security answer, you will get a notice saying your security credentials were incorrect.

Add extra field(s) in registration page

Dear Tow…, this post is basically for new guys. Few guys asked me how to add extra field(s) in registration process. So, here I will try to give few technical tricks.

1. Add new fields in config xml (app\code\core\Mage\Customer\etc\config.xml). If you create new module then you can add this xml block in module config xml file. Create new module is the best practice and recommended 🙂

<?xml version="1.0"?>
<fieldsets>
   <customer_account>
     <prefix><create>1</create><update>1</update><name>1</name></prefix>
     <firstname><create>1</create><update>1</update><name>1</name></firstname>
     <middlename><create>1</create><update>1</update><name>1</name></middlename>
     <lastname><create>1</create><update>1</update><name>1</name></lastname>
     <suffix><create>1</create><update>1</update><name>1</name></suffix>
     <email><create>1</create><update>1</update></email>
     <password><create>1</create></password>
     <confirmation><create>1</create></confirmation>
     <dob><create>1</create><update>1</update></dob>
     <taxvat><create>1</create><update>1</update></taxvat>
     <gender><create>1</create><update>1</update></gender>

     /* newly added field(s)*/
     <accounttype><create>1</create><update>1</update><name>1</name></accounttype>
     <companyname><create>1</create><update>1</update><name>1</name></companyname>
  </customer_account>
</fieldsets>

2. Add these extra field(s) in your respective theme registration.phtml (app\design\frontend\…\…\template\customer\form\registration.phtml). Keep the field name same as you mentioned in config.xml

3. To save extra data in database with customer registration process you have to add these extra field(s) as entity attribute in eav_attribute table. Here is sql script.

insert into `magento`.`eav_attribute` (`entity_type_id`, `attribute_code`, `attribute_model`, `backend_model`, `backend_type`, `backend_table`, `frontend_model`, `frontend_input`, frontend_label`, `frontend_class`, `source_model`, `is_required`, `is_user_defined`, `default_value`, `is_unique`, `note`)
values(1, 'accounttype', '', '', 'varchar', '', '', 'select', 'Account Type', '', '', 0, 0, '', 0,''),
        (1, 'companyname', '', '', 'varchar', '', '', 'text', 'Company Name', '', '', 0, 0, '', 0,'');

That’s all. Try and let me know if you face any complexity.

Like this you can add extra field(s) in any magento pages as well.

Add option(s) to quote item object at order processing step

Hi guys, how are you? Hope all of you are doing well. I have been backed after long time and have decided to share few of my recent experiences.

For a recent project I had to create a custom order processing module in magento. I got help from a post of magento forum ( http://www.magentocommerce.com/boards/viewthread/28426/). That was nice and very helpful for me. And it saved my time as well. So my heartiest thanks to all of the guys who have been contributed in that forum post.

But I faced problem to add option(s) with order item. I found a solution to add option(s) to quote object. But using this you can order only single item at a time. Below is the code snap.

$option = array('options'=>array(
              "option_id1" => 'option_value1',
              "option_id2" => 'option_value2'
             ));

$request = new Varien_Object();
 $request->setData($option);
$quoteObj->addProduct($productObj,$request);

To order multiple items at a time you have to add option(s) with quote item object. Here is the code snap for your help.

$quoteObj=Mage::getModel('sales/quote')->assignCustomer($customerObj);
$productModel=Mage::getModel('catalog/product');

foreach($products as $product) {
	$productObj = $productModel->load($productId);
	$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);

	$quoteItem->addOption(new Varien_Object(
                   	array(
                      		'product' => $quoteItem->getProduct(),
                       		'code' => 'option_ids',
                       		'value' => $option_id  // 45,46,55
               	         )
               	));

	$quoteItem->addOption(new Varien_Object(
                    	array(
                       		'product' => $quoteItem->getProduct(),
                       		'code' => 'option_'.$option_id,   //45
                       		'value' => $option_value          // ‘White’
             	         )
   		));

        $quoteItem->addOption(new Varien_Object(
                    	array(
                       		'product' => $quoteItem->getProduct(),
                       		'code' => 'option_'.$option_id,   //46
                       		'value' => $option_value         // ‘Large’
               	        )
   		));

	$quoteItem->setQuote($quoteObj);
	$quoteItem->setQty($Quantity);
	$quoteObj->addItem($quoteItem);
}
$quoteObj->collectTotals();
$quoteObj->save();

This code snap has been worked so far. For more details and any kind of helps contact with me.