Monday, June 18, 2012

Drupal 7 Webform with an item catalog table element

I was working on a Drupal 7 project and there was a requirement of a form with some simple text fields to put values and some elements in a grid like format to display catalog of items including item name, price, a text box for quantity and automatically calculated sub totals and grand total.



I started with webform module but the built in grid element did not work. Then I tried webform_table_element module, it had some bugs but I managed to configure it. But, unfortunately, it was not able to produce a similar form. I was on a tight deadline (as usual) and did not have time to do something custom, so I decided to try some workaround and after spending a little time I got acceptable result.

I am writing some simple steps to re-generate similar result. I know this is not an ideal solution but it can save a little time if you have to add a couple of similar forms in your Drupal based project.


You need to install webform and webform_table_element module modules first.

a) Add a field of type table_element in webform. table_element type requires you to put key|value pairs in 'Rows' textarea there, convert your 'value' to a simple JSON so it can be accessed later, something like:

1|{"ID":"001", "title":"My Item 1", "rate":"245"}
2|{"ID":"002", "title":"My Item 2", "rate":"460"}
3|{"ID":"003", "title":"My Item 3", "rate":"740"}

And here is a screenshot:

b) Add these child elements under newly created table_element type item:


  1.  Item Name
    1. Type: markup
    2. Label: Item Name
    3. Field Key: item_name
    4. Value: Name
  2. Item Rate
    1. Type: markup
    2. Label: Item Rate
    3. Field Key: item_rate
    4. Value: Rate
  3. Quantity
    1. Type: textfield
    2. Label: Quantity
    3. Field Key: quantity
  4. Item Rate
    1. Type: markup
    2. Label: Sub Total
    3. Field Key: sub_total
    4. Value: <div class="sub-total"></div>
      (you will need to disable rich text editor or write in source view with Text Format=Full HTML)

c) We are done with form building here, now time to add some code in template.php file:

// This will display form element in a multi column table

function adibf_table_element($variables) {
  $element = $variables['element'];
  $header = array();
  $header_complete = false;
  $rows = array();
  
  foreach (element_children($element) as $child) {
    $child_element = $element[$child];
   
 $rowCustomData = $child_element['#row_title'];
 $rowCustomData = json_decode($rowCustomData);
   
    $row = array($rowCustomData->ID);
 
    foreach (element_children($child_element) as $grandchild) {
      
      if (!$header_complete && isset($element['#row_titles'])) {
       if($child_element[$grandchild]['#type'] == 'markup') {
   $theKey = trim(strip_tags($child_element[$grandchild]['#markup']));
   $theTitle = '';
   
   switch($theKey) {
    case 'Name':
     $theTitle = t('Item');
     break;
    
    case 'Rate':
     $theTitle = t('Rate (usd)');
     break;
    
    case 'Quantity':
     $theTitle = t('Quantity');
     break;
   }
   
   if($element['#column_titles'][$grandchild] == 'sub-total')
    $theTitle = t('Sub Total');
   
   $header[]  = array('data' => $theTitle, 'class' => $element['#column_titles'][$grandchild]);
  } else {
         $header[]  = array('data' => t($element['#row_titles'][$grandchild]), 'class' => $element['#column_titles'][$grandchild]);
  }
      }
  
  if($child_element[$grandchild]['#type'] == 'markup') {
   if(trim(strip_tags($child_element[$grandchild]['#markup'])) == 'Name')
    $child_element[$grandchild]['#markup'] = $rowCustomData->title;
  
   if(trim(strip_tags($child_element[$grandchild]['#markup'])) == 'Rate')
   $child_element[$grandchild]['#markup'] = $rowCustomData->rate;
  
   if(trim(strip_tags($child_element[$grandchild]['#markup'])) == 'Color')
   $child_element[$grandchild]['#markup'] = $rowCustomData->color;
  
   if(trim(strip_tags($child_element[$grandchild]['#markup'])) == 'Dimension')
   $child_element[$grandchild]['#markup'] = $rowCustomData->dimension;
  }
  
     $row[] = array('data' => drupal_render($child_element[$grandchild]));
    }

    $header_complete = true;
    $rows[] = $row;
  }

  array_unshift($header, array('class' => 'row-title', 'data' => t('Code')));
  return theme('table', array('header' => $header, 'rows' => $rows));
}

// This will show posted results in multi column table

function adibf_webform_submission_render_alter(&$renderable) {
 if (isset($renderable['#submission'])) {
  foreach (element_children($renderable) as $key) {
   $tableRows = array();
   
   if ($renderable[$key]['#webform_component']['type'] == 'table_element') {
    $cid = $renderable[$key]['#webform_component']['cid'];
    
    foreach($renderable['#submission']->data[$cid]['value']['rows'] as $row) {
     $data = strip_tags($row[0]);
     $quantity = $row['quantity'];
     
     $objData = json_decode($data);
     $subTotal = $objData->rate * $quantity;
     $tableRows[] = array($objData->ID, $objData->title, $objData->rate, $quantity, $subTotal);
    }
    
    $tableHeader = array('ID', 'Title', 'Rate', 'Quantity', 'Sub Total');
    
    $theTable = array(
     'header' => $tableHeader,
     'rows' => $tableRows,
    );
    
    $renderable[$key]['#markup'] = theme('table', $theTable);
   }
  }
 }
}

First code block will display form element visually in a multi column table with one text field for quantity in each row, the second block is for the posted results.

d) The last step is to add a little jQuery somewhere in the theme so after entering quantity, sub total column value would be changed. You can also add a feature to show Net Total somewhere on the page:

jQuery('.webform-component-table_element .form-text').change(function() {
  var elems = jQuery('.webform-component-table_element .form-text');
  
  var totalAmount = 0;
  for(var i=0; i<elems.length; i++) {
   totalAmount += table_element_calculate(elems[i]);
  }
  
  jQuery('#net_total').html(totalAmount);
 });


function table_element_calculate(elem) {
 var sPrice = jQuery(elem).parents('td').prev().text();
 var hTotal = jQuery(elem).parents('td').next();
 
 var p = 0;
 
 try {
  p = sPrice * jQuery(elem).val();
  
  if(isNaN(p))
   p = 0;
  
  if(p > 0)
   hTotal.find('.sub-total').html(p);
  // alert(p);
 } catch(e) {}
 
 return p;
}

Note: I just copied pasted these codes from a project that I did some months ago, so if something don't work please post in comments. Thanks.

43 comments:

  1. Anonymous9:31 PM

    Wοw, that's what I was seeking for, what a information! existing here at this blog, thanks admin of this website.

    Feel free to visit my homepage :: trying lose

    ReplyDelete
  2. Anonymous12:54 AM

    Thanκs a lot foг ѕhaгіng this
    with аll folks уоu rеally know whаt you're talking approximately! Bookmarked. Please also talk over with my site =). We may have a link change contract between us

    my web blog ... raspberry ketone uk

    ReplyDelete
  3. Anonymous10:35 PM

    Howdy! I could have sworn I've been to this site before but after reading through some of the post I realized it's new
    to me. Nonetheless, I'm definitely delighted I found it and I'll
    be bookmarking and checking back frequently!

    Stop by my site: Click On this page

    ReplyDelete
  4. Anonymous11:06 PM

    Hello! Someone in my Facebook group shared this website with us so I
    came to take a look. I'm definitely enjoying the information. I'm bookmarking and will be tweeting this to my followers!

    Fantastic blog and fantastic style and design.


    Check out my blog: auto insurance colorado

    ReplyDelete
  5. Anonymous11:57 PM

    Howdy this is kind of of off topic but I was wondering if blogs use
    WYSIWYG editors or if you have to manually code with HTML.
    I'm starting a blog soon but have no coding expertise so I wanted to get advice from someone with experience. Any help would be enormously appreciated!

    Also visit my blog post - similar resource site

    ReplyDelete
  6. Anonymous11:59 PM

    I've gone ahead and included a backlink back to your site from one of my clientele requesting it. We have used your web site URL: http://www.blogger.com/comment.g?blogID=33304191&postID=2939022638997093974 and blog title: Blogger: Helper Class to be certain you get the proper anchor text. If you woud like to see where your hyperlink has been placed, please e-mail me at: quentinbenner@aol.com. Thankyou

    my homepage: just click the following website

    ReplyDelete
  7. Anonymous11:21 PM

    Greetings from Idaho! I'm bored to death at work so I decided to check out your site on my iphone during lunch break. I enjoy the knowledge you provide here and can't wait to take a look when
    I get home. I'm amazed at how quick your blog loaded on my cell phone .. I'm not even using WIFI,
    just 3G .. Anyways, amazing site!

    Here is my website ... click to read more

    ReplyDelete
  8. Anonymous2:03 AM

    Hi there, i read your blog from time to time and i own a similar
    one and i was just curious if you get a lot of spam remarks?

    If so how do you protect against it, any plugin or anything you can advise?
    I get so much lately it's driving me crazy so any support is very much appreciated.

    My site - link building india

    ReplyDelete
  9. Anonymous4:29 PM

    Have you ever considered publishing an e-book or guest authoring on other websites?

    I have a blog based on the same ideas you discuss and would really
    like to have you share some stories/information.
    I know my visitors would value your work. If you're even remotely interested, feel free to send me an e mail.

    Here is my blog post; Click On this page

    ReplyDelete
  10. Anonymous3:27 PM

    Hello there just happened upon your blog via Google after I typed in, "Blogger: Helper Class" or something similar (can't quite remember exactly). In any case, I'm glad
    I found it because your content is exactly what I'm looking for (writing a college paper) and I hope you don't mind
    if I collect some material from here and I will of course
    credit you as the reference. Thank you very much.

    Here is my web-site Read Full Report

    ReplyDelete
  11. Anonymous4:10 PM

    Hey just wanted to give you a brief heads up and let you know a few of the
    images aren't loading properly. I'm not sure why but I think its
    a linking issue. I've tried it in two different web browsers and both show the same results.

    My web site :: Continue

    ReplyDelete
  12. Anonymous12:31 AM

    It's remarkable for me to have a website, which is valuable in favor of my know-how. thanks admin

    Here is my blog post; Read This method

    ReplyDelete
  13. Anonymous11:27 AM

    I do not even know how I ended up here, but I thought this
    post was good. I do not know who you are but certainly you are going to a famous blogger if you are not already ;) Cheers!


    Also visit my website Get More Info

    ReplyDelete
  14. Anonymous6:07 AM

    The other day, while I was at work, my sister stole my iPad and tested
    to see if it can survive a thirty foot drop, just so she can be a
    youtube sensation. My apple ipad is now destroyed and she has 83 views.

    I know this is entirely off topic but I had to share it with someone!



    My webpage: click the next internet site

    ReplyDelete
  15. Anonymous7:32 AM

    Hi! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing months of hard
    work due to no backup. Do you have any methods to prevent hackers?


    Look at my homepage :: link building for seo

    ReplyDelete
  16. Anonymous9:04 AM

    Hi! I'm at work browsing your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!

    Feel free to visit my web blog this blog

    ReplyDelete
  17. Anonymous4:05 PM

    Currently it looks like Wordpress is the best blogging
    platform out there right now. (from what I've read) Is that what you're using on your
    blog?

    My site: auto insurance san diego

    ReplyDelete
  18. Anonymous9:41 PM

    Hello! This is the second time visiting now and I really just wanted to say
    I truley get pleasure from looking through your blog site.
    I have decided to bookmark it at delicious.com
    with your title: Blogger: Helper Class and your URL: http://www.
    blogger.com/comment.g?blogID=33304191&postID=2939022638997093974.
    I hope this is ok with you, I'm making an attempt to give your wonderful blog a bit more exposure. Be back soon.

    My web-site: visit the following site

    ReplyDelete
  19. Anonymous12:52 PM

    Hey. I noticed your site title, "Blogger: Helper Class"
    doesn't really reflect the content of your web-site. When writing your website title, do you think it's most beneficial to write it for Web
    optimization or for your visitors? This is something
    I've been battling with mainly because I want great search rankings but at the same time I want the best quality for my website visitors.

    Feel free to surf to my web blog: This Web-site

    ReplyDelete
  20. Anonymous4:30 PM

    Admiring the time and energy you put into your site
    and detailed information you offer. It's awesome to come across a blog every once in a while that isn't the same unwanted rehashed information.

    Wonderful read! I've saved your site and I'm including your RSS feeds
    to my Google account.

    My web page Read the Full Posting

    ReplyDelete
  21. Anonymous2:43 AM

    When I initially commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added
    I get several emails with the same comment. Is there any way you can remove me from that service?
    Thanks a lot!

    Here is my web page; visit the following webpage

    ReplyDelete
  22. Anonymous5:09 AM

    Hi! Would you mind if I share your blog with my facebook
    group? There's a lot of folks that I think would really appreciate your content. Please let me know. Cheers

    Feel free to visit my web blog :: one way link building service []

    ReplyDelete
  23. Anonymous5:55 AM

    I am curious which blogging platform you're running? I'm new to blogging and have been thinking about using the Vox platform.
    Do you think this is a good foundation to start with?

    I would be extremely grateful if I could ask you some questions through
    email so I can learn a bit more prior to getting started.

    When you have some free time, please be sure to get in touch with me at: mitchelllorenzo@gmx.
    net. Cheers

    Here is my page Read the Full Write-up []

    ReplyDelete
  24. Anonymous10:14 PM

    Hi I am so glad I found your blog, I really found you by error, while I was
    researching on Bing for something else, Anyhow I am here
    now and would just like to say cheers for a remarkable post and a all
    round enjoyable blog (I also love the theme/design),
    I don’t have time to go through it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to
    read a lot more, Please do keep up the fantastic b.


    My blog post ... more helpful hints []

    ReplyDelete
  25. Anonymous11:33 PM

    Hello! It seems as though we both have a passion for the same thing.

    Your blog, "Blogger: Helper Class" and mine are very similar.
    Have you ever considered authoring a guest write-up for a related blog?
    It will surely help gain publicity to your blog (my website recieves a lot of targeted traffic).
    If you might be interested, contact me at: jeffnunn@gmail.
    com. Thanks for your time

    Feel free to visit my web blog - backlink building service

    ReplyDelete
  26. Anonymous1:53 AM

    I absolutely love your blog and find nearly all of your post's to be just what I'm looking for.
    Do you offer guest writers to write content for you?
    I wouldn't mind writing a post or elaborating on a few of the subjects you write related to here. Again, awesome web site!

    Also visit my page; visit this weblink

    ReplyDelete
  27. Anonymous3:50 AM

    Hello! Would you mind if I share your blog with my facebook group?

    There's a lot of people that I think would really appreciate your content. Please let me know. Many thanks

    Feel free to visit my webpage similar web-site - -

    ReplyDelete
  28. Anonymous11:02 AM

    Howdy are using Wordpress for your site platform? I'm new to the blog world but I'm trying to
    get started and create my own. Do you require any coding
    knowledge to make your own blog? Any help would be greatly appreciated!


    Feel free to surf to my web page; responsive auto insurance []

    ReplyDelete
  29. Anonymous2:51 PM

    Hi there! Do you use Twitter? I'd like to follow you if that would be ok. I'm absolutely enjoying your blog and look forward to new posts.


    Stop by my webpage ... illinois auto insurance *aeev.at*

    ReplyDelete
  30. Anonymous4:20 PM

    Hmm is anyone else experiencing problems with the pictures on this blog
    loading? I'm trying to determine if its a problem on my end or if it's the blog.
    Any responses would be greatly appreciated.

    Visit my web site ... original site

    ReplyDelete
  31. Anonymous3:28 AM

    Hmm it appears like your site ate my first comment (it was extremely long) so I guess I'll just sum it up what I wrote and say, I'm thoroughly
    enjoying your blog. I too am an aspiring blog writer but I'm still new to everything. Do you have any tips for rookie blog writers? I'd definitely appreciate it.


    my web page: who has the cheapest auto insurance ()

    ReplyDelete
  32. Anonymous4:43 AM

    Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the shell to
    her ear and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is entirely off topic but I had
    to tell someone!

    my weblog; Get More Info

    ReplyDelete
  33. Anonymous12:46 PM

    Hi there! I'm about to start my own blog and was wondering if you know where the best place to acquire a website url is? I am not even sure if that's what its called?

    (I'm new to this) I'm referring to "http://www.blogger.com/comment.g?blogID=33304191&postID=2939022638997093974".
    Exactly how do I go about acquiring one of these for the website I'm building? Thanks a lot

    Have a look at my web-site - check out the post right here ()

    ReplyDelete
  34. Anonymous1:21 PM

    Doh! I was domain name searching at namecheap.
    com and went to type in the domain name: http://www.
    blogger.com/comment.g?blogID=33304191&postID=2939022638997093974 and guess who already acquired it?
    You did! lol j/k. I was about to purchase this domain name but
    realized it was taken so I thought I'd come check it out. Wonderful blog!

    My site; read more here

    ReplyDelete
  35. Anonymous2:00 PM

    I’m not that much of a online reader to be honest but your sites really nice, keep it up!
    I'll go ahead and bookmark your site to come back later on. Many thanks

    Feel free to surf to my web page ... check out the post right here

    ReplyDelete
  36. Anonymous11:54 PM

    Hello just came upon your website from Bing after I typed in, "Blogger: Helper Class" or something similar (can't quite remember exactly). Anyways, I'm happy I found it simply
    because your subject material is exactly what I'm searching for (writing a college paper) and I hope you don't mind if I collect some material from here and I will of course credit
    you as the reference. Appreciate it., see additional reading []!

    ReplyDelete
  37. Anonymous6:13 PM

    Incredible! This blog looks exactly like my old one! It's on a entirely different topic but it has pretty much the same page layout and design. Outstanding choice of colors!

    Feel free to surf to my website effective link building service

    ReplyDelete
  38. Anonymous3:00 AM

    Hello there! I know this is somewhat off topic but I was wondering
    which blog platform are you using for this website?
    I'm getting sick and tired of Wordpress because I've
    had issues with hackers and I'm looking at options for another platform. I would be great if you could point me in the direction of a good platform.

    My website Read Full Report

    ReplyDelete
  39. Anonymous12:12 PM

    Hey there! This post could not be written any better! Reading this post reminds me of my previous room mate!
    He always kept talking about this. I will forward this article
    to him. Pretty sure he will have a good read.
    Thank you for sharing!

    Here is my site ... Website link building

    ReplyDelete
  40. Anonymous11:59 AM

    Hey! My name is Isabel and I just desired to say your site rocks!
    It truly is hilarious due to the fact I use to have a site
    that virtually had an identical web address: http://www.blogger.
    com/comment.g?blogID=33304191&postID=2939022638997093974 mine was
    only a few letters different. Nonetheless, I am a big fan of your web site and if you ever want a guest write-up please email me personally
    at: isabelhowell@arcor.de. I take pleasure in writing!


    My site - omni auto insurance ()

    ReplyDelete
  41. Anonymous7:45 AM

    Greetings! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your articles.
    Can you suggest any other blogs/websites/forums that deal with the same subjects?
    Thanks!

    My webpage: backlinking service

    ReplyDelete
  42. Anonymous6:48 AM

    Hello! Quick question that's entirely off topic. Do you know how to make your site mobile friendly? My website looks weird when browsing from my iphone4. I'm trying to find a theme or
    plugin that might be able to correct this problem. If you
    have any recommendations, please share. Many thanks!

    my web site - blog backlink

    ReplyDelete