Skip to content
Tags

Making a sortable, dynamic grid

by admin on October 11th, 2009

GridI came up against an interesting challenge on a current project. This was actually pretty fun to figure out. Here is what I came up with.

I needed to display a grid with columns and rows that had information in each cell. The information in the cells needed to be dynamic, or change based on a UI perspective.

Also, if there were more than 10 rows in a column, the remaining cells needed to wrap to the next column.

This is definitely a job for a helper so I wrote these methods for the helper to render this sortable, dynamic grid. So far it seems to be holding up when rendering grids of various columns and rows.

  1.  
  2.   def my_grid
  3.     @my_data =
  4.     @my_data += ‘<table>’
  5.     @my_data += ‘<tr>’
  6.    
  7.     num = 1
  8.     #this starts a new column for each category
  9.     @columns.each do |col|
  10.       cell = Cell.find(:all, :conditions => [‘category_id = ?’, col]) rescue nil
  11.          
  12.       count = cell.size
  13.       item = 0
  14.       itemtotal = 1
  15.       cell.each do |row|
  16.         #if this is the 0 item start a new column
  17.         if item == 0
  18.                 @my_data += self.start_col
  19.         end
  20.        
  21.         score = row.get_my_score(row.id, @grid, @user).to_s
  22.         @my_data += self.list_item(score, row, itemtotal)
  23.        
  24.         #if this is the 9th item, or is the last of the cells, close the column and reset count
  25.         item += 1
  26.         if item == 10 || itemtotal == count
  27.                 @my_data += self.end_col(num)
  28.                 num = num.to_i + 1
  29.                 item = 0
  30.         end
  31.         itemtotal += 1
  32.       end
  33.      
  34.      
  35.     end
  36.    
  37.     @my_data += ‘</tr>’
  38.     @my_data += ‘</table>’
  39.     #return @my_data
  40.   end
  41.  

  1.  
  2. def start_col
  3.     @start = ‘<td valign="bottom"><div style="position: relative; bottom: 0px; display: block;">’
  4.     @start += ‘<ul style="vertical-align: bottom">’
  5.     return @start
  6. end
  7.  

  1.  
  2. def end_col(num)
  3.     @end = ‘</ul>’
  4.     @end += num.to_s
  5.     @end += ‘</td>’
  6.     return @end
  7. end
  8.  

  1.  
  2. def list_item(score, row, item)
  3.     @list = ‘<li class=key_’+ score +‘>’
  4.     #some stuff here…
  5.     @list += ‘</li>’
  6.     return @list
  7. end
  8.  

From → Ruby on Rails

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS