HTML/JavaScript

Monday, July 29, 2013

Useful Code Snippets

Create Order

Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.
   
$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);



// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());

$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2
    )
);

foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order->addItem($orderItem);
}

$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();



Creating Customer


Below is a php code to create a customer account in magento.

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';

    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);

    $customer->setConfirmation(null);
    $customer->save();

    echo $customer->getId();
}




Creating Invoice

Below is a php code to create invoice for an order in magento.
   
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
 
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
 
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
 
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
 
}



Create Shipment


Below is a php code to create a shipment for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());      
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}



Creating Credit Memo

Below is a php code to create a credit memo for an order in magento.
$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $data = array();

        
        $service = Mage::getModel('sales/service_order', $order);
       
        $creditmemo = $service->prepareCreditmemo($data);

        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,     min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
        echo $creditmemo->getIncrementId();

Useful Code Snippets

Create Order

Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.
   
$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);

// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());

$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2
    )
);

foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order->addItem($orderItem);
}

$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();



Creating Customer


Below is a php code to create a customer account in magento.

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';

    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);

    $customer->setConfirmation(null);
    $customer->save();

    echo $customer->getId();
}




Creating Invoice

Below is a php code to create invoice for an order in magento.
   
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
 
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
 
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
 
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
 
}



Create Shipment


Below is a php code to create a shipment for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());      
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}



Creating Credit Memo

Below is a php code to create a credit memo for an order in magento.
$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $data = array();

        
        $service = Mage::getModel('sales/service_order', $order);
       
        $creditmemo = $service->prepareCreditmemo($data);

        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,     min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
        echo $creditmemo->getIncrementId();

5 Magento Myths Dispelled


The more popular the platform is the more it is talked about. As online merchant “spinning in eCommerce circles” you have probably heard lot’s of things about Magento shopping cart. The undeniable official facts are:

- the open-source php-based platform was established in 2008 by Varien

- the world famous eBay corporation has made investment in Magento getting 49% ownership share

- currently Magento can boast of more than 125 000 devoted users

- more than 4 million software downloads were already performed

The opinions of users are not as straightforward, though. Some are really satisfied with platform’s rich functionality and powerful modular system. Other find considerable drawbacks of the solution claiming it to be difficult in management. When considering Magento for establishing online store it is important to create an unbiased impression and get away from inaccurate or cliche public talks.

So that your decision wasn’t affected by misconceptions we offer for your consideration 5 common Magento myths.

Myth 1. Magento is slow

The performance of any shopping platform depends on various factors so that’s incorrect to claim that Magento store will run slowly for everybody. The platform is quite complicated, which can influence the load time and performance. However, Magento developers realise the issue and are working on it, so each Magento version gets more optimized in these terms. The users find a lot of ways to make their Magento store faster. This includes:

    Hosting environment. Magento is not lightweight so it requires good dedicated servers to be hosted on. Shared unoptimized hosting will definitely slow down your store. It is recommended to host site in the country where the most of your traffic comes from.
    Templates optimization. If you choose the lightweight templates and resize images, Magento performance will appreciate this. The optimal size of images is below 10 kb. You can crop the unnecessary spaces in images or compress them with special tools. All of these measures will positively result in Magento speed.
    Configuration settings. Not to overload your shopping cart functionality, disable modules which are not essential for you. For this go to : System -> Configuration -> Advanced -> Advanced and change the settings in the dropdown list. Disabling layered navigation may be also helpful.



Myth 2. Magento is a free platform

In official and unofficial source you will find the statement that Magento is free open-source platform. Lots of people understand it to charge no fees for its use and are surprised to find the pricing page on Magento commerce official site. However, it is not the fraud. Magento shopping cart is really free and open-source however free here stands for the idea you have freedom to copy and reuse software rather than with regard to pricing.

Magento offers both free and paid edition. Community edition is not charged for, however it is limited in support and lacks some advanced features you can get with Enterprise edition. If you will require additional functionality you will have to purchase extensions. Two types of Enterprise Magento editions charge considerable amount of money annually, but offer more opportunities to develop. It’s up to you what amount of money you are ready to invest in business growth.

Myth 3. Magento doesn’t provide customer support


It is closely connected with the previous myth, as it has to do with pricing plan you choose. With Magento community edition you will have to rely on support from community members in online forums only. As Magento community is one of the biggest and most responsive in eCommerce industry it will not present much difficulties to find answers to questions you are interested in. Enterprise paid editions provide users with professional support on various issues like platform installation, hosting environment, basic configuration issues. It is available 24/7 and offers different communication channels.

Myth 4. Magento is easily customized


It depends on technical skills and experience of course. However, Magento is built on Zend Framework which is not quite easy to handle. Though the source code is open and can be modified, but the coding system itself is quite complicated. That makes customization time and resource consuming. Moreover, it is complicated by the lack of Magento technical documentation. So, the shopping cart allows customization but the user should be PHP expert and at least be familiar with Zend framework.

Myth 5. Magento is for large scale business only


The platform offers wide scalability. It works equally well for small stores and branched enterprises. You should estimate the level of your technical knowledge and the requirement of business to decide whether Magento is suitable for your store. With steep learning curve it will be more difficult for eCommerce startups to handle Magento, however on the other hand it promises potential business growth.

Now that you know all the truth about Magento you should rely on your sober mind and decide whether the platform is suitable for you business. The reason will also prompt you to use Cart2Cart for Magento migration. The service handles all the peculiarities of the shopping cart and makes data transfer accurate and fast. Check it by yourself! Demo Migration allows to transfer 10 products/customers/orders for absolutely free!

5 Magento Myths Dispelled




The more popular the platform is the more it is talked about. As online merchant “spinning in eCommerce circles” you have probably heard lot’s of things about Magento shopping cart. The undeniable official facts are:

- the open-source php-based platform was established in 2008 by Varien

- the world famous eBay corporation has made investment in Magento getting 49% ownership share

- currently Magento can boast of more than 125 000 devoted users

- more than 4 million software downloads were already performed

The opinions of users are not as straightforward, though. Some are really satisfied with platform’s rich functionality and powerful modular system. Other find considerable drawbacks of the solution claiming it to be difficult in management. When considering Magento for establishing online store it is important to create an unbiased impression and get away from inaccurate or cliche public talks.

So that your decision wasn’t affected by misconceptions we offer for your consideration 5 common Magento myths.

Myth 1. Magento is slow

The performance of any shopping platform depends on various factors so that’s incorrect to claim that Magento store will run slowly for everybody. The platform is quite complicated, which can influence the load time and performance. However, Magento developers realise the issue and are working on it, so each Magento version gets more optimized in these terms. The users find a lot of ways to make their Magento store faster. This includes:

    Hosting environment. Magento is not lightweight so it requires good dedicated servers to be hosted on. Shared unoptimized hosting will definitely slow down your store. It is recommended to host site in the country where the most of your traffic comes from.
    Templates optimization. If you choose the lightweight templates and resize images, Magento performance will appreciate this. The optimal size of images is below 10 kb. You can crop the unnecessary spaces in images or compress them with special tools. All of these measures will positively result in Magento speed.
    Configuration settings. Not to overload your shopping cart functionality, disable modules which are not essential for you. For this go to : System -> Configuration -> Advanced -> Advanced and change the settings in the dropdown list. Disabling layered navigation may be also helpful.

Myth 2. Magento is a free platform

In official and unofficial source you will find the statement that Magento is free open-source platform. Lots of people understand it to charge no fees for its use and are surprised to find the pricing page on Magento commerce official site. However, it is not the fraud. Magento shopping cart is really free and open-source however free here stands for the idea you have freedom to copy and reuse software rather than with regard to pricing.

Magento offers both free and paid edition. Community edition is not charged for, however it is limited in support and lacks some advanced features you can get with Enterprise edition. If you will require additional functionality you will have to purchase extensions. Two types of Enterprise Magento editions charge considerable amount of money annually, but offer more opportunities to develop. It’s up to you what amount of money you are ready to invest in business growth.

Myth 3. Magento doesn’t provide customer support


It is closely connected with the previous myth, as it has to do with pricing plan you choose. With Magento community edition you will have to rely on support from community members in online forums only. As Magento community is one of the biggest and most responsive in eCommerce industry it will not present much difficulties to find answers to questions you are interested in. Enterprise paid editions provide users with professional support on various issues like platform installation, hosting environment, basic configuration issues. It is available 24/7 and offers different communication channels.

Myth 4. Magento is easily customized


It depends on technical skills and experience of course. However, Magento is built on Zend Framework which is not quite easy to handle. Though the source code is open and can be modified, but the coding system itself is quite complicated. That makes customization time and resource consuming. Moreover, it is complicated by the lack of Magento technical documentation. So, the shopping cart allows customization but the user should be PHP expert and at least be familiar with Zend framework.

Myth 5. Magento is for large scale business only


The platform offers wide scalability. It works equally well for small stores and branched enterprises. You should estimate the level of your technical knowledge and the requirement of business to decide whether Magento is suitable for your store. With steep learning curve it will be more difficult for eCommerce startups to handle Magento, however on the other hand it promises potential business growth.

Now that you know all the truth about Magento you should rely on your sober mind and decide whether the platform is suitable for you business. The reason will also prompt you to use Cart2Cart for Magento migration. The service handles all the peculiarities of the shopping cart and makes data transfer accurate and fast. Check it by yourself! Demo Migration allows to transfer 10 products/customers/orders for absolutely free!


Friday, July 26, 2013

How to Random Products Home Magento

Create the Home Products file

In my theme I created a copy of the list.phtml called home_list.phtml

/app/design/frontend/base/theme156/template/catalog/product
Show the file in the Home Page

Now we need to show our new file in the Home Page.

Go to your Admin panel -> CMS -> Pages

You should have a page called something like Home. Open it and paste the following code:
{{block type="catalog/product_list" category_id="36" template="catalog/product/home_list.phtml"}}

NOTE: please notice the category_id. It will force to show a certain category. In my case a special one called Home Products.
Shuffle it



The code is quite simple. We need to add the shuffle function after getting all the products.

Look for the getItems() function and past it below.
    <?php $_items = $_productCollection->getItems();
        shuffle($_items); ?>
Break on 3

I added a counter to break the foreach. Something like:
// Show 3 items
$max_items = 3;
$personal_count = 1;

And then at the end:
  if($personal_count == $max_items){break;}
  else{$personal_count++;}
Full Code

Here’s my full code of the home_list.phtml. It will depend on your theme but the suffle part should be the same.
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   design_blank
 * @package    Mage
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php $userIsloggedIn = Mage::getSingleton('customer/session')->isLoggedIn(); ?>
<?php $_productCollection=$this->getLoadedProductCollection() ?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div style="clear:both;">&nbsp;</div>
<div class="category-products" style="border:none !important;">
  
    <div class="page-indent">   
        <?php // List mode ?>
        <?php if($this->getMode()!='grid'): ?>
        <?php $_iterator = 0; ?>
        <ol class="products-list" id="products-list">
        <?php $list_item=1; foreach ($_productCollection as $_product): ?>
            <li class="item<?php if($list_item==1){echo ' first ';} ?><?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                <?php // Product Image ?>
                <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                    <img src="<?php echo $this-/>helper('catalog/image')->init($_product, 'small_image')->resize(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" /></a>
  
                <?php // Product description ?>
                <div class="product-shop">
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName())?></a></h3>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <p><button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button></p>
                    <?php else: ?>
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>

                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>                   
                </div>
                <div class="clear"></div>
                <div class="desc std">
                    <?php echo nl2br($_product->getShortDescription()) ?>
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->__('Learn More') ?></a>
                </div>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
            </li>
        <?php $list_item++; endforeach; ?>
        </ol>
        <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
  
        <?php else: ?>
  
        <?php // Grid Mode ?>
  
        <?php $_collectionSize = $_productCollection->count() ?>
        <table class="products-grid" id="products-grid-table">
        <?php $_columnCount = 3/*$this->getColumnCount()*/; ?>
      
         <?php
            $_items = $_productCollection->getItems();
            shuffle($_items);
        ?>
      
        < ?
            // Show 3 items
            $max_items = 3;
            $personal_count = 1;
        ?>
        <?php $i=0; foreach ($_items as $_product): ?>
      
            <?php if ($i++%$_columnCount==0): ?>
            <tr>
            <?php endif ?>
                <td>
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
                    <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                        <img src="<?php echo $this-/>helper('catalog/image')->init($_product, 'small_image')->resize(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
                    </a>                   
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <button type="button" class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <?php else: ?>
                      
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>
                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>
                
                </td>
            <?php if ($i%$_columnCount==0 && $i!=$_collectionSize): ?>
            </tr>
            <?php endif ?>
            < ?
               if($personal_count == $max_items){break;}
               else{$personal_count++;}
            ?>
            <?php endforeach ?>
            <?php for($i;$i%$_columnCount!=0;$i++): ?>
                  <td class="empty">&nbsp;</td>
            <?php endfor ?>
            <?php if ($i%$_columnCount==0): ?>
          
            <?php endif ?>
        </table>
        <script type="text/javascript">decorateTable('products-grid-table')</script>
        <?php endif; ?>       
    </div>

</div>
<?php endif; ?>

How to Random Products Home Magento

Create the Home Products file

In my theme I created a copy of the list.phtml called home_list.phtml

/app/design/frontend/base/theme156/template/catalog/product
Show the file in the Home Page

Now we need to show our new file in the Home Page.

Go to your Admin panel -> CMS -> Pages

You should have a page called something like Home. Open it and paste the following code:
{{block type="catalog/product_list" category_id="36" template="catalog/product/home_list.phtml"}}

NOTE: please notice the category_id. It will force to show a certain category. In my case a special one called Home Products.
Shuffle it

The code is quite simple. We need to add the shuffle function after getting all the products.

Look for the getItems() function and past it below.
    <?php $_items = $_productCollection->getItems();
        shuffle($_items); ?>
Break on 3

I added a counter to break the foreach. Something like:
// Show 3 items
$max_items = 3;
$personal_count = 1;

And then at the end:
  if($personal_count == $max_items){break;}
  else{$personal_count++;}
Full Code

Here’s my full code of the home_list.phtml. It will depend on your theme but the suffle part should be the same.
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   design_blank
 * @package    Mage
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php $userIsloggedIn = Mage::getSingleton('customer/session')->isLoggedIn(); ?>
<?php $_productCollection=$this->getLoadedProductCollection() ?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div style="clear:both;">&nbsp;</div>
<div class="category-products" style="border:none !important;">
  
    <div class="page-indent">   
        <?php // List mode ?>
        <?php if($this->getMode()!='grid'): ?>
        <?php $_iterator = 0; ?>
        <ol class="products-list" id="products-list">
        <?php $list_item=1; foreach ($_productCollection as $_product): ?>
            <li class="item<?php if($list_item==1){echo ' first ';} ?><?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                <?php // Product Image ?>
                <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                    <img src="<?php echo $this-/>helper('catalog/image')->init($_product, 'small_image')->resize(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" /></a>
  
                <?php // Product description ?>
                <div class="product-shop">
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName())?></a></h3>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <p><button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button></p>
                    <?php else: ?>
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>

                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>                   
                </div>
                <div class="clear"></div>
                <div class="desc std">
                    <?php echo nl2br($_product->getShortDescription()) ?>
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->__('Learn More') ?></a>
                </div>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
            </li>
        <?php $list_item++; endforeach; ?>
        </ol>
        <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
  
        <?php else: ?>
  
        <?php // Grid Mode ?>
  
        <?php $_collectionSize = $_productCollection->count() ?>
        <table class="products-grid" id="products-grid-table">
        <?php $_columnCount = 3/*$this->getColumnCount()*/; ?>
      
         <?php
            $_items = $_productCollection->getItems();
            shuffle($_items);
        ?>
      
        < ?
            // Show 3 items
            $max_items = 3;
            $personal_count = 1;
        ?>
        <?php $i=0; foreach ($_items as $_product): ?>
      
            <?php if ($i++%$_columnCount==0): ?>
            <tr>
            <?php endif ?>
                <td>
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
                    <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                        <img src="<?php echo $this-/>helper('catalog/image')->init($_product, 'small_image')->resize(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
                    </a>                   
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <button type="button" class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <?php else: ?>
                      
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>
                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>
                
                </td>
            <?php if ($i%$_columnCount==0 && $i!=$_collectionSize): ?>
            </tr>
            <?php endif ?>
            < ?
               if($personal_count == $max_items){break;}
               else{$personal_count++;}
            ?>
            <?php endforeach ?>
            <?php for($i;$i%$_columnCount!=0;$i++): ?>
                  <td class="empty">&nbsp;</td>
            <?php endfor ?>
            <?php if ($i%$_columnCount==0): ?>
          
            <?php endif ?>
        </table>
        <script type="text/javascript">decorateTable('products-grid-table')</script>
        <?php endif; ?>       
    </div>

</div>
<?php endif; ?>

Thursday, July 25, 2013

Magento Application some useful functions we used in development

Sometimes we need to check the current host name in magento. Here is the function that returns the hostname of server where the application is executing.

The following code is same as normal PHP $_SERVER[‘HTTP_HOST’]

<?php      echo Mage::app()->getFrontController()->getRequest()->getHttpHost();?>

 It returns 127.0.0.1 if we runs on 127.0.0.1 or in other cases it returns the domain name of the site.
 When we want to retrieve the Path of Base Directory in Magento. We can use the following function

 <?php echo Mage::getBaseDir();  //gives  physical path of the sites root directory ?>

(In my case it return e:\www\magento )



Its returns the Physical path of the Application directory where magento application installed.
When we want to retrieve the relative path of the sites default skin folder. IT return the virtual path of the default skin folder. Many time we used in theme development

 <?php echo $this->getSkinURL(); ?>

 It returns the http://127.0.0.1/www/magento/skin/frontend/default/default/
Virtual path of the magneto application can be retrieved with the following function. Relative path of the Magento site

<?php echo Mage::getBaseURL();   ?>
Or
<?php echo Mage::getURL();?>

Magento Application some useful functions we used in development

Sometimes we need to check the current host name in magento. Here is the function that returns the hostname of server where the application is executing.

The following code is same as normal PHP $_SERVER[‘HTTP_HOST’]

<?php      echo Mage::app()->getFrontController()->getRequest()->getHttpHost();?>

 It returns 127.0.0.1 if we runs on 127.0.0.1 or in other cases it returns the domain name of the site.
 When we want to retrieve the Path of Base Directory in Magento. We can use the following function

 <?php echo Mage::getBaseDir();  //gives  physical path of the sites root directory ?>

(In my case it return e:\www\magento )

Its returns the Physical path of the Application directory where magento application installed.
When we want to retrieve the relative path of the sites default skin folder. IT return the virtual path of the default skin folder. Many time we used in theme development

 <?php echo $this->getSkinURL(); ?>

 It returns the http://127.0.0.1/www/magento/skin/frontend/default/default/
Virtual path of the magneto application can be retrieved with the following function. Relative path of the Magento site

<?php echo Mage::getBaseURL();   ?>
Or
<?php echo Mage::getURL();?>

Best Seller Products in Magento

irst of All before writting about the best seller products in magento. Here is the file you can use to retrieve best seller products in magento. anywhere in your magento site. you jut need to place this file at correct location and use as your requirements. Either on home page or in any catalog page or at any other location as per your need. So here is the file contain code of showing best-seller products in magento.

Bestseller in magento

One of the most popular option, that each customer needs is the best selling/ best seller products. Each second e-commerce site that uses magento, needs a location where they can show products which are mostly purchased by customer and in the term e-commerce, we call that products as Best Seller Products. Now the question arise that how to show best seller products in magento. I also needed to implement this feature and as generally we do, I also searched best–seller module for magento, as I was also unkown from the little trick of showing products collection in magento.

And I found some technical write-ups related to magento. Like the following Model Named Mage Reports model 

(Mage_Reports_Model_Mysql4_Product_Collection)

http://docs.magentocommerce.com/Mage_Reports/Mage_Reports_Model_Mysql4_Product_Collection.html#sec-methods

we have to just call


Mage::getResourceModel('reports/product_collection');  //in our php file

returns the Products Collection for reporting purpose. We can add a few functions and get some useful data that we need for many customer’s e-commerce site.

Like when we want to get Best Seller Products in magento we just need to add one more filter to this collection.

$products = Mage::getResourceModel(‘reports/product_collection’)->addOrderedQty(); // retrieve Ordered qty of Products with Products collection.

Now a few more filter like

addAttributeToSelect(array('name', 'price', 'small_image', 'short_description', 'description'))
// or

addAttributeToSelect('*')

Above filter used to select required attributes/fields, we need with product collection. We can select the required attributes/ fields with this function by passing fields in array or we can also pass * when we need to take all fields

setStoreId($storeId)
addStoreFilter($storeId) // add this to retrieve products collection related to specific store

setOrder('ordered_qty', 'desc');

Mostly Ordered products on top. Hence we with the help of all of above functions related to this model we can get the Best Seller Products in magento through the following PHP Code

$products = Mage::getResourceModel('reports/product_collection')

->addOrderedQty()

//->addAttributeToSelect('*')

->addAttributeToSelect(array('name', 'price', 'small_image', 'short_description', 'description')) //edit to suit tastes

->setStoreId($storeId)

->addStoreFilter($storeId)

->setOrder('ordered_qty', 'desc'); //best sellers on top

So with the help of above collection we can create best seller module for magento. So, finally i think this code helps us to create magento best seller products extension.

Best Seller Products in Magento

irst of All before writting about the best seller products in magento. Here is the file you can use to retrieve best seller products in magento. anywhere in your magento site. you jut need to place this file at correct location and use as your requirements. Either on home page or in any catalog page or at any other location as per your need. So here is the file contain code of showing best-seller products in magento.

Bestseller in magento

One of the most popular option, that each customer needs is the best selling/ best seller products. Each second e-commerce site that uses magento, needs a location where they can show products which are mostly purchased by customer and in the term e-commerce, we call that products as Best Seller Products. Now the question arise that how to show best seller products in magento. I also needed to implement this feature and as generally we do, I also searched best–seller module for magento, as I was also unkown from the little trick of showing products collection in magento.

And I found some technical write-ups related to magento. Like the following Model Named Mage Reports model  (Mage_Reports_Model_Mysql4_Product_Collection)

http://docs.magentocommerce.com/Mage_Reports/Mage_Reports_Model_Mysql4_Product_Collection.html#sec-methods

we have to just call


Mage::getResourceModel('reports/product_collection');  //in our php file

returns the Products Collection for reporting purpose. We can add a few functions and get some useful data that we need for many customer’s e-commerce site.

Like when we want to get Best Seller Products in magento we just need to add one more filter to this collection.

$products = Mage::getResourceModel(‘reports/product_collection’)->addOrderedQty(); // retrieve Ordered qty of Products with Products collection.

Now a few more filter like

addAttributeToSelect(array('name', 'price', 'small_image', 'short_description', 'description'))
// or

addAttributeToSelect('*')

Above filter used to select required attributes/fields, we need with product collection. We can select the required attributes/ fields with this function by passing fields in array or we can also pass * when we need to take all fields

setStoreId($storeId)
addStoreFilter($storeId) // add this to retrieve products collection related to specific store

setOrder('ordered_qty', 'desc');

Mostly Ordered products on top. Hence we with the help of all of above functions related to this model we can get the Best Seller Products in magento through the following PHP Code

$products = Mage::getResourceModel('reports/product_collection')

->addOrderedQty()

//->addAttributeToSelect('*')

->addAttributeToSelect(array('name', 'price', 'small_image', 'short_description', 'description')) //edit to suit tastes

->setStoreId($storeId)

->addStoreFilter($storeId)

->setOrder('ordered_qty', 'desc'); //best sellers on top

So with the help of above collection we can create best seller module for magento. So, finally i think this code helps us to create magento best seller products extension.

Test Credit Card Account Numbers

While testing, use only the credit card numbers listed here. Other numbers produce an error.
Expiration Date must be a valid date in the future (use the mmyy format).

Test Credit Card Account Numbers

Credit Card TypeCredit Card Number
American Express378282246310005
American Express371449635398431
American Express Corporate378734493671000
Australian BankCard5610591081018250
Diners Club30569309025904
Diners Club38520000023237
Discover6011111111111117
Discover6011000990139424
JCB3530111333300000
JCB3566002020360505
MasterCard5555555555554444
MasterCard5105105105105100
Visa4111111111111111
Visa4012888888881881
Visa4222222222222 Note : Even though this number has a different character count than the other test numbers, it is the correct and functional number.
Processor-specific Cards
Dankort (PBS)76009244561
Dankort (PBS)5019717010103742
Switch/Solo (Paymentech)6331101999990016

Test Credit Card Account Numbers

While testing, use only the credit card numbers listed here. Other numbers produce an error.
Expiration Date must be a valid date in the future (use the mmyy format).

Test Credit Card Account Numbers

Credit Card TypeCredit Card Number
American Express378282246310005
American Express371449635398431
American Express Corporate378734493671000
Australian BankCard5610591081018250
Diners Club30569309025904
Diners Club38520000023237
Discover6011111111111117
Discover6011000990139424
JCB3530111333300000
JCB3566002020360505
MasterCard5555555555554444
MasterCard5105105105105100
Visa4111111111111111
Visa4012888888881881
Visa4222222222222 Note : Even though this number has a different character count than the other test numbers, it is the correct and functional number.
Processor-specific Cards
Dankort (PBS)76009244561
Dankort (PBS)5019717010103742
Switch/Solo (Paymentech)6331101999990016

Adding thumbnail image for custom column in magento admin grid

Sometimes we  need to show thumbnail image for custom attribute in magento admin grid. As we might know it is little tricky to add thumbnail image in a grid in magento admin. Here we’ve discussed the way how we can add thumbnail image.

1.  Firstly we have to add the following code snippet in _prepareColumns() function, in Grid.php(path: code/local/Packagename/Modulename/Block/Adminhtml/Modulename/Grid.php). Here we use the local path you can use community.



<?php
$this->addColumn('modulenameimage', array(
'header' => Mage::helper('modulename')->__('Image'),
'align' => 'left',
'index' => 'modulenameimage',
'renderer' => 'modulename/adminhtml_modulename_renderer_image',
'width' => '107'
));
?>

Note: Here modulenameimage is the custom attribute.

2. Here we can see that a renderer block(adminhtml_modulename_renderer_image), so now our task is to create that block in Packagename_Modulename_Block_Adminhtml_Modulename_Renderer_Image file as below:



<?php
class Packagename_Modulename_Block_Adminhtml_Modulename_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {

public function render(Varien_Object $row) {
$html = '<img ';
$html .= 'id="' . $this->getColumn()->getId() . '" ';
$html .= 'width="' . $this->getColumn()->getWidth() . '" ';
$html .= 'src="' . Mage::getBaseUrl("media") . 'images/' . $row->getData($this->getColumn()->getIndex()) . '"';
$html .= 'class="grid-image ' . $this->getColumn()->getInlineCss() . '"/>';
return $html;
}
}
?>

These are all you need to do to show thumbnail image in grid view. Now you can the grid for that particular module and see the image there. You can change the custom column, image path, width, height as you desire.

Adding thumbnail image for custom column in magento admin grid

Sometimes we  need to show thumbnail image for custom attribute in magento admin grid. As we might know it is little tricky to add thumbnail image in a grid in magento admin. Here we’ve discussed the way how we can add thumbnail image.

1.  Firstly we have to add the following code snippet in _prepareColumns() function, in Grid.php(path: code/local/Packagename/Modulename/Block/Adminhtml/Modulename/Grid.php). Here we use the local path you can use community.

<?php
$this->addColumn('modulenameimage', array(
'header' => Mage::helper('modulename')->__('Image'),
'align' => 'left',
'index' => 'modulenameimage',
'renderer' => 'modulename/adminhtml_modulename_renderer_image',
'width' => '107'
));
?>

Note: Here modulenameimage is the custom attribute.

2. Here we can see that a renderer block(adminhtml_modulename_renderer_image), so now our task is to create that block in Packagename_Modulename_Block_Adminhtml_Modulename_Renderer_Image file as below:



<?php
class Packagename_Modulename_Block_Adminhtml_Modulename_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {

public function render(Varien_Object $row) {
$html = '<img ';
$html .= 'id="' . $this->getColumn()->getId() . '" ';
$html .= 'width="' . $this->getColumn()->getWidth() . '" ';
$html .= 'src="' . Mage::getBaseUrl("media") . 'images/' . $row->getData($this->getColumn()->getIndex()) . '"';
$html .= 'class="grid-image ' . $this->getColumn()->getInlineCss() . '"/>';
return $html;
}
}
?>

These are all you need to do to show thumbnail image in grid view. Now you can the grid for that particular module and see the image there. You can change the custom column, image path, width, height as you desire.