Friday, December 30

How to Add a Logout Link in Magento

Magento seems to include the “Login” link by default. However, Magento does not seem to show a link to Logout after one logs in.

If you have been searching tirelessly for a solution to your Magento logout woes, have no worries your search is at an end! We’ve already searched and found. We’ve included the code you will need to add a Logout link to Magento. This code actually only displays the pertinent link – so if a user is already logged in they will only see a Logout link and if a user is not Logged in then they will see a Login link.

Here is the code:

<?php if (!Mage::getSingleton('customer/session')->isLoggedIn()): ?>
<a href="<?php echo Mage::helper('customer')->getLoginUrl(); ?>"><?php echo $this->__('Login') ?></a>
<?php else: ?>
<a href="<?php echo Mage::helper('customer')->getLogoutUrl(); ?>"><?php echo $this->__('Logout') ?></a>
<?php endif; ?>


Hope it Helps... Thanks

Thursday, December 29

How to Clear the cache with PHP script in Magento

It always take time to get rid of the Magento cache. However cache is needed to execute the request faster. One way of clearing the cache is delete all the directories inside the /var/cache directory. Doing that manually it will take some time if you are connected to the FTP server.
The easiest way of clearing the cache in Magento is here.

<?php

ini_set('max_execution_time', 3600);
ini_set("memory_limit","256M");

$script = "rm -rf var/cache/*";
$results = system($script,$retval);
echo " Cache cleared, RETURN VALUE: $retval\n";

?>


Name the file clearcache.php. Put it in the root directory of the Magento setup & execute in the browser.

hope it helps.. Thanks....

Magento – How to Add custom comment box to each product in Cart

Are you looking for the solution i.e. customer can provide their inputs or comments along with the products they are going to order. To make it easier, one way is to allow them enter the comments for each individual item they order.

On the other hand, admin should be able to view the comment on the order page.

Adding a custom comment box for each item in the cart is actually very easy. First lets add the textarea field for each item.

In your theme, for the file: template/checkout/cart.phtml
Add the new heading along with other heading for cart items.

__('Comments') ?> 
In the file: template/checkout/cart/item/default.phtml
Add a new column



For Older version of Magento it would be:


Doing upto this. shoul show the text area added

The next step is to save the comment in DB, when customer update the cart.

So add a new field ‘itemcomment’ in the tabel ‘sales_flat_quote_item’. (For older version of Magento the table would be ‘sales_quote_item’)

Now we are going to add the code which will do the DB operation. For this we will need to modify the file:
app/code/core/Mage/Checkout/Model/Cart.php (Note: If you are planning to upgrade your Magento setup, copy this file to local & modify.)

Here we need to add some code to the function updateItems(), such a way that the function should now look like below:

 public function updateItems($data)
 {
     Mage::dispatchEvent('checkout_cart_update_items_before', array('cart'=>$this, 'info'=>$data));

     foreach ($data as $itemId => $itemInfo) {

         $item = $this->getQuote()->getItemById($itemId);
         if (!$item) {
             continue;
         }

         if (!empty($itemInfo['remove']) || (isset($itemInfo['qty']) && $itemInfo['qty']=='0')) {
             $this->removeItem($itemId);
             continue;
         }

         $qty = isset($itemInfo['qty']) ? (float) $itemInfo['qty'] : false;
         if ($qty > 0) {
             $item->setQty($qty);
         }

     /* Start: Custom code added for comments */
     if(!empty($itemInfo['comments'])) {

     	$write = Mage::getSingleton('core/resource')->getConnection('core_write');

     	# make the frame_queue active
   		$query = "UPDATE `sales_flat_quote_item` SET itemcomment = '".$itemInfo['comments']."' where item_id = $itemId";
$write->query($query);

     	$item->setItemcomment($itemInfo['comments']);
     }
     /* End: Custom code added for comments */

     }

     Mage::dispatchEvent('checkout_cart_update_items_after', array('cart'=>$this, 'info'=>$data));
     return $this;
 }
Showing the comment in Admin -> View Order

Add a new function getItemcomment() to the file below:
app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php

If you are on verstion 1.5 or later.. add it to the file below.
app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php

	public function getItemcomment($item) {
		$itemId = $item->getId();

		$write = Mage::getSingleton('core/resource')->getConnection('core_write');

    	$query = "SELECT q.* FROM `sales_flat_order_item` o
	    LEFT JOIN `sales_flat_quote_item` q on o.quote_item_id = q.item_id
	    WHERE o.item_id = $itemId";

		# For older versions of Magento
/*	    $query = "SELECT q.* FROM `sales_order_entity_int` o
	    LEFT JOIN `sales_flat_quote_item` q on o.value = q.entity_id
	    WHERE o.entity_id = $itemId AND o.attribute_id = 343";       */	    

		$res = $write->query($query);

		while ($row = $res->fetch() ) {
			if(key_exists('itemcomment',$row)) {
				echo nl2br($row['itemcomment']);
			}
		}
	}    

To add the comments column to the items edit the .phtml file below:
app/design/adminhtml/default/default/template/sales/order/view/items.phtml

Adding header for items to make it look like below:
.
.

    helper('sales')->__('Product') ?>
    helper('sales')->__('Comments') ?>
    helper('sales')->__('Item Status') ?>
.
.
.

Adding Column with comments. app/design/adminhtml/default/default/template/sales/order/view/items/renderer/default.phtml
Add a column for item comments juts before status columns to make it look a like below.
.
.
getItemcomment($_item) ?> 
getStatus() ?>
.
.
Doing upto this will show the comments column in the item table. It should look like image below.

Hope it Helps... Thanks...

Tuesday, December 27

How to Reindex Data Programmatically in Magento

This article shows how to reindex Magento Data Programmatically (through code).

You can manually reindex data from System -> Index Management. However, this article is concerned how this can be done through code/programming.

Currently, there are 9 indexes. They are as under (with their respective key number):-

1. Product Attributes
2. Product Prices
3. Catalog URL Rewrites
4. Product Flat Data
5. Category Flat Data
6. Category Products
7. Catalog Search index
8. Tag Aggregation Data
9. Stock Status

So, if you want to reindex “Category Products” only then you can do as follows:-

$process = Mage::getModel('index/process')->load(6);
$process->reindexAll();

If you want to reindex all data then you can loop through these indices and then reindex them:-

for ($i = 1; $i <= 9; $i++) {
    $process = Mage::getModel('index/process')->load($i);
    $process->reindexAll();
}

Ref : http://blog.chapagain.com.np/magento-reindex-data-programmatically

How to get product rating and review in Magento

Here is the code to get ratings and reviews for any particular product.

/**
 * Getting reviews collection object
 */
$productId = $product->getId();
$reviews = Mage::getModel('review/review')
                ->getResourceCollection()
                ->addStoreFilter(Mage::app()->getStore()->getId())
                ->addEntityFilter('product', $productId)
                ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
                ->setDateOrder()
                ->addRateVotes();
/**
 * Getting average of ratings/reviews
 */
$avg = 0;
$ratings = array();
if (count($reviews) > 0) {
    foreach ($reviews->getItems() as $review) {
        foreach( $review->getRatingVotes() as $vote ) {
            $ratings[] = $vote->getPercent();
        }
    }
    $avg = array_sum($ratings)/count($ratings);
}

Displaying the ratings
<!-- REMOVE 'IF CONDITION', TO SHOW RATING IN ALL RATED/UNRATED PRODUCTS -->
<?php if($avg): ?>
    <div class="rating-box" style="float:left;">
        <div class="rating" style="width: <?php echo ceil($avg) ; ?>%;"></div>
    </div>
<?php endif; ?>

Ref : http://blog.chapagain.com.np/magento-how-to-get-product-rating-and-review

How to get actual price and special price of a product in Magento

Here is a quick and useful code on getting actual price and special price of any product in Magento. The actual price is the real price assigned to the product and special price is the price after any discount is applied to the product.

Loading Product

$_productId = 52;
$_product = Mage::getModel('catalog/product')->load($_productId);

Get Actual Price
// without currency sign
$_actualPrice = $_product->getPrice();
 
// with currency sign
$_formattedActualPrice = Mage::helper('core')->currency($_product->getPrice(),true,false);

Get Special Price
// without currency sign
$_specialPrice = $_product->getFinalPrice();
 
// with currency sign
$_formattedSpecialPrice = Mage::helper('core')->currency($_product->getFinalPrice(),true,false);


Ref : http://blog.chapagain.com.np/magento-how-to-get-actual-price-and-special-price-of-a-product

How to Show/Hide Demo Store Notice in Magento

A demo store is where there are products but the order done by customer is not processed. If your website is in development mode then it is better to enable demo store notice.

Enabling demo store notice in Magento is very simple. You just need to select an option in configuration settings in admin panel.

Go to System -> Configuration -> Design -> HTML Head -> Display Demo Store Notice

By default, it is set as ‘No’. To enable demo store notice, select ‘Yes’.

Now, you will see a notice bar at top of your page saying ‘This is a demo store. Any orders placed through this store will not be honored or fulfilled.‘

Ref : http://blog.chapagain.com.np

Sunday, December 18

How to Create 'Place an Order API' in Magento

Magento provides a number of web services to ease the life of programmers and users. You will find web services for adding, deleting, listing, editing of products, customers, shipments etc. But Magento lacks a very important web service- Placing Orders. Magento says that it is due to security reasons so that a hacker does not break into your site and place unwanted orders. But no worries, I have found a way out, a simple one. I have developed the web service for placing an order in Magento.

Open the file: app\code\core\Mage\Sales\etc\api.xml
Here search for methods tag inside sales_order parent tag an add the folloeing lines to it
<place translate="title" module="sales">
  <title>Place order</title>
  <acl>sales/order/change</acl>
 </place>

so that the sales_order enclosure looks like:
<config>
    <api>
        <resources>
            <sales_order translate="title" module="sales">
                <model>sales/order_api</model>
                <title>Order API</title>
                <acl>sales/order</acl>
                <methods>
                    <list translate="title" module="sales">
                        <title>Retrieve list of orders by filters</title>
                        <method>items</method>
                        <acl>sales/order/info</acl>
                    </list>
                    <info translate="title" module="sales">
                        <title>Retrieve order information</title>
                        <acl>sales/order/info</acl>
                    </info>
                    <addComment translate="title" module="sales">
                        <title>Add comment to order</title>
                        <acl>sales/order/change</acl>
                    </addComment>
                    <hold translate="title" module="sales">
                        <title>Hold order</title>
                        <acl>sales/order/change</acl>
                    </hold>
                    <unhold translate="title" module="sales">
                        <title>Unhold order</title>
                        <acl>sales/order/change</acl>
                    </unhold>
                    <cancel translate="title" module="sales">
                        <title>Cancel order</title>
                        <acl>sales/order/change</acl>
                    </cancel>
                    <place translate="title" module="sales">
                        <title>Place order</title>
                        <acl>sales/order/change</acl>
                    </place>
                </methods>
   

Now go to the file: app\code\core\Mage\Sales\Model\Order\Api.php
Here at last add the following function:
public function place()
 {
  $customer = Mage::getModel('customer/customer')->load($customerId);/*$customerId is the id of the customer who is placing the order, it can be passed as an argument to the function place()*/
 
  $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 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('flatrate');
 
  $orderPayment = Mage::getModel('sales/order_payment')
  ->setStoreId($storeId)
  ->setCustomerPaymentId(0)
  ->setMethod('purchaseorder')
  ->setPo_number(' - ');
  $order->setPayment($orderPayment);
 
  // let say, we have 2 products
  $subTotal = 0;
  $products = array('1' => array('qty' => 1),'2'=>array('qty' => 3));
  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();
 }
Now our web service is ready to use. Lets call the service to place an order:
<?php
 define('WSDL_URL', 'http://example.com:/api/soap/?wsdl');
 define('WSDL_USER', 'user');
 define('WSDL_KEY', 'password');
 
try {
  $proxy = new SoapClient(WSDL_URL);    //call magento API 
  $sessionId = $proxy->login(WSDL_USER, WSDL_KEY);//check Valid API Authentications 
   $proxy->call($sessionId, 'sales_order.place');
  echo "Order Placed Successfully!";
 }
catch (Exception $e) 
 {
  echo 'Error in order invoice web service: '.$e->getMessage();
  exit;
 }
?>


And it is all to place an order through web service!

Hope it Helps... Thanks....