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.


Create custom pagination in magento


Hope you known about block, xml in Magento.
Here is an extracted code that would help you to create pagination with custom collection in magento.

    >> First paste the following code in your block class (e.g. product.php)
       
        <?php
        class example extends parentclass
        {
            private $_itemPerPage = 2;
            private $_pageFrame = 8;
            private $_curPage = 1;
           
            public function getCollection($collection = 'null')
            {
                if($collection != 'null'){
                    $page = $this->getRequest()->getParam('p');
                    if($page) $this->_curPage = $page;
                   
                    $collection->setCurPage($this->_curPage);
                    $collection->setPageSize($this->_itemPerPage);
                    return $collection;
                }
            }
           
            public function getPagerHtml($collection = 'null')
            {   
                $html = false;
                if($collection == 'null') return;
                if($collection->count() > $this->_itemPerPage)
                {
                    $curPage = $this->getRequest()->getParam('p');
                    $pager = (int)($collection->count() / $this->_itemPerPage);
                    $count = ($collection->count() % $this->_itemPerPage == 0) ? $pager : $pager + 1 ;
                    $url = $this->getPagerUrl();
                    $start = 1;
                    $end = $this->_pageFrame;
                   
                    $html .= '<ol>';
                    if(isset($curPage) && $curPage != 1){
                        $start = $curPage - 1;                                       
                        $end = $start + $this->_pageFrame;
                    }else{
                        $end = $start + $this->_pageFrame;
                    }
                    if($end > $count){
                        $start = $count - ($this->_pageFrame-1);
                    }else{
                        $count = $end-1;
                    }
                   
                    for($i = $start; $i<=$count; $i++)
                    {
                        if($i >= 1){
                            if($curPage){
                                $html .= ($curPage == $i) ? '<li class="current">'. $i .'</li>' : '<li><a href="'.$url.'&p='.$i.'">'. $i .'</a></li>';
                            }else{
                                $html .= ($i == 1) ? '<li class="current">'. $i .'</li>' : '<li><a href="'.$url.'&p='.$i.'">'. $i .'</a></li>';
                            }
                        }
                       
                    }
                   
                    $html .= '</ol>';
                }
               
                return $html;
            }
           
            public function getPagerUrl()                            // You need to change this function as per your url.
            {
                $cur_url = mage::helper('core/url')->getCurrentUrl();
                $new_url = preg_replace('/\&p=.*/', '', $cur_url);
               
                return $new_url;
            }
       
        }
        ?>
       
    >> Now you have to modify your frontend phtml page. (e.g. custom.phtml)
       
        <?php
            $_collections = $this->getProductCollection();            // Default Collection on which you'll implement pagination.
            $_productCollection = $this->getCollection($_collections);  // calling the function that have been created in block page.
            foreach ($_productCollection as $_product):

           ------------------ Your code here ------------

           endforeach;
        ?>   
        <?php if($this->getPagerHtml($this->getProductCollection())):?>        // pass the default collection as parameter
        <div class="pages">
            <span><?php echo $this->__('Page : ');?></span>
            <?php echo $this->getPagerHtml($this->getProductCollection());?>
        </div>
        <?php endif;?>
       
       
       
       
       
       
       
       

Friday, November 9, 2012

get product quantity/qty in Magento


>> $_product is your product object. = Mage::getModel('catalog/product')->load('product_id');

    <?php
      $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
      $qty = $stock->getQty();
      print_r( $stock->getData());      // To get other stock information.
    ?>

Thursday, November 8, 2012

How to redirect in magento


>> Pass the url in this function :

    public function redirect($url)
    {
        return Mage::app()->getFrontController()
                       ->getResponse()
                       ->setRedirect($url);  
    }



Tuesday, November 6, 2012

Change default sort by order for one category in Magento


>> If you want to change default sort by value "position" to "name", change admin category setting. see the screen-shot.

   

    you can change default direction by providing the following code in Custom Layout Update section in admin category "Custom Design" Tab
    <reference name="product_list_toolbar">
          <action method="setDefaultDirection"><dir>desc</dir></action>
    </reference>

>> Add "created_at" in sort by dropdown.


    update eav_attribute set frontend_label = "Date" where attribute_code = "created_at" AND entity_type_id = 4; // Ensure about the entity_type_id
    update catalog_eav_attribute set used_for_sort_by = 1 where attribute_id = (select attribute_id from eav_attribute where attribute_code = "created_at" AND entity_type_id = 4);
   
    Now You can see the Date in admin default sort by configuration.
    Admin=>System=>Configuration=>Catalog=>Frontend=> change value here "Product Listing Sort by"

>> If you want to add another attribute, go to the attribute setting and set "yes" for use for default sort by, see the screen-shot.

    Admin=>Attributes=>Manage Attributes