Tuesday 29 September 2015

Custom Magento CMS page layout

Add new custom layout for few cms pages in one Magento shop. It’s really useful for different static pages of your shop. First create extension with only config file in it: app/code/local/Metizsoft/CmsPageLayout/etc/config.xml

<?xml version="1.0"?>
<config>
 <global>
  <page>
   <layouts>
    <custom_static_page_one>
     <label>Must Login Page</label>
     <template>page/mustloginpage.phtml</template>
    </custom_static_page_one>
   </layouts>
  </page>
 </global>
</config>
Then activate it: app/etc/modules/Metizsoft_CmsPageLayout.xml

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

Clear cache, add your page/mustloginpage.phtml template file (or copy some default one for start) to your current theme and you’re done

Monday 28 September 2015

Creating xml file of all products fields in magento programmatically

I will be using Varien_Simplexml_Element class to read write xml nodes. The path to this class file is lib/Varien/Simplexml/Element.php

Here is a sample XML file which I am going to read through Magento code. I will also be adding an XML node to the following XML data.

$file = "products.xml";
        if (file_exists($file)) { unlink ($file); }
       
        $products = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('status', array('eq' => '1'))
                    ->addAttributeToFilter('type_id', array('eq' => 'simple'));
       
        //process your product collection as per your bussiness logic
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $productsX = $doc->createElement( "products" );
        $doc->appendChild( $productsX );
        foreach($products as $_product){

            $product = $doc->createElement( "product" );

            $sku = $doc->createElement( "sku" );
            $sku->appendChild(
             $doc->createTextNode($_product->getSku())
            );
            $product->appendChild($sku);

            $name = $doc->createElement("name");
            $name->appendChild(
             $doc->createTextNode( trim($_product->getName()) )
            );
            $product->appendChild($name);

            $image = $doc->createElement( "image" );
            $image->appendChild(
             $doc->createTextNode( trim($_product->getData('image')) )
            );
            $product->appendChild( $image );

            $smallimage = $doc->createElement( "smallimage" );
            $smallimage->appendChild(
             $doc->createTextNode( trim($_product->getData('small_image')) )
            );
            $product->appendChild( $smallimage );

            $thumbnail = $doc->createElement( "thumbnail" );
            $thumbnail->appendChild(
             $doc->createTextNode( trim($_product->getData('thumbnail')) )
            );
            $product->appendChild( $thumbnail );

            $urlkey = $doc->createElement( "urlkey" );
            $urlkey->appendChild(
             $doc->createTextNode( trim($_product->getData('url_key')) )
            );
            $product->appendChild( $urlkey );

            $shippingdelivery = $doc->createElement( "shippingdelivery" );
            $shippingdelivery->appendChild(
             $doc->createTextNode( trim($_product->getShippingDelivery()) )
            );
            $product->appendChild( $shippingdelivery );

            $shippingweight = $doc->createElement( "shippingweight" );
            $shippingweight->appendChild(
             $doc->createTextNode( trim($_product->getShippingWeight()) )
            );
            $product->appendChild( $shippingweight );

            $alu = $doc->createElement( "alu" );
            $alu->appendChild(
             $doc->createTextNode( trim($_product->getAlu()) )
            );
            $product->appendChild( $alu );

            $upsize = $doc->createElement( "upsize" );
            $upsize->appendChild(
             $doc->createTextNode( trim($_product->getUpsize()) )
            );
            $product->appendChild( $upsize );

            $price = $doc->createElement( "price" );
            $price->appendChild(
             $doc->createTextNode( trim($_product->getPrice()) )
            );
            $product->appendChild( $price );

            $specialprice = $doc->createElement( "specialprice" );
            $specialprice->appendChild(
             $doc->createTextNode( trim($_product->getSpecialPrice()) )
            );
            $product->appendChild( $specialprice );

            $color = $doc->createElement( "color" );
            $color->appendChild(
             $doc->createTextNode( trim($_product->getResource()->getAttribute('color')->getFrontend()->getValue($_product)))
            );
            $product->appendChild( $color );

            $status = $doc->createElement( "status" );
            $status->appendChild(
             $doc->createTextNode( trim($_product->getResource()->getAttribute('status')->getFrontend()->getValue($_product)) )
            );
            $product->appendChild( $status );

            $description = $doc->createElement( "description" );
            $description->appendChild(
             $doc->createTextNode( trim($_product->getDescription()) )
            );
            $product->appendChild( $description );

            $qty = $doc->createElement( "qty" );
            $qty->appendChild(
             $doc->createTextNode( trim(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()) )
            );
            $product->appendChild( $qty );

            $availability = $doc->createElement( "availability" );
            $availability->appendChild(
             $doc->createTextNode( trim(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getIsInStock()) )
            );
            $product->appendChild( $availability );

            $productsX->appendChild($product); 
        }
        file_put_contents($file,$doc->saveXML(),FILE_APPEND);

Friday 18 September 2015

Add product to cart but price getting 0 or NULL in magento API

I’m testing out the Cart API and it seems I cannot get any data related to price, total price, etc until I enter in customer information.  The variables are there, but all of the price values are null/0. Is this the intended functionality, or am I doing something wrong?

The code below works except any variable relating to the price is null.

<pre>
<?php
$client = new SoapClient('http://magento.com/api/soap/?wsdl');
$session = $client->login('jemsw','write');
$cartId = $client->call($session,'cart.create',array(0));
$result = $proxy->call($sessionId, 'cart_product.add', array($cartId, array("product_id" => 53,"qty" => 2)));
$result = $client->call($session,'cart.totals',array($cartId));
print_r($result);
?></pre>

Array(
    [0] => Array(
        [title] => Subtotal
        [amount] =>
        )
        [1] => Array(
        [title] => Grand Total
        [amount] =>
        )
    )

If I add this code in after add product to cart `cart_product.add` the price is reflected correctly.

<pre>
<?php

    $client = new SoapClient('http://magento.com/api/soap/?wsdl');$session = $client->login('jemsw','write');

    $cartId = $client->call($session,'cart.create',array(0));

    $result = $proxy->call($sessionId, 'cart_product.add', array($cartId, array("product_id" => 53,"qty" => 2)));


    ################################################################################


    $arrAddresses = array(

        array(

            "mode" => "shipping",

            "firstname" => "test",

            "lastname" => "test",

            "company" => "test",

            "street" => "test",

            "city" => "test",

            "region" => "test",

            "postcode" => "test",

            "country_id" => "id",

            "telephone" => "0123789",

            "fax" => "01234589",

            "is_default_shipping" => 0,

            "is_default_billing" => 0

        ),

        array(

            "mode" => "billing",

            "firstname" => "test",

            "lastname" => "test",

            "company" => "test",

            "street" => "test",

            "city" => "test",

            "region" => "test",

            "postcode" => "test",

            "country_id" => "id",

            "telephone" => "012356789",

            "fax" => "0123459",

            "is_default_shipping" => 0,

            "is_default_billing" => 0

        )

    );

    $resultCustomerAddresses = $client->call($session, "cart_customer.addresses", array($cartId, $arrAddresses));


    ################################################################################

    $result = $proxy->call($sessionId, "cart.info", array($cartId));

    print_r($result);

    ?>

    </pre>

Display Your Cart item with price. 

Saturday 12 September 2015

Dump jquery object in an alert box

I am not quite adept in maneuvering jQuery, and it came to a point that I need to debug a program that was passed down from me without a documentation.
I have this var a, an object, that I really want to know the content of its collection. In my mind I need a function like foreach() in PHP to iterate over this object variable. Upon researching I end up in using jQuery.each(). Now I can clearly iterate and see what was inside var a.
However, it was kind of annoying to alert once every value on the var a. What I wanna know if it's possible to display all the contents in just one pop of alert box?

Here is my code:

var acc = []
$.each(a, function(index, value) {
    acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));

Thursday 10 September 2015

Enable gzip compression

What is gzip Compression?

When a user visit your website a request is made to web server to deliver the requested data. The response of the server is directly proportional to the size in mb/kb of the page as generally all pages contains video, images and textual part. so as page size bigger response time will be higher
Gzip facilitate to compress the your webpages  video, image and textual and style sheets before serving the request them over to the browser. This really reduces response time since the files are now in less size due to compression.
Gzip is the technique right now most effecting in the all speed optimization concept

How Apply Gzip to Apache Server Website

First of all you need to have a “.htaccess” file, If not create it and edit with the following code.

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>


After Applying the code to the htaccess test the website url with a http://checkgzipcompression.com/.

Wednesday 9 September 2015

How to make custom PDF in magento admin panel


Put this code in your Controllers file.

How to make custom PDF in magento admin panel


$pdf = new Zend_Pdf();
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
        $page->setFont($font, 11);
       
        //add pages to main document
        $pdf->pages[] = $page;
        $top = $this->y;
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0.45));
        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.45));
        $page->drawRectangle(25, $top, 570, $top - 55);
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
       
        //Header order
        $titre = "Packingslip # 100000039";
        $page->drawText($titre, 40, $page->getHeight()-115, "UTF-8");
        $titre = "Order # 100000031";
        $page->drawText($titre, 40, $page->getHeight()-130, "UTF-8");
        $titre = "Order Date: Aug 20, 2015";
        $page->drawText($titre, 40, $page->getHeight()-145, "UTF-8");
       
        //Create rectangle
        $top -= 55;
        $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $top, 275, ($top - 25));
        $page->drawRectangle(275, $top, 570, ($top - 25));
       
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
        $page->drawText(Mage::helper('sales')->__('Sold to:'), 35, ($top - 15), 'UTF-8');
        $page->drawText(Mage::helper('sales')->__('Ship to:'), 285, ($top - 15), 'UTF-8');
       
        //Create rectangle
        $addressesHeight = 110;
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
        $page->drawRectangle(25, ($top - 25), 570, $top - 33 - $addressesHeight);
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
        $page->setFont($font, 10);
        $this->y = $top - 40;
        $addressesStartY = $this->y;
       
        //Billing Address
        $page->drawText(strip_tags(ltrim('Jaydip Kanasagra')), 35, $this->y, 'UTF-8');
        $page->drawText(strip_tags(ltrim('Metizsoft')), 35, $this->y-15, 'UTF-8');
        $page->drawText(strip_tags(ltrim('35 Brownsboro,')), 35, $this->y-30, 'UTF-8');
        $page->drawText(strip_tags(ltrim('Madison,')), 35, $this->y-45, 'UTF-8');
        $page->drawText(strip_tags(ltrim('Alabama, 33324')), 35, $this->y-60, 'UTF-8');
        $page->drawText(strip_tags(ltrim('United States')), 35, $this->y-75, 'UTF-8');
        $page->drawText(strip_tags(ltrim('T: (256) 683 - 0237')), 35, $this->y-90, 'UTF-8');
       
       
        //Shipping Address
        $page->drawText(strip_tags(ltrim('Jaydip Kanasagra')), 285, $this->y, 'UTF-8');
        $page->drawText(strip_tags(ltrim('Metizsoft')), 285, $this->y-15, 'UTF-8');
        $page->drawText(strip_tags(ltrim('35 Brownsboro,')), 285, $this->y-30, 'UTF-8');
        $page->drawText(strip_tags(ltrim('Madison,')), 285, $this->y-45, 'UTF-8');
        $page->drawText(strip_tags(ltrim('Alabama, 33324')), 285, $this->y-60, 'UTF-8');
        $page->drawText(strip_tags(ltrim('United States')), 285, $this->y-75, 'UTF-8');
        $page->drawText(strip_tags(ltrim('T: (256) 683 - 0237')), 285, $this->y-90, 'UTF-8');
        $this->y -= 110;
        $addressesEndY = $this->y;
       
        $addressesEndY = min($addressesEndY, $this->y);
        $this->y = $addressesEndY;
       
        //Create rectangle
        $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $this->y, 275, $this->y-25);
        $page->drawRectangle(275, $this->y, 570, $this->y-25);
       
        //Payment and Shipping Method
        $this->y -= 15;
        $page->setFont($font, 12);
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
        $page->drawText(Mage::helper('sales')->__('Payment Method'), 35, $this->y, 'UTF-8');
        $page->drawText(Mage::helper('sales')->__('Shipping Method:'), 285, $this->y , 'UTF-8');
       
        $this->y -=10;
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));

        $page->setFont($font, 10);
        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
       
        $paymentLeft = 35;
        $yPayments   = $this->y - 15;
       
        foreach (Mage::helper('core/string')->str_split('Cash On Pickup', 45, true, true) as $_value) {
            $page->drawText(strip_tags(trim($_value)), $paymentLeft, $yPayments, 'UTF-8');
            $yPayments -= 15;
        }
        $yPayments = min($addressesEndY, $yPayments)-60;
        $page->drawLine(25,  ($top - 150), 25,  $yPayments);
        $page->drawLine(570, ($top - 150), 570, $yPayments);
        $page->drawLine(25,  $yPayments,  570, $yPayments);
       
        foreach (Mage::helper('core/string')->str_split('Delivery - Delivery (Only available for local area)', 45, true, true) as $_value) {
            $page->drawText(strip_tags(trim($_value)), 285, $this->y-15, 'UTF-8');
            $this->y -= 15;
        }
        $topMargin    = 20;
        $methodStartY = $this->y;
        $yShipments = $this->y;
       
        $totalShippingChargesText = "(" . Mage::helper('sales')->__('Total Shipping Charges') . " $0.00)";
        $page->drawText($totalShippingChargesText, 285, $yShipments - $topMargin, 'UTF-8');
       
        $currentY = min($yPayments, $yShipments);
        // replacement of Shipments-Payments rectangle block
        $page->drawLine(25,  $methodStartY, 25,  $currentY); //left
        $page->drawLine(25,  $currentY,     570, $currentY); //bottom
        $page->drawLine(570, $currentY,     570, $methodStartY); //right
        $this->y = $currentY;
        $this->y -= 15;
       
        //Items
        $page->setFont($font, 10);
        $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $this->y, 570, $this->y-15);
        $this->y -= 10;
        $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));
       
        $page->drawText(Mage::helper('sales')->__('Qty'), 35, $this->y, 'UTF-8');
        $page->drawText(Mage::helper('sales')->__('Products'), 125, $this->y , 'UTF-8');
        $page->drawText(Mage::helper('sales')->__('Sku'), 550, $this->y , 'UTF-8');
       
        $test = array(0=>'test',1=>'test1',2=>'test2');
        $this->y = $this->y-15;
        foreach ($test as $_value) {
            $this->y -= 15;
            $page->drawText(strip_tags(trim('10')), 35, $this->y, 'UTF-8');
            $page->drawText(strip_tags(trim('SWISHER SWEET CGRL WGRP 2F.99')), 125, $this->y, 'UTF-8');
            $page->drawText(strip_tags(trim('025900227289')), 500, $this->y, 'UTF-8');
        }
       
        //generate pdf
        $content =  $pdf->render();
        $fileName = 'details.pdf';
        $this->_prepareDownloadResponse($fileName, $content);

Wednesday 2 September 2015

Tuesday 1 September 2015

How to create shipping and invoice in magneto by code or API


Various merchants, various demands. Imagine you have a private on site sale or something like that, where your checkout requirements are pretty simply: create invoice / ship and complete the order all at once. For example, you are doing the checkout for bunch of people standing in front of you, paying you money right on the spot. In such scenario overload of manually creating an invoice and shipment can be too much.

Thus, having your Magento automatically invoice/ship/complete orders can be a logical request. So how do we do that?

Easy! All you need to do is to observe the sales_order_save_after event or observe the controller_action_predispatch event and target the Mage_Checkout_OnepageController::successAction() catching the Mage::getSingleton(‘checkout/session’)->getLastOrderId(). In this example I decided to demonstrate the possible (not ideal, or not even the best) “sales_order_save_after event” approach. 

And here is the code for our observer model. 

$order = $observer->getEvent()->getOrder();
 
        $orders = Mage::getModel('sales/order_invoice')->getCollection()
                        ->addAttributeToFilter('order_id', array('eq'=>$order->getId()));
        $orders->getSelect()->limit(1);  
 
        if ((int)$orders->count() !== 0) {
            return $this;
        }
 
        if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) {
 
            try {
                if(!$order->canInvoice()) {
                    $order->addStatusHistoryComment('Inchoo_Invoicer: 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 by Invoicer.', 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 by Invoicer.', false);
 
                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($shipment)
                    ->addObject($shipment->getOrder())
                    ->save();
                //END Handle Shipment
            } catch (Exception $e) {
                $order->addStatusHistoryComment('Inchoo_Invoicer: Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
                $order->save();
            }                
        }