Friday, December 21, 2012

Create placeholder input field in javascript


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function removeText(id, val)
{
    if(document.getElementById(id).placeholder == val){
        document.getElementById(id).placeholder ='';
        document.getElementById(id).style.color= '#000';
    }
}
function newText(id, val)
{
    if(document.getElementById(id).value == ''){
        document.getElementById(id).placeholder = val;
        document.getElementById(id).style.color = '#aaa';
    }
}
</script>
</head>
<body>
<input type="text" name="abc" id="abc" placeholder="Enter your name" onfocus="removeText(this.id, 'Enter your name')" onblur="newText(this.id, 'Enter your name')"/>
<input type="text" name="abc1" id="abc1" placeholder="Enter your address" onfocus="removeText(this.id,'Enter your address')" onblur="newText(this.id,'Enter your address')"/>
<input type="text" name="abc2" id="abc2" placeholder="Enter your phone" onfocus="removeText(this.id,'Enter your phone')" onblur="newText(this.id,'Enter your phone')"/>
</body>
</html>

see the demo here.



Thursday, December 13, 2012

How to use dynamic value in a dropdown attribute in magento


>> Here I'll show you how to use dynamic value in a dropdown product attribute. Suppose you need to store Customer Id with a product, then you've to list all customers when you creating a product.

    => First create an attribute of select type and don't need to put the option value there.



    => Now you just need to change the Source Model of this attribute. You can also do it by code. But I'm showing you the easiest way. Go to your phpMyadmin database, find the table "eav_attribute". Search the attribute that you've created. Here I've changed the source model to "vendor/product_attribute_unit". You can use your own.



     I've used a module named "vendor" and a page within app/code/local/JR/Vendor/Model/Product/Attribute/Unit.php .
    Now this the model code.
  
    <?php
    class JR_Vendor_Model_Product_Attribute_Unit extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
    {
      public function getAllOptions()
      {
        $model = Mage::getModel('customer/customer');
        $collection = $model->getCollection();
        $customerArr = array();
        $customerArr[] = array('value' => '0','label' => 'Admin');
        foreach($collection as $customer)
        {
            $customer = $model->load($customer->getId());
            $customerArr[] = array(
                           'value' => $customer->getId(),
                           'label' => $customer->getEmail(),
                            );
        }
        if (!$this->_options) {
            $this->_options = $customerArr;
        }
        return $this->_options;
      }
    }
    ?>
  
    Now you're ready to use your customer to assign in a product.


Send custom transactional email in Magento.


>> Here I'll show you how to use custom transactional mail in Magento. It's very simple, you can use it for your custom page.

    => First create your mail template. Go to Admin=>System=>Transactional Emails=> Click "Add New Template" button. There you'll find a page like :




        Select a template from "Template" dropdown. You can use the "Contact Form". Now fill the all require fields and click save template. Now note the "Template Id" of this template.

    => Use this method to send the mail.

        public function sendJrTransactionalEmail()
        {
            // set the Transactional Email Template's ID that you've created...
            $templateId = 1;
       
            // Set sender information
            $senderName = Mage::getStoreConfig('trans_email/ident_support/name');
            $senderEmail = Mage::getStoreConfig('trans_email/ident_support/email');
            $sender = array('name' => $senderName,
                        'email' => $senderEmail);
       
            // Set recepient information
            $recepientEmail = 'jayanta@example.com';
            $recepientName = 'Jayanta Roy';       
       
            // Get Store ID
            $storeId = Mage::app()->getStore()->getId();
       
            // Set variables that can be used in email template. To get this variable write like {{var customerEmail}} in transactional Email.
            $vars = array('customerEmail' => 'customer@example.com',           
                      'customerName' => 'Mr. John Due');
       
            $translate  = Mage::getSingleton('core/translate');
       
            // Send Transactional Email
            Mage::getModel('core/email_template')
                ->addBcc($senderEmail)      // You can remove it if you don't need to send bcc
                ->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $vars, $storeId);
       
            $translate->setTranslateInline(true);
        }

Hope it'll help you........ :)




Monday, December 10, 2012

Override controllers in Magento


>> I've described admin controller override in my previous post. You just need to change config.xml and controller page with this code :

                        <?xml version="1.0"?>
                        <config>
                            <modules>
                               <JR_Overridecontroller>
                                 <version>1.0.0</version>
                               </JR_Overridecontroller>
                             </modules>
                       
                            <frontend>
                              <routers>
                                <catalog><!-- Name of core module to be overridden  -->
                                  <args>
                                    <modules>
                                      <JR_Overridecontroller before="Mage_Catalog">JR_Overridecontroller_Catalog</JR_Overridecontroller><!-- Tell Magento to call our custom module before the Mage/Catalog module -->
                                    </modules>
                                  </args>
                                </catalog>
                              </routers>
                            </frontend>
                        </config>

and in your controller page :

                     <?php
                        include_once("Mage/Catalog/controllers/ProductController.php");
                        class JR_Overridecontroller_Catalog_ProductController extends Mage_Catalog_ProductController
                        {
                            public function editAction(){
                             
                                // Here is your overridden controller method.....
                             
                            }
                        }
                    ?>

You can override any controller with the help of this.....


Thursday, December 6, 2012

How to override Admin controller Action in Magento


>> Hi! friends this example will help you to override admin controller action. I had to replicate admin product edit section as there were two types of products. First one was normal Magento products another was Used products. Client wanted to manage them separately. So, I override admin product controller action. How ?

  •  First You need to create a new module. Create a xml file within app/etc/modules/JR_Overridecontroller.xml
                        <?xml version="1.0"?>
                        <config>
                            <modules>
                                <JR_Overridecontroller>
                                    <active>true</active>
                                    <codePool>local</codePool>
                                </JR_Overridecontroller>
                            </modules>
                        </config>

  •  Now make the config.xml within app/code/local/JR/Overridecontroller/etc/config.xml
                         <?xml version="1.0"?>
                        <config>
                            <modules>
                               <JR_Overridecontroller>
                                 <version>1.0.0</version>
                               </JR_Overridecontroller>
                             </modules>
                        
                            <admin>
                                <routers>
                                    <adminhtml>
                                        <args>
                                            <modules>
                                                <JR_Overridecontroller before="Mage_Adminhtml">JR_Overridecontroller</JR_Overridecontroller>
                                            </modules>
                                        </args>
                                    </adminhtml>
                                </routers>
                            </admin>
                        </config>

     With this code you can override any admin controller action. But I'm just showing with product controller.

  •  So, now make the controller file that you need to modify within app/code/local/JR/Overridecontroller/controllers/Catalog/ProductController.php
                   <?php
                        include_once("Mage/Adminhtml/controllers/Catalog/ProductController.php");
                        class JR_Overridecontroller_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
                        {
                            public function editAction(){
                              
                                // Here is your overridden controller method.....
                              
                            }
                        }
                    ?>

Download the Zip from here.


                                                 ********       Good Luck       ************




Tuesday, November 27, 2012

How to get all attributes of an attribute group in Magento


>> Sometimes you need to display all attributes value of a particular attribute group. Then you can follow this piece of code :
    <ul>
        <?php
            $_product = $productObj;
            $attributesCollection = Mage::getResourceModel('catalog/product_attribute_collection');
            $attributesCollection->setAttributeGroupFilter(27);                    // Here 27 is Attribute Group Id.
            foreach ($attributesCollection as $attribute) {
                    if($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'boolean'){
                        echo "<li>".$attribute->getFrontendLabel()." : ".$_product->getAttributeText($attribute->getAttributeCode())."</li>";
                    }else{
                        echo "<li>".$attribute->getFrontendLabel()." : ".$_product->getData($attribute->getAttributeCode())."</li>";
                    }

            }
        ?>
    </ul>



How to add a breadcrumb to any Magento page.


>> Here's a easy solution to add breadcrumb to any page. In core block page find _prepareLayout() method.

    <?php
        public function _prepareLayout()
        {
            $breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
            $breadcrumbs->addCrumb('home', array('label'=>Mage::helper('vendor')->__('GEAR WAREHOUSE'),
                                            'title'=>Mage::helper('vendor')->__('Home Page'), 'link'=>Mage::getBaseUrl()));
            $breadcrumbs->addCrumb('my_account', array('label'=>Mage::helper('vendor')->__('My Account'),
                                            'title'=>Mage::helper('vendor')->__('My Account'), 'link'=>Mage::getBaseUrl().'customer/account'));
                                           
            $breadcrumbs->addCrumb('my_classified', array('label'=>Mage::helper('vendor')->__('Classified'),
                                            'title'=>Mage::helper('vendor')->__('My Classified'), 'link'=>Mage::getBaseUrl().'vendor'));
                                           
            $breadcrumbs->addCrumb('an_alias', array('label'=>'Edit',
                                            'title'=>'Edit Classified', 'link'=>''));
        }
    ?>
   
    By using addCrumb() method you can set your breadcrumb to any page. In your phtml page you've to write the following code :
   
    <?php echo $this->getLayout()->getBlock('breadcrumbs')->toHtml(); ?>
   
    By default this code is written in layout page. (e.g. 1column.phtml)

>> I'll show you the another way by xml:
        <reference name="root">
            <action method="unsetChild"><alias>breadcrumbs</alias></action>
            <block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs">
                <action method="addCrumb">
                    <crumbName>Home</crumbName>
                    <crumbInfo><label>Home</label><title>Home</title><link>/</link></crumbInfo>
                </action>
                <action method="addCrumb">
                    <crumbName>Parent Page</crumbName>
                    <crumbInfo><label>Parent Page</label><title>Parent Page</title><link>/Parent Page link</link></crumbInfo>
                </action>
                <action method="addCrumb">
                    <crumbName>Current Page</crumbName>
                    <crumbInfo><label>Current Page</label><title>Current Page</title></crumbInfo>
                </action>
            </block>
        </reference>



  
  You can use it in your custom module xml, admin category custom layout update section and also CMS page layout update xml section.




Monday, November 26, 2012

Automatically shipment and invoice order in Magento

>> In magento to complete an order from admin you need to create an Invoice then a Shipment. If you want to make it by once click on shipment button. you can easily try this code to get the result.

     $order = $orderObj;                  // get your order object.

     if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) {
            
            try {
                if(!$order->canInvoice()) {
                    $order->addStatusHistoryComment('Order cannot be invoiced.', false);
                    $order->save();
                }
                
                //START Handle Invoice
                $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();

                $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
                $invoice->register();

                $invoice->getOrder()->setCustomerNoteNotify(false);        
                $invoice->getOrder()->setIsInProcess(true);
                $order->addStatusHistoryComment('Automatically INVOICED.', false);

                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder());

                $transactionSave->save();
                //END Handle Invoice
                
                //START Handle Shipment
                $shipment = $order->prepareShipment();
                $shipment->register();

                $order->setIsInProcess(true);
                $order->addStatusHistoryComment('Automatically SHIPPED.', false);

                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($shipment)
                    ->addObject($shipment->getOrder())
                    ->save();
                //END Handle Shipment
            } catch (Exception $e) {
                $order->addStatusHistoryComment('Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
                $order->save();
            }              
     }

Now see I've implemented it in shipment save action, means when you'll click on the shipment button to create the shipment, it'll automatically generate the invoice also. Go to app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
find the saveAction() method and replace it with the following code :

        public function saveAction()
        {
            $data = $this->getRequest()->getPost('shipment');
            if (!empty($data['comment_text'])) {
                Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
            }
       
            try {
                $shipment = $this->_initShipment();
                if (!$shipment) {
                    $this->_forward('noRoute');
                    return;
                }
       
                $shipment->register();
               
                $order = $shipment->getOrder();
                if(!$order->canInvoice()) {
                    $order->addStatusHistoryComment('Order cannot be invoiced.', false);
                    $order->save();
                }
               
                //START Handle Invoice
                $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
       
                $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
                $invoice->register();
       
                $invoice->getOrder()->setCustomerNoteNotify(false);       
                $invoice->getOrder()->setIsInProcess(true);
                $order->addStatusHistoryComment('Automatically INVOICED.', false);
       
                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder());
       
                $transactionSave->save();
                //END Handle Invoice
               
                $comment = '';
                if (!empty($data['comment_text'])) {
                    $shipment->addComment(
                        $data['comment_text'],
                        isset($data['comment_customer_notify']),
                        isset($data['is_visible_on_front'])
                    );
                    if (isset($data['comment_customer_notify'])) {
                        $comment = $data['comment_text'];
                    }
                }
       
                if (!empty($data['send_email'])) {
                    $shipment->setEmailSent(true);
                }
       
                $shipment->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
                $responseAjax = new Varien_Object();
                $isNeedCreateLabel = isset($data['create_shipping_label']) && $data['create_shipping_label'];
       
                if ($isNeedCreateLabel && $this->_createShippingLabel($shipment)) {
                    $responseAjax->setOk(true);
                }
       
                $this->_saveShipment($shipment);
       
                $shipment->sendEmail(!empty($data['send_email']), $comment);
       
                $shipmentCreatedMessage = $this->__('The shipment has been created.');
                $labelCreatedMessage    = $this->__('The shipping label has been created.');
       
                $this->_getSession()->addSuccess($isNeedCreateLabel ? $shipmentCreatedMessage . ' ' . $labelCreatedMessage
                    : $shipmentCreatedMessage);
                Mage::getSingleton('adminhtml/session')->getCommentText(true);
            } catch (Mage_Core_Exception $e) {
                if ($isNeedCreateLabel) {
                    $responseAjax->setError(true);
                    $responseAjax->setMessage($e->getMessage());
                } else {
                    $this->_getSession()->addError($e->getMessage());
                    $this->_redirect('*/*/new', array('order_id' => $this->getRequest()->getParam('order_id')));
                }
            } catch (Exception $e) {
                Mage::logException($e);
                if ($isNeedCreateLabel) {
                    $responseAjax->setError(true);
                    $responseAjax->setMessage(
                        Mage::helper('sales')->__('An error occurred while creating shipping label.'));
                } else {
                    $this->_getSession()->addError($this->__('Cannot save shipment.'));
                    $this->_redirect('*/*/new', array('order_id' => $this->getRequest()->getParam('order_id')));
                }
       
            }
            if ($isNeedCreateLabel) {
                $this->getResponse()->setBody($responseAjax->toJson());
            } else {
                $this->_redirect('*/sales_order/view', array('order_id' => $shipment->getOrderId()));
            }
        }

Hope it'll help you..........   :)


Friday, November 23, 2012

Create stylish file upload button in jquery


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Stylish file input</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
            <script type="text/javascript">
            // JavaScript Document
            jQuery(document).ready(function(){
                jQuery('input:file').each(function(){
                   
                    jQuery(this)
                        .wrap('<div class="file-wrapper"></div>')
                        .css({'z-index':1000,'position':'relative','opacity':0,'-khtml-appearance':'none'})
                        .attr('size', 1)
                        .before('<span class="file"><label>No file choosen</label></span>')
                        .change(function(){
                            var val = jQuery(this).val();
                            var str = val.split(/[\s/\\]+/);
                            jQuery(this).prev('span.file').html("<label>"+str[str.length-1]+"</label>");
                        });
                   
                });
            });
            </script>
            <style type="text/css">
            .file-wrapper {
                clear: both;
                display: block;
                height: 23px;
                margin-bottom: 10px;
                position: relative;
            }
            .file {
                background: url("choose.png") no-repeat scroll 0 0 transparent;
                font-family: Arial;
                font-size: 13px;
                height: 30px;
                left: 0;
                position: absolute;
                text-align: left;
                width: 400px;
            }
            .file label {
                color: #353535;
                float: left;
                font-family: Arial;
                font-size: 13px;
                line-height: 17px;
                margin: 0;
                font-weight: normal;
                   padding-left: 110px;
            }
            .file-input-type{
                margin-top:10%;
                margin-left:10%;
            }
            </style>
    </head>
   
    <body>
            <div class="file-input-type">
              <input name="image1" type="file" class="file1">
            </div>
    </body>
</html>


see the demo here.