Tuesday 1 July 2014

Magento Get the parent of a simple product

This tutorial will guide you on how to get parent product id for simple product in magento. There are several ways we can achieve this.

$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
->getParentIdsByChild($product->getId());
if (isset($parentIds[0])) {
    // If we find a parent product then we display it's ID
    $parentProduct = Mage::getModel('catalog/product')->load($parentIds[0]);
    echo $parentProduct->getId();
}


OR

$simpleProductId = 102;
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
                  ->getParentIdsByChild($simpleProductId);
$product = Mage::getModel('catalog/product')->load($parentIds[0]);
echo $product->getId();


Best of luck

Magento Get dropdown attribute’s option Id or Lable or Value

This tutorial will guide you on how to get drop down attribute value or label or id

Get attribute id using label.
$productModel = Mage::getModel('catalog/product');
$attr = $productModel->getResource()->getAttribute("color_group");
if ($attr->usesSource()) {
    echo $attr->getSource()->getOptionId("Green");
}


Get attribute label using id.
$productModel = Mage::getModel('catalog/product');
$attr = $productModel->getResource()->getAttribute("color_group");
if ($attr->usesSource()) {
    echo $attr->getSource()->getOptionText("723");
}



Get all options by attribute Code.
$attributeId = Mage::getResourceModel('eav/entity_attribute')
->getIdByCode('catalog_product','color_group');

if ($attributeId->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);
}


Get all options by attribute Id.
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load(723);
if ($attribute->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);
}


Best of luck

Magento How to get child product collection of configurable product

A configurable product can have multiple other products associated to it.This tutorial describe How can get all the simple products associated with a configurable product.

Get all product id of all simple products associated with a configurable product.
$AssociatedProducts = Mage::getModel('catalog/product_type_configurable')
->getChildrenIds($_product->getId());

Get collection of all the simple products associated with a configurable product.
$product = Mage::getModel('catalog/product')->load($product_id);
$childProducts = Mage::getModel('catalog/product_type_configurable')->

getUsedProducts(null,$product);

Best of luck

Magento Get a product collection by specific ids

This tutorial describe How can get product collection using specific product id.
Here is the code to fetch AND filter with custom option using specific product id also you can use to get simple products associated with a configurable product.

$productIds= Mage::getModel('catalog/product_type_configurable')
->getChildrenIds($_product->getId());

$productCollection = Mage::getModel('catalog/product')->getCollection()
                ->addAttributeToSelect('sceneseven_thumbnail_image')
                ->addAttributeToFilter('entity_id', array('in' => $productIds))
                ->addAttributeToFilter('color_group',$colorFilter)
                ->addAttributeToSort('color', 'ASC');


Best of luck

Tuesday 17 June 2014

Magento add a custom email template

While creating a local module you may sometimes required to add the send mail functionality with custom email template.
Below is the code and description on how to create a send mail and loading it with a custom template with product data.

This tutorial for send email using custom template with product data like(Product name,description,image).

The following steps are for sending email with custom template feature for the module.

Step1:
Go to : app > code > community > Namespace > Modulename  > etc > system.xml
Add the following code:

<email_template translate="label">
    <label>Email Template for User</label>
    <frontend_type>select</frontend_type>
    <source_model>adminhtml/system_config_source_email_template</source_model>
    <sort_order>13</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>


Step2:
Go to : app > code > community > Namespace > Modulename  > etc > config.xml
Add the following code:

<global>
    <template>
        <email>
            <modulename_general_email_template translate="label">
                <label>Pre-Order</label>
                <file>modulename_template.html</file>
                <type>html</type>
            </modulename_general_email_template>
        </email>
    </template>
</global>


Step3:
Go to : app > code > community > Namespace > Modulename > controllers > IndexController.php:
Add the following Email code in method:

<?php
    $storeId = Mage::app()->getStore()->getId();
    // get email template   
    $emailTemplate = Mage::getStoreConfig('modulename/general/email_template', $storeId);
   
    $translate = Mage::getSingleton('core/translate');
    $translate->setTranslateInline(false);   
    Mage::getModel('core/email_template')
    ->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
    ->sendTransactional(
        $emailTemplate,
        'support',
        'test@test.com',
        '',
        array(
            'productcollection'     => "$productid",               
        ));
    $translate->setTranslateInline(true);
?>


Step4: Create custom template file
At location app > locale > en_US > template >  email > 
modulename_template.html
Add the following code:

<!--@subject custom Email for @-->
<body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
<div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">

<!--you can add template file like-->
 {{block type='core/template' area='frontend' template='modulename/email_tempate.phtml' productcollection=$productcollection }}

Thank you for sending email.
</div>
</body>


Step3: Create custom template file
At location: app > design > frontnend > default > default > template > modulename > email_tempate.phtml
Add the following code:

 <?php
$products = $this->getData('productcollection');
$obj = Mage::getModel('catalog/product');
$product = $obj->load($products);

if ($product): ?>
<p><?php echo $this->__('Message:') ?></p>
<table>
    <tr>
        <td><a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $this->escapeHtml($product->getName()) ?>"><img src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail')->resize(75, 75) ?>" border="0" align="left" height="75" width="75" alt="<?php echo $this->escapeHtml($product->getName()) ?>" /></a></td>
        <td>
            <p><a href="<?php echo $product->getProductUrl() ?>"><strong><?php echo $this->escapeHtml($product->getName()) ?></strong></a></p>
            <?php $shortDescription = $product->getShortDescription(); ?>
            <?php if ($shortDescription): ?>
                <p><small><?php echo $shortDescription ?></small></p>
            <?php endif; ?>
            <p><?php if ($product->getPrice() != $product->getFinalPrice()): ?>
                <?php echo $this->__('Regular Price:') ?> <strong style="text-decoration:line-through;"><?php echo Mage::helper('core')->currency($product->getPrice()) ?></strong><br />
                <strong><?php echo $this->__('Special price:') ?> <span style="color:#FF0000;"><?php echo Mage::helper('core')->currency($product->getFinalPrice()) ?></span></strong>
            <?php else: ?>
                <strong><?php echo $this->__('Price:') ?></strong> <?php echo Mage::helper('core')->currency($product->getPrice()) ?>
            <?php endif; ?></p>
        </td>
    </tr>
</table>
<?php endif; ?>


Hope this helps you.
Best of luck. 

Magento send contact form email with attachment

Here You can see how to send contact form email with image attachment.

1.You need to rewrite Magento's Contacts IndexController.

 config.xml:
Add xml override code in your module’s config.xml as:

<frontend>
    <routers>
        <contacts>
            <args>
                <modules>
                    <namespace_modulename before="Mage_Contacts">Namespace_Modulename</namespace_modulename>
                </modules>
            </args>
        </contacts>
    </routers>
</frontend>


IndexController.php:
copy the following code:

<?php
require_once Mage::getModuleDir('controllers', 'Mage_Contacts') . DS . 'IndexController.php';
class Namespace_Modulename_IndexController extends Mage_Contacts_IndexController
{
public function postAction()
    {
        $post = $this->getRequest()->getPost();      
      
        if ($post) {
          
            $translate = Mage::getSingleton('core/translate');
          
          
            /* @var $translate Mage_Core_Model_Translate */
            $translate->setTranslateInline(false);
          
            try {
                $postObject = new Varien_Object();
                $postObject->setData($post);
              
                $error = false;
                if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
                    $error = true;
                }

                if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
                    $error = true;
                }

                if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                    $error = true;
                }

                if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                    $error = true;
                }
                
                $fileName = '';
                if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
                    try {
                        $fileName       = $_FILES['attachment']['name'];
                        $fileExt        = strtolower(substr(strrchr($fileName, ".") ,1));
                        $fileNamewoe    = rtrim($fileName, $fileExt);
                        $fileName       = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;

                        $uploader       = new Varien_File_Uploader('attachment');
                        $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                        $uploader->setAllowRenameFiles(false);
                        $uploader->setFilesDispersion(false);
                        $path = Mage::getBaseDir('media') . DS . 'Customform';
                        if(!is_dir($path)){
                            mkdir($path, 0777, true);
                        }
                        $uploader->save($path . DS, $fileName );

                    } catch (Exception $e) {
                        $error = true;
                    }
                }
                        
                if ($error) {
                    throw new Exception();
                }     
              
                $mailTemplate = Mage::getModel('core/email_template');
                /* @var $mailTemplate Mage_Core_Model_Email_Template */
              
          
        //send file
                $attachmentFilePath = Mage::getBaseDir('media'). DS . 'Customform' . DS . $fileName;
                if(file_exists($attachmentFilePath)){
                    $fileContents = file_get_contents($attachmentFilePath);
                    $attachment   = $mailTemplate->getMail()->createAttachment($fileContents);
                    $attachment->filename = $fileName;
                }

                 
                $mailTemplate->setDesignConfig(array('area' => 'frontend'))
                    ->setReplyTo($post['email'])
                    ->sendTransactional(
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
                        null,
                        array('data' => $postObject)
                    );

                if (!$mailTemplate->getSentSuccess()) {
                    throw new Exception();
                }

                $translate->setTranslateInline(true);

                Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
              
                $this->_redirect('*/*/');

                return;
            } catch (Exception $e) {
                $translate->setTranslateInline(true);

                Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
                $this->_redirect('*/*/');
                return;
            }

        } else {
            $this->_redirect('*/*/');
        }
    }
}
?>

 
Hope this helps you.
Best of luck.

Magento How to throw specific exceptions

The call Mage::throwException() is used to throw exceptions of the specific Mage_Core_Exception variety. These are generally used to show error messages to the end user.

Sometimes a basic Exception just isn't specific enough to catch the problem responsibly so you can deal with the issue. If you're writing a custom module and you tend to wrap your code in try and catch blocks, convention would insist you use Mage::throwException().

Mage::throwException is essentially a wrapper for Mage_Core_Exception($message) with the additional functionality of being able to add the exception to a session via a getSingleton call chained with addMessage

Type hinting your catch blocks with specific Exceptions allows you to deal with each specific issue separately,
you might have something like this in your controller action:

try {
        try {
            if (!Zend_Validate::is(trim($_FILES['attachment']['name']), 'NotEmpty')) {
                $error = true;
            }
        } catch (Exception $e) {
            $error = true;
        }
        if ($error) {
            Mage::throwException('error message');
        }

    } catch (Exception $e) {
        $translate->setTranslateInline(true);              
        $errorMsg = $e->getMessage() ? $e->getMessage() : 'Unable to submit your request. Please, try again later';
        Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__($errorMsg));
        $this->_redirect('*/*/');
        return;
    }


Best of luck

Monday 9 June 2014

Magento send email using smtp

First we need to Override Magento Core Files Into local

Go to : app > code > core > Mage > Core > Model > Email.php
AND
app > code > core > Mage > Core > Model >Email > Template.php

Copy These files and paste here

Go to : app > code > local > Mage > Core > Model > Email.php
AND
app > code > local > Mage > Core > Model >Email > Template.php


After paste open these files and add following code in "send" function with your credentials:

$config = array('ssl' => 'tls',
'port' => 587,
'auth' => 'login',
'username' => 'username@gmail.com',
'password' => 'password');

$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config); 
and replace: 
$mail->send(); 
with:
$mail->send($transport);
 
After this clear your cache.
Now magento will be able to send emails for you.
Best of luck 

Sunday 8 June 2014

Magento show image over system config menu tab of extension

This article shows image on system configuration (System -> Configuration) menu with menu tab for your custom module.

Let us suppose, you have already created a local module.


Go to in \app\code\local\MyChannel\MyModule\etc\system.xml

<tabs>
        <test>           
            <label><![CDATA[<div style="position: absolute;"><img id="test_block" src="" alt="" border="0" /></div>&nbsp;<script>
            var n = SKIN_URL.indexOf("adminhtml");
            $('test_block').src = SKIN_URL.substring(0, n) + "adminhtml/default/default/images/test.png";
            </script>]]></label>
            <sort_order>400</sort_order>
        </test>           
    </tabs>

We have created a new system tab with Image ‘test.png’.

Saturday 31 May 2014

Magento Reset products per page value to default on pageload

Go to : app > code > core > Mage > Catalog > Block > Product > List > Toolbar.php

Copy this file and paste here

Go to : app > code > local > Mage > Catalog > Block > Product > List > Toolbar.php

Open this file and find this

"$limit = Mage::getSingleton('catalog/session')->getLimitPage()" aroung 745 line no.

replace with

$limit = Mage::getStoreConfig('catalog/frontend/list_per_page');

After completed above steps Please remove cache

Best of luck