jbox-web / ajax-datatables-rails

A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app
MIT License
590 stars 227 forks source link

Can't search for Date (or change its format) #260

Closed PhilippMeissner closed 6 years ago

PhilippMeissner commented 7 years ago

Hi,

I want to enable datatable search for the DateTime column of my model. Within the view the date is displayed as 1. November 2017. If possible I'd like the search input to allow either searching for this very string (or parts of it), or at least define the format (like dd-mm-yyyy or yyyy.mm.dd, something along the lines).

This is my HTML setup:

%table.table.table-striped.table-bordered.table-hover.table-responsive#product-selections-table{:data => {:source => "#{@path}.json"}, :width => "100%"}
    %thead
      %tr
        %th= t('product_selections.name')
        %th= t('product_selections.user_login_name')
        %th= t('product_selections.tag_names')
        %th= t('product_selections.products_count')
        %th= t('product_selections.items_count')
        %th= t('product_selections.updated_at')
        %th
        %th
        %th
        %th
    %tbody

My coffeescript options hash:

{
  columns: [
    {
      data: 'updated_at',
      sortable: true,
    },...
  ]
}

My DatatableClass:

  def view_columns
    @view_columns ||= {
      ...,
      updated_at: { source: 'ProductSelection.updated_at', searchable: true, cond: :validate_date },
    }
  end

  private
  def data
    records.map do |record|
      {
        ....,
        updated_at: localize(record.updated_at),
      }
    end
  end

  def localize(obj)
    return obj.nil? ? '' : I18n.l(obj, :format => :datatable)
  end

  def get_raw_records
    ProductSelection.includes(:tags, :user, :folder).references(:tag, :user, :folder).distinct
  end

  def validate_date
    ->(column) { is_valid_date?(column.search.value) ? column.table[column.field].matches("#{column.search.value}") : false }
  end

  def is_valid_date? date
    begin
      Date.parse date
    rescue ArgumentError
      false
    end
  end
end

Unfortunately within my Proc the column isn't the actual column, but my input value. This causes the following error: undefined methodsearch' for "The string that I entered":String`

So my questions: 1) Can I search for a DateTime value? 2) Can I define the format for which to search? 3) How to use the Proc properly?

Regards Phil

n-rodriguez commented 6 years ago

Can you please try with the master branch of the repo?

The lamba will receive 2 params : the column object itself and the formated_value :

  def validate_date
    ->(column, formated_value) { is_valid_date?(column.search.value) ? column.table[column.field].matches("#{column.search.value}") : false }
  end

A new release with this fix is coming.