Tuesday 29 December 2015

Add Field in Account Information in magento admin panel direct database

Add field in          ---------> eav_attribute table
Add field in          ---------> customer_eav_attribute table
Add field in          ---------> customer_form_attribute table

Friday 20 November 2015

Upgrade Mysql version 5.6.0 or later ubuntu upgrade

For 14.04 users:

Ubuntu 14.04 defaults to MySQL 5.5, but also has MySQL 5.6 available for installation from the universe archive. Installing 5.6 is as easy as specifying the version:
myuser@mypc:~$ sudo apt-get purge mysql-server-5.5 mysql-client-5.5
myuser@mypc:~$ sudo apt-get autoremove
myuser@mypc:~$ sudo apt-get install mysql-server-5.6 mysql-client-5.6
If you have existing data in a MySql 5.5 database, it should be migrated automatically. Though it is always a good idea to make a backup before doing a major upgrade.

First make a backup of the data in your existing database:

mysqldump --lock-all-tables -u root -p --all-databases > dump.sql
Then after installing the newer version, you can restore if needed by running:

mysql -u root -p < dump.sql 

Tuesday 17 November 2015

How to upload a project to Github





  1. cd var/www/html/github/my-first-pro/
  2. git add .
  3. git commit -m "adding files". -m
  4. git commit -m "adding files". -a
  5. git remote add origin https://github.com/Kanasagra-Jaydip/my-first-pro.git
  6. git push -u origin master

Here is how you would do it in Windows:
  1. If you don't have git installed, see this article on how to set it up.
  2. Open up a Windows command prompt.
  3. Change into the directory where your source code is located in the command prompt.
  4. First, create a new repository in this directory git init. This will say "Initialized empty git repository in ....git" (... is the path).
  5. Now you need to tell git about your files by adding them to your repository. Do this with git add filename. If you want to add all your files, you can do git add .
  6. Now that you have added your files and made your changes, you need to commit your changes so git can track them. Type git commit -m "adding files". -m lets you add the commit message in line.
So far, the above steps is what you would do even if you were not using github. They are the normal steps to start a git repository. Remember that git is distributed (decentralized), means you don't need to have a "central server" (or even a network connection), to use git.
Now you want to push the changes to your git repository hosted with github. To you this by telling git to add a remote location, and you do that with this command:
git remote add origin https://github.com/yourusername/your-repo-name.git
Once you have done that, git now knows about your remote repository. You can then tell it to push (which is "upload") your commited files:
git push -u origin master

How to add grouped products in Magento



In Magento, you can easily create a grouped product. Customers can choose this grouped product to buy all products in group or only buy some of the associated products.

Step 1: Login to your Magento Admin Panel, go to Catalog -> Manage Products




Step 2: On Manage Products page, choose Add Product



Step 3: In Product Type drop-down menu, choose Grouped Product option and then click Continue



Step 4: You should fill all necessary information and settings for this grouped product. Most of settings and information are configured in the same way as they are configured when add a simple product. There only have some differences in weight and price because they are managed by the products that are added into group. Besides, you should mark the checkbox of products you want to add to the grouped product in Associated Products



Finally, you should click Save button

How to Create Creditit Memo in Magento

Once transaction is processed and invoice created, you need to create credit memo if you want to refund the customer. In Magento, the best way to do it is to open order in question and go to the invoice list on the left side of the order form. Click on an invoice you want to refund. Invoice detail information will appear. Now click on 'Credit Memo...' button on top of the form. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf

In list of products, you can choose quantity to refund and return to stock. Maximum qty is added by default. Additionally, you can specify 'Refund Shipping' amount and adjustment amounts which are added or subtracted from refund total. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf

When you are satisfied with amount to refund, you can continue with credit memo process. There are two ways to refund, offline and online. Online refund is used if transaction is made through Authorize.net or similar payment gateway. This way Magento will try to automatically refund the customer credit cart trough gateway API. If you choose to refund custom by using offline refund it will only create internal Magento credit memo and not contact any payment gateway. This method is used for check / money transfers or if you used 'Authorize Only' payment type. Using this credit memo type will allow you to continue with Magento order process, but you will have to refund the money to customer manually trough payment gateways website if one is used. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf

In list of products, you can choose quantity to refund and return to stock. Maximum qty is added by default. Additionally, you can specify 'Refund Shipping' amount and adjustment amounts which are added or subtracted from refund total. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf

Once transaction is processed and invoice created, you need to create credit memo if you want to refund the customer. In Magento, the best way to do it is to open order in question and go to the invoice list on the left side of the order form. Click on an invoice you want to refund. Invoice detail information will appear. Now click on 'Credit Memo...' button on top of the form. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf
Once transaction is processed and invoice created, you need to create credit memo if you want to refund the customer. In Magento, the best way to do it is to open order in question and go to the invoice list on the left side of the order form. Click on an invoice you want to refund. Invoice detail information will appear. Now click on 'Credit Memo...' button on top of the form. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf
Once transaction is processed and invoice created, you need to create credit memo if you want to refund the customer. In Magento, the best way to do it is to open order in question and go to the invoice list on the left side of the order form. Click on an invoice you want to refund. Invoice detail information will appear. Now click on 'Credit Memo...' button on top of the form. - See more at: http://www.magedevelopers.com/blog/magento-tutorials/refund-credit-memo-creation-magento/#sthash.R7HV0Ur1.dpuf

Friday 6 November 2015

Disable mod_rewrite for subdirectory OR Set Apache Password Protected Directories With .htaccess File OR API Protected


If you don't know the username and password to enter, then you can't access the page or site - it's "password protected". It's sometimes handy to be able to password protect your pages like this - for example:


  1. You're building a new site, but you only want yourself (and maybe a select few) to be able to view the work-in-progress.
  2. You have an area of your site that you never want the general public to have access to - for example, your web stats or private pages.
  3. You have some paid (subscription) content on your site that only subscribers should be able to access.
  4. Apache lets you password protect individual files, folders, or your entire site fairly easily. Read on to find out how it's done.


  1. Create a special file called .htaccess in the folder you want to protect.
ErrorDocument 401 "Unauthorized"
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/*/public_html/directory/.htpasswd
require user myusername_same_as_.htpasswd_file
     2. Creating the password file Called .htpasswd
The first step is to create a simple text file that will store your username and password, separated by a colon (:). The small catch is that the password must be encrypted. Luckily, there are many free web-based utilities that will encrypt the password for you. Try one of these:
myusername_same_as_.htaccess_file:$apr1$TSQAiMQm$MIJ.m3qpJ3mnY6NXdzppz. 

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();
            }                
        }

Thursday 27 August 2015

Redirect all urls exactly, just change domain name

How to change domain using htaccess file

Many times we have a in CMS and Ecommerce website to change the domain due to maintenance or other reason but the main headache is the suburl (categories or collection) should be work as it is other wise we need to write the 301 url redirect for each and every url to not get the SEO errors.
This is tutorial will be help for the following CMS :
  1. wordpress development
  2. Joomal development
  3. Drupal development
There are Ecommerce platform that get help from this
  1. Magento development
  2. Opencart development
  3. Woocommerce
  4. Virtumart
So here is the simple and easy option that will work using the add the few lines in the htaccess file (if file not available create it .htaccess).


RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)domain\.com$ [NC]
RewriteRule ^ http://newdomain.com%{REQUEST_URI} [L,R=301]

Saturday 22 August 2015

amazon

Get controller, module, action and router name

You can easily get controller name, action name,
router name and module name in any template file or class file. 

IN TEMPLATE FILES
 
$this->getRequest() can be used in template (phtml) files. 

 
/**
 * get Controller name
 */
$this->getRequest()->getControllerName();

/**
 * get Action name, i.e. the function inside the controller
 */
$this->getRequest()->getActionName();

/**
 * get Router name
 */
$this->getRequest()->getRouteName();

/**
 * get module name
 */
$this->getRequest()->getModuleName();
 
 /**
 * get Current URL
 */ 
 
$currentUrl = Mage::helper('core/url')->getCurrentUrl();
$url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
$path = $url->getPath(); 


IN CLASS FILES

/**
* get Controller name
*/
Mage::app()->getRequest()->getControllerName();
/**
* get Action name, i.e. the function inside the controller
*/
Mage::app()->getRequest()->getActionName();
/**
* get Router name
*/
Mage::app()->getRequest()->getRouteName();
/**
* get module name
*/
Mage::app()->getRequest()->getModuleName();

Thursday 20 August 2015

Simple Ajax add to cart in magento

list.phtml page in template

<form class="product_addtocart_form" action="<?php echo $this->getAddToCartUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
 <?php if(!$_product->isGrouped()): ?>
                         <label for="qty" class="qtylabel" style=""><?php echo $this->__('Qty') ?>:</label>
 <input type="text" class="form-control qtybox" name="qty">
 <?php endif; ?>
 <button type="submit" class="link_cart"><span><i class="fa fa-shopping-cart" style="margin-right: 5px;"></i><?php echo $this->__('Add to Cart') ?></span></button>
 </form>

<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('.product_addtocart_form').submit(function(event){
            event.preventDefault();
            var $this = jQuery(this);
            jQuery($this).parents('li').append('<div class="ajax_loader"></div>');
            url = jQuery(this).attr('action');
            console.log(jQuery(this).serialize());
            url += '&isAjax=1';
            var data = jQuery(this).serialize();
            data += '&isAjax=1';
            jQuery.ajax({
                    url : url,
                    dataType : 'json',
                    type : 'post',
                    data : data,
                    success : function(data) {
                        getcartdata($this);
                    }
                });
            setTimeout(function(){
                //getcartdata($this);
            },1000);
        });
    });






    function getcartdata($this){
        jQuery.ajax( {
            url : "<?php echo Mage::getBaseUrl().'getcitys/index/getcartdetail'; ?>",
            dataType : 'html',
            type : 'get',
            success : function(data) {
                jQuery('.ajax_loader').hide();
                jQuery('.block-cart-header').html(data);
            }
        });
    }
</script>

Make in controllers/IndexController.php

public function getcartdetailAction() {
        $block = $this->getLayout()->createBlock('checkout/cart_sidebar');
        $block->setTemplate('checkout/cart/sidebar_header_ajax.phtml');
        echo $block->toHtml();exit;
 }


view.phtml page in template
 
productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {
                var form = this.form;
                var oldUrl = form.action;

                if (url) {
                   form.action = url;
                }
                var e = null;
                try {
                    this.form.submit();
                } catch (e) {
                }
                this.form.action = oldUrl;
                if (e) {
                    throw e;
                }

                if (button && button != 'undefined') {
                    button.disabled = true;
                }
            }
           
        }.bind(productAddToCartForm);

Replace above code To below code


productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {
                var form = this.form;
                var oldUrl = form.action;

                if (url) {
                   form.action = url;
                }
                var e = null;
                if(!url){
                    url = jQuery('#product_addtocart_form').attr('action');
                }
                var data = jQuery('#product_addtocart_form').serialize();
                data += '&isAjax=1';
                try {
                    jQuery('.product-shop').prepend('<div class="ajax_loader">&nbsp;</div>');
                    jQuery.ajax({
                          url: url,
                          dataType: 'json',
                          type : 'post',
                          data: data,
                          success: function(data){
                                getcartdata(this);
                          }
                    });
                    setTimeout(function(){
                        getcartdata(this.form);
                    },1000);
                } catch (e) {
                }
                this.form.action = oldUrl;
                if (e) {
                    throw e;
                }
            }
        }.bind(productAddToCartForm);

Write Bottom in view page

<script type="text/javascript">
    function getcartdata($this){
        jQuery.ajax( {
            url : "<?php echo Mage::getBaseUrl().'getcitys/index/getcartdetail'; ?>",
            dataType : 'html',
            type : 'get',
            success : function(data) {
                jQuery('.ajax_loader').hide();
                jQuery('.block-cart-header').html(data);
            }
        });
    }
</script>

Wednesday 19 August 2015

How to import database using ubuntu terminal or windwos CMD

For linux ubunto
pv /var/www/html/decorati_main.sql.gz | gunzip | mysql -u root -p root

apt-get install pv
pv /var/www/html/decorati_main.sql.gz | gunzip | mysql -u root -p  decorativeplumb

For Windows

mysql -uroot -ppassword mydb > myfile.sql.gz

Tuesday 18 August 2015

How to get only cart sidebar Layout block in magento

In your controller you could try something like this:

$block = $this->getLayout()->createBlock('checkout/cart_sidebar');

$block->setTemplate('checkout/cart/sidebar.phtml');
 
Depending on your configuration (Config -> Checkout -> Shopping Cart Sidebar),
you can render the template with  
 
$block->toHtml(); 
If you use a custom template, you could ignore the config value so it renders anytime.

JQuery serialize() function with $.ajax() post for bigger HTML forms

JQuery provides a very useful function jQuery.serialize() which encodes a set of form elements as a string for submission, and is very useful while we are dealing with huge HTML forms. Basically it will combine your values of form element and then you can post it on any server side scripting page.

For example, suppose you have a very long form with many fields and you want to post it with the help of $.ajax() function, you need to add just few lines of code for jquery from with ajax, no need to add id attribute to any form elements, just have to give id to form itself as follows:

<form name="frm_details" id="frm_details" method="post">
<input type="text" name="name" value="jems">
<input type="submit" name="submit" value="submit">
</form>

The above form will have all the fields like text boxes, text areas, select boxes, radios etc. having only name attribute, just as our usual html form. Now the JQuery code will be as follows:
<script>
 $(function() {
   $("#product_details").on("submit", function(event) {
      event.preventDefault();

      $.ajax({
         url: "somefile.php",
         type: "post",
         data: $(this).serialize(),
         success: function(d) {
           alert(d);
         }
      });
    });
  });
</script>

Saturday 8 August 2015

Including jQuery condition if in page have jQuery or not

// Including jQuery conditionnally.
  if (typeof jQuery === 'undefined') {
    document.write("\u003cscript src=\"\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1\/jquery.min.js\" type=\"text\/javascript\"\u003e\u003c\/script\u003e");
    document.write('<script type="text/javascript">jQuery.noConflict();<\/script>');
  }

Monday 20 July 2015

How to Set, Retrieve and Unset Session Variables in Magento

Set session Data


$session = Mage::getSingleton("core/session", array("name"=>"frontend"));

$session->setData("day_filter", 'weeks');
$session->setData("days", '5');          
$session->setData("next_delivery_date", '2012-05-12');
 
or
 
Mage::getSingleton('core/session')->setIsSalesrepTax('test'); 
 

UnSet session Data

 
$session->unsetData('day_filter');
$session->unsetData('days');
$session->unsetData('next_delivery_date'); 
$session->unsetData('IsSalesrepTax');  

Session Data Set to null

$session->setData('day_filter', NULL);
$session->setData('days', NULL);
$session->setData('next_delivery_date', NULL); 
 
 

Magento Set, Retrieve and Unset Session Variables

 To set a Magento session variable:

$myValue = 'My session';
Mage::getSingleton('core/session')->setMyValue($myValue);
 

To Retrieve:

$myValue=Mage::getSingleton('core/session')->getMyValue();

To Unset:

Mage::getSingleton('core/session')->unsMyValue();

Wednesday 15 July 2015

Reverse array values while keeping keys

$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5'); $k = array_keys($a);$v = array_values($a); $rv = array_reverse($v); $b = array_combine($k, $rv); var_dump($b);
 
 
Result: 

array(5) { 'a' => string(2) "a5" 'b' => string(2) "a4" 'c' => string(2) "a3" 'd' => string(2) "a2" 'e' => string(2) "a1"}