boydenhartog
boydenhartog

Reputation: 752

How to add custom server side filter to datatables

I've got an AJAX based datatable to which I would like to apply additional filtering. So far I've only found client side or outdated examples. I fail to understand how the search is actually performed and how I can add filters to function.

A simple example, I'm trying to add a vendor filter to my SKU datatable. I have populated a selectbox with the vendor names. If a vendor is selected I would only like to show that vendors SKUs. Additionally the user should be able to use the search to look through this vendors results. How can I filter my results?

Here is my coffeescript (UPDATE):

$ ->
  $('#vendor-skus-table').DataTable
  processing: true
  serverSide: true
  retrieve: true
  pagingType: 'full_numbers'
  ajax: data: (d) ->
    d.sku = $('#vendor-skus-table').data('source')
    d.extra_search = $('#vendor-select').val();
    return

Some additional javascript for my filter field:

$('#vendor-select.vendor-select').on('change', function() {
  $('#vendor-skus-table').DataTable().ajax.reload();
});

My datatable file:

class VendorSkuDatatable < AjaxDatatablesRails::Base
def_delegators :@view, :params, :link_to, :vendor_skus_path, :vendor_path

def sortable_columns
  @sortable_columns ||= ['VendorSku.name', 'Vendor.name', 'VendorSku.inventory_quantity' ]
end

def searchable_columns
  @searchable_columns ||= ['VendorSku.name', 'Vendor.name']
end

private

def data
  records.map do |record|
    [
      link_to(record.name, record),
      link_to(record.vendor.name, record.vendor),
      record.inventory_quantity
    ]
  end
end

def get_raw_records
  VendorSku.joins(:vendor).where(vendor_id: params[:extra_search])
end
end

Upvotes: 1

Views: 3402

Answers (1)

Andrei Zhytkevich
Andrei Zhytkevich

Reputation: 8099

Sorry, my code will be JavaScript, I don't know CoffeScript.

In order to add parameters to your ajax request you have to specify an option ajax.data when creating your datatable:

  $('#vendor-skus-table').DataTable({
    // ... your paramteres
    ajax: {
      data: function(d) {
        d.sku = $('#vendor-skus-table').data('source'); // or maybe $('#vendor-skus-table').data('source').join(',')
      }
    }

You'll get sku parameter of ajax request on the back-end.

Upvotes: 2

Related Questions