module Wice::GridViewHelper

Public Instance Methods

define_grid(grid, opts = {}, &block) click to toggle source

Has the same parameters as grid but does not output the grid. After define_grid render_grid can be used to output the grid HTML code. Usually used with detached filters: first define_grid, then grid_filters, and then render_grid

# File lib/wice/helpers/wice_grid_view_helpers.rb, line 83
def define_grid(grid, opts = {}, &block)
  # strip the method from HTML stuff
  unless grid.class == WiceGrid
    raise WiceGridArgumentError.new("The first argument for the grid helper must be an instance of the WiceGrid class")
  end

  options = {
    :allow_showing_all_records     => Defaults::ALLOW_SHOWING_ALL_QUERIES,
    :class                         => nil,
    :extra_request_parameters      => {},
    :header_tr_html                => {},
    :hide_reset_button             => false,
    :hide_submit_button            => false,
    :hide_csv_button               => false,
    :show_filters                  => Defaults::SHOW_FILTER,
    :sorting_dependant_row_cycling => false,
    :html                          => {},
    :upper_pagination_panel        => Defaults::SHOW_UPPER_PAGINATION_PANEL
  }

  opts.assert_valid_keys(options.keys)

  options.merge!(opts)

  options[:show_filters] = :no     if options[:show_filters] == false
  options[:show_filters] = :always if options[:show_filters] == true


  rendering = GridRenderer.new(grid, self)

  block.call(rendering) # calling block containing column() calls

  reuse_last_column_for_filter_buttons =
    Defaults::REUSE_LAST_COLUMN_FOR_FILTER_ICONS && rendering.last_column_for_html.capable_of_hosting_filter_related_icons?

  if grid.output_csv?
    grid_csv(grid, rendering)
  else
    # If blank_slate is defined we don't show any grid at all
    if rendering.blank_slate_handler &&  grid.resultset.size == 0 && ! grid.filtering_on?
      generate_blank_slate(grid, rendering)
    else
      grid_html(grid, options, rendering, reuse_last_column_for_filter_buttons)
    end
  end

  grid.view_helper_finished = true

  grid.csv_tempfile ? grid.csv_tempfile.path : nil
end
dump_filter_parameters_as_hidden_fields(grid) click to toggle source

This method dumps all HTTP parameters related to filtering and ordering of a certain grid as hidden form fields. This might be required if you want to keep the state of a grid while reloading the page using other forms.

The only parameter is a grid object returned by initialize_grid in the controller.

# File lib/wice/helpers/wice_grid_misc_view_helpers.rb, line 9
def dump_filter_parameters_as_hidden_fields(grid)
  unless grid.kind_of? WiceGrid
    raise WiceGridArgumentError.new("dump_filter_parameters_as_hidden_fields: the parameter must be a WiceGrid instance.")
  end

  grid.get_state_as_parameter_value_pairs(true).collect{|param_name, value|
    hidden_field_tag(param_name, value, :id => "hidden-#{param_name.gsub(/[\[\]]/, '-')}")
  }.join("\n").html_safe
end
filter_and_order_state_as_hash(grid) click to toggle source

This method dumps all HTTP parameters related to filtering and ordering of a certain grid in the form of a hash. This might be required if you want to keep the state of a grid while reloading the page using Rails routing helpers.

The only parameter is a grid object returned by initialize_grid in the controller.

# File lib/wice/helpers/wice_grid_misc_view_helpers.rb, line 33
def filter_and_order_state_as_hash(grid)
  {
    grid.name => {
      'f'               => grid.status[:f],
      'order'           => grid.status[:order],
      'order_direction' => grid.status[:order_direction]
    }
  }
end
filter_state_as_hash(grid) click to toggle source

This method dumps all HTTP parameters related to filtering of a certain grid in the form of a hash. This might be required if you want to keep the state of a grid while reloading the page using Rails routing helpers. Attention: this does not return parameters for ordering the grid, use filter_and_order_state_as_hash if you need it.

The only parameter is a grid object returned by initialize_grid in the controller.

# File lib/wice/helpers/wice_grid_misc_view_helpers.rb, line 25
def filter_state_as_hash(grid)
  {grid.name => {'f' => grid.status[:f]}}
end
grid(grid, opts = {}, &block) click to toggle source

View helper for rendering the grid.

The first parameter is a grid object returned by initialize_grid in the controller.

The second parameter is a hash of options:

  • :html - a hash of HTML attributes to be included into the table tag.

  • :class - a shortcut for :html => {:class => 'css_class'}

  • :header_tr_html - a hash of HTML attributes to be included into the first tr tag (or two first tr's if the filter row is present).

  • :show_filters - defines when the filter is shown. Possible values are:

    • :when_filtered - the filter is shown when the current table is the result of filtering

    • :always or true - show the filter always

    • :no or false - never show the filter

  • :upper_pagination_panel - a boolean value which defines whether there is an additional pagination panel on top of the table. By default it is false.

  • :extra_request_parameters - a hash which will be added as additional HTTP request parameters to all links generated by the grid, be it sorting links, filters, or the 'Reset Filter' icon. Please note that WiceGrid respects and retains all request parameters already present in the URL which formed the page, so there is no need to enumerate them in :extra_request_parameters. A typical usage of :extra_request_parameters is a page with javascript tabs - changing the active tab does not reload the page, but if one such tab contains a WiceGrid, it could be required that if the user orders or filters the grid, the result page should have the tab with the grid activated. For this we need to send an additional parameter specifying from which tab the request was generated.

  • :sorting_dependant_row_cycling - When set to true (by default it is false) the row styles odd and even will be changed only when the content of the cell belonging to the sorted column changes. In other words, rows with identical values in the ordered column will have the same style (color).

  • :allow_showing_all_records - allow or prohibit the "All Records" mode.

  • :hide_reset_button - Do not show the default Filter Reset button. Useful when using a custom reset button. By default it is false.

  • :hide_submit_button - Do not show the default Filter Submit button. Useful when using a custom submit button By default it is false.

  • :hide_csv_button - a boolean value which defines whether the default Export To CSV button should be rendered. Useful when using a custom Export To CSV button. By default it is false. Please read README for more insights.

The block contains definitions of grid columns using the column method sent to the object yielded into the block. In other words, the value returned by each of the blocks defines the content of a cell, the first block is called for cells of the first column for each row (each ActiveRecord instance), the second block is called for cells of the second column, and so on. See the example:

<%= grid(@accounts_grid, :html => {:class => 'grid_style', :id => 'accounts_grid'}, :header_tr_html => {:class => 'grid_headers'}) do |g|

  g.column :name => 'Username', :attribute => 'username' do |account|
    account.username
  end

  g.column :name => 'application_account.field.identity_id'._, :attribute => 'firstname', :model =>  Person do |account|
    link_to(account.identity.name, identity_path(account.identity))
  end

  g.column do |account|
    link_to('Edit', edit_account_path(account))
  end

end -%>

Defaults for parameters :show_filters and :upper_pagination_panel can be changed in lib/wice_grid_config.rb using constants Wice::Defaults::SHOW_FILTER and WiceGrid::Defaults::SHOW_UPPER_PAGINATION_PANEL, this is convenient if you want to set a project wide setting without having to repeat it for every grid instance.

Pease read documentation about the column method to achieve the enlightenment.

# File lib/wice/helpers/wice_grid_view_helpers.rb, line 71
def grid(grid, opts = {}, &block)
  raise WiceGridArgumentError.new('Missing block for the grid helper.' +
    ' For detached filters use first define_grid with the same API as grid, ' +
    'then grid_filter to add filters, and then render_grid to actually show the grid' ) if block.nil?
  define_grid(grid, opts, &block)
  render_grid(grid)
end
grid_filter(grid, filter_key) click to toggle source

Renders a detached filter. The parameters are:

  • grid the WiceGrid object

  • filter_key an identifier of the filter specified in the column declaration by parameter :detach_with_id

# File lib/wice/helpers/wice_grid_view_helpers.rb, line 529
def grid_filter(grid, filter_key)
  unless grid.kind_of? WiceGrid
    raise WiceGridArgumentError.new("grid_filter: the parameter must be a WiceGrid instance.")
  end
  if grid.output_buffer.nil?
    raise WiceGridArgumentError.new("grid_filter: You have attempted to run 'grid_filter' before 'grid'. Read about detached filters in the documentation.")
  end
  if grid.output_buffer == true
    raise WiceGridArgumentError.new("grid_filter: You have defined no detached filters, or you try use detached filters with" +
      ":show_filters => :no (set :show_filters to :always in this case). Read about detached filters in the documentation.")
  end

  content_tag :span,
    grid.output_buffer.filter_for(filter_key),
    :class => "wg-detached-filter #{grid.name}_detached_filter",
    'data-grid-name' => grid.name
end
render_grid(grid) click to toggle source

Used after define_grid to actually output the grid HTML code. Usually used with detached filters: first define_grid, then grid_filters, and then render_grid

# File lib/wice/helpers/wice_grid_view_helpers.rb, line 137
def render_grid(grid)
  if grid.output_buffer
    grid.output_buffer
  elsif grid.csv_tempfile
    grid.csv_tempfile.path
  else
    raise WiceGridException.new("Attempt to use 'render_grid' without 'define_grid' before.")
  end
end
saved_queries_panel(grid, opts = {}) { || ... } click to toggle source

View helper to render the list of saved queries and the form to create a new query. Parameters:

  • :extra_parameters - a hash of additional parameters to use when creating a new query object.

  • :confirm - A boolean value which turns on or off the JS confirm dialogs when deleting saved queries.

Read section “Adding Application Specific Logic to Saving/Restoring Queries” in README for more details.

# File lib/wice/helpers/wice_grid_serialized_queries_view_helpers.rb, line 9
def saved_queries_panel(grid, opts = {})
  unless grid.kind_of? WiceGrid
    raise WiceGridArgumentError.new("saved_queries_panel: the parameter must be a WiceGrid instance.")
  end

  options = {:extra_parameters => {}, :confirm => 1}
  opts.assert_valid_keys(options.keys)
  options.merge!(opts)

  grid_name = grid.name
  input_field_name = "#{grid_name}_saved_query_name"
  base_path_to_query_controller = create_serialized_query_url(:grid_name => grid_name, :confirm => options[:confirm])

  parameters = grid.get_state_as_parameter_value_pairs

  options[:extra_parameters].each do |k, v|
    parameters << [ CGI.unescape({:extra => {k => ''}}.to_query.sub(/=$/,'')) , v.to_s ]
  end
  parameters <<  ['authenticity_token', form_authenticity_token]
  notification_messages_id = "#{grid_name}_notification_messages"
  (%Q <div class="wice-grid-query-panel well"><h3>#{NlMessage['saved_query_panel_title']}</h3>! +
    saved_queries_list(grid_name, grid.saved_query, options[:extra_parameters], options[:confirm]) +
    %Q<div id="#{notification_messages_id}" ></div>! +
    if block_given?
      view, ids = yield
      view
    else
      ''
    end +

    '<div class="form-horizontal"><div class="wg-saved-query-input-controls input-append">'+

    text_field_tag(input_field_name,  '',  :onkeydown=>'', :class => 'wice-grid-save-query-field span4') +
    button_tag(
      NlMessage['save_query_button_label'],
      :class => 'wice-grid-save-query-button btn',
      'data-grid-name'   => grid_name,
      'data-base-path-to-query-controller' => base_path_to_query_controller,
      'data-parameters'  => parameters.to_json,
      'data-ids'         => ids.to_json
    ) +
    '</div></div></div>'
    ).html_safe
end