Aug
17
2010

Magento – 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.

<th><?php echo $this->__('Comments') ?></th> 

In the file: template/checkout/cart/item/default.phtml
Add a new column

            <td class="a-center">
            <textarea name="cart[<?php echo $_item->getId() ?>][comments]" rows="3" cols="20"><?php echo $_item->getItemcomment() ?></textarea>
            </td>

For Older version of Magento it would be:

            <td class="a-center">
            <textarea name="cart[<?php echo $_item->getId() ?>][comments]" rows="3" cols="20"><?php echo $this->getItemItemcomment($_item) ?></textarea>
            </td>

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:

.
.
<tr class="headings">
    <th><?php echo $this->helper('sales')->__('Product') ?></th>
    <th><?php echo $this->helper('sales')->__('Comments') ?></th>
    <th><?php echo $this->helper('sales')->__('Item Status') ?></th>
.
.
.

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.

.
.
<td><?php echo $this->getItemcomment($_item) ?></td> <!-- New column added for item comments -->
<td class="a-center"><?php echo $_item->getStatus() ?></td>
.
.

Doing upto this will show the comments column in the item table. It should look like image below.

Related Posts

About the Author: Jignesh Patel

Jignesh Patel is a geek, an engineer & a web developer, who focus on developing web sites which look great, work great and can still work on older web browsers. Expertise in PHP, MySQL, JS, Magento & Wordpress.

  • Anonymous

    Note: The name of the DB tables may be differ between Magento Versions.

  • Anonymous

    Note: The name of the DB tables may be differ between Magento Versions.

  • Jdunham

    I’m having troubles with the comments saving to the quote. I think it’s the part where I’m suppose to add ‘itemcomment’. The cart states that it Cannot update shopping cart once I put Test text in the comment area. Where do I put the ‘itemcomment’

  • Jdunham

    Hello? Still waiting on a reply for help below. Comment is not being saved to DB. Need HELP.

  • Anonymous

    Hi..

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

  • Jdunham

    Where do I find that table? I tried to add it in Setup.php file which now looks like this:

    class Mage_Sales_Model_Mysql4_Setup extends Mage_Eav_Model_Entity_Setup
    {
    protected $_flatEntityTables = array(
    ‘quote’ => ‘sales_flat_quote’,
    ‘quote_item’ => ‘sales_flat_quote_item’,
    ‘quote_itemcomment’ => ‘sales_flat_quote_itemcomment’,
    ‘quote_address’ => ‘sales_flat_quote_address’,
    ‘quote_address_item’=> ‘sales_flat_quote_address_item’,
    ‘quote_address_rate’=> ‘sales_flat_quote_shipping_rate’,
    ‘quote_payment’ => ‘sales_flat_quote_payment’,
    ‘order_item’ => ‘sales_flat_order_item’,

    And I have also tried adding it in the config.xml which now looks like this:


    Mage_Sales_Model_Mysql4


    sales_flat_quote



    sales_flat_quote_item



    sales_flat_quote_itemcomment



    sales_flat_quote_address



    sales_flat_quote_address_item



    sales_flat_quote_item_option



    sales_flat_quote_payment



    sales_flat_quote_shipping_rate

    But I still get the error stating that “Cannot update shopping cart”.

    Am I doing something wrong?

    Thank you for your help.

  • Jdunham

    Here’s what I put in the Setup.php: class Mage_Sales_Model_Mysql4_Setup extends Mage_Eav_Model_Entity_Setup
    {
    protected $_flatEntityTables = array(
    ‘quote’ => ‘sales_flat_quote’,
    ‘quote_item’ => ‘sales_flat_quote_item’,
    ‘quote_itemcomment’ => ‘sales_flat_quote_itemcomment’,
    ‘quote_address’ => ‘sales_flat_quote_address’,
    ‘quote_address_item’=> ‘sales_flat_quote_address_item’,
    ‘quote_address_rate’=> ‘sales_flat_quote_shipping_rate’,
    ‘quote_payment’ => ‘sales_flat_quote_payment’,
    ‘order_item’ => ‘sales_flat_order_item’,

  • Anonymous

    Hi

    Are you sure that the field is added to the respective table. Have you tried to look directly in the DB via phpMyAdmin or something. If the field is not added, add it via phpMyAdmin only.

  • Jdunham

    I’m sorry, I’m not sure what folder to find that file in.

    Thanks,
    JDunham

  • Akg1989 Garg

    Dear Jignesh Patel,

    thnks for ur code u give above , i go through each and every step as u mention and got success to sho comment box for each item on product view page as well as order view page
    but i m feeling sad to say these words that it’s not working properly . when i enter some text in comment box and press “update shopping cart ” button it show an error ” Cannot update shopping cart.” .

    Please help me it’s urgent
    thnks in advance

  • Anonymous

    Hi,

    Sorry for late reply. Are you still facing problems ? If yes, then are you sure you have implemented the updateItems() functions correctly. Just make sure that the name of the table could be different between the Magento versions.

  • Jam

    If you have custom table prefixes you have to take it into account.
    I used Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_item’) to get the table name (replace sales_order_entity_int as well)

  • Rob

    I like your solution, but I get the same issue ” Cannot update shopping cart.” . The problem for me is the table name in the Update statement. So I need the table name explained in a little more detail. My full table name is: mage_sales_flat_quote_item. my magento directory is “ecm” My assumption was that the file name would be ecm_ mage_sales_flat_quote_item, but that doesn’t work. Oh, I did add the field to the table via PHPadmin. Are ther any special table settings for the field.

    Any ideas,

    Rob

  • EricB

    Lolz you made me laugh. He is talking about creating that table in the database itself. I used this SQL command to create the field:
    ALTER TABLE `nmmsales_flat_quote_item` ADD `itemcomment` LONGTEXT AUTO_INCREMENT

    My tables have the nmm prefix, without it you would use:
    ALTER TABLE `sales_flat_quote_item` ADD `itemcomment` TEXT AUTO_INCREMENT

  • EricB

    I did everything but the last step. You say Find the relevant code below & edit as per need:

    < ?php echo $this->renderInfoColumn($_item) ?> < ?php echo $this->getItemcomment($_item) ?>

    Where is this code?? I do not see it in items.phtml…

  • EricB

    I have the same problem. It errors out when you try and update the cart saying “Cannot update shopping cart.”. I did not do the last step as I could not follow it as you see in my comment above. PLEASE HELP!

  • Anonymous

    Hello Eric

    Sorry for let reply. I have now updated the whole post for the latest version of Magento. I have tested on Magento ver. 1.4.1.1 & its working

    Please go through the whole post from beginning.

    Thanks

  • Anonymous

    The whole post is now updated for Magento ver. 1.4.1.1 . So please go through it once again,

  • Anonymous

    The whole post is now updated for Magento ver. 1.4.1.1 . So please go through it once again.

  • Mage_New

    Hello,

    I’ve been trying for hours to get this working. Followed your instructions for Magento 1.4.1

    The itemcomment has been added to mysql with Type=Text, Null=Yes, default=NULL
    But I continue to get the ‘Cannot update shopping cart error’

    PS: my sql tables have a default mgn_ prefix.

    I followed Jam’s comment and also added this line Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_item’)

    in both Cart and Items.php but nothing works.

    Please help?

  • Anonymous

    Hello

    I am not sure, why you are getting still an error. if you want, we can chat on skype. I will try to help. My skype: jaggsr

  • Mage_New

    Hope to catch you on skype soon. I’ve upgraded to 1.4.2.0 and it seems like this code needs a bit of updating?

  • http://www.facebook.com/EricRBacker Eric Bäcker

    You are a godsend to all of the Magento amateurs out there myself included! Thank you for your work. I have reimplemented your comment system and I am still getting the cannot update shopping cart error just as Mage_New is as well. I do have a prefix on my db tables however I took this into account and used the correct name each time your code mentions the tables at hand.

  • http://www.securityguardcenter.com/ Nick

    Have you found a solution? If so, can you please let me know? My skype: nickcrptrr1

  • Meera

    Yes, me too need bit of help.. this is not working in 1.4.2. Can anybody help to solve the issue?

    Thanks a lot…

    Meera

  • Meera

    Hi Nick..
    if ur issue is related with viewing the comment in adminpanel
    You can do the following here –

    ==> app/design/adminhtml/default/temlate/sales/order/view/renderer/default.phtml
    mine is working now..

    getQuoteItemId();
    $quote_item = Mage::getModel(‘sales/quote_item’)->load($quote_item_id)->getItemcomment();
    echo $quote_item;
    ?>

  • Peter

    Your customization doesn’t work properly in v1.5. At least, not without modification…

    The function getItemcomment() should be added to:
    app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
    NOT

    app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Items.php

  • Anonymous

    Peter.. Thanks for letting us know.

  • mconstanzo

    Hey guys I’m in a similar situation but I need 2 input text from the user,
    those values will be width and length for the product. So I also need to
    calculate the final price according to the square per meter price. Anybody knows how to pass this values to magento so the checkout price can be modified?

    Thanks

  • Anonymous

    Check my another post. http://magentocoder.jigneshpatel.co.in/add-to-cart-with-custom-attributes-values/

    However It may not work with your latest Magento version. I yet to update the post.

  • mconstanzo

    I’ll give it a try, thanks mate

  • Jeremiah Lewis

    Great code! How would you implement the comment return in the review portion of the one page checkout (last step)? I can get the extra column to show up, but the comment doesn’t seem to carry through to that step.

  • Abdullah Radwan

    another helpful article on the same topic, check this link out
    http://www.webcenter.co.in/repository/how-to-add-custom-fields-for-order-line-items-in-magento

  • denisa

    Hi! I have a question regarding your code. I would like to add a new field for each product in cart, something like an Insurance option – a checkbox. For each product the customer can choose if he wants insurance or not through a checkbox. Also, when the checkbox will be checked I want that the price be updated as working with the quantity option. Please, give me an idea.
    Thanks,

  • Pratik

    Pls Help This Code Did Not Work in My Magento ..
    Add Database Filde Add All The Step Completed But Not Work Pls Help…
    Provide Code Bro It s Hurry…  

  • Khamar_pratik

    Work Perfect But I want To Show Comment In Invoice And Creditmemo Create And View In Back end So Pls Tell Me How Can i DO…
    Tnanx For Great Post…

  • http://www.facebook.com/thuong.classical Đoạn Đường Vắng Em

    Thank you so much! It’s very useful :X

  • Lu

    I followed your step by step, but in Magento 1.7, after you click the “Place Order” button, the order information will be loaded from sales_flat_quoto_item to table sales_flat_order_item How to insert the itemcomments to this table? In my admin panel, it could not display the comments. Thanks!

  • Lu

    Hi,

    Thanks a lot for your post, it is very helpful. I followed every step and everything works fine except the last one —  the comment won’t display in the Admin view. My is Magento 1.7.

    Could you please advise? Thank you!

  • Anonymous

    Hi,
    Thanks a lot for sharing your code here, it is really helpful to me. I followed every steps and works fine except the last one, the itemcomment won’t display in the admin panel. I did see the data was input to the quote_item table through the phpAdmin, any idea what was the problem?

    My Magento is 1.7

    Thank you in advance.

  • Anonymous

    Hi cant make it work for 1.7.0.2
    Cant retieve comment from database in admin with getItemcomment($_item) ?>
    Any insight please?

  • http://www.magento-galaxy.com/ Magento customization

    Thank you for posting this we were going crazy finding something suitable !

blog comments powered by Disqus