Can I show data is sorted when not sorted by dataTables - datatables

I am using the https://datatables.net/ jQuery plugin to display client side tabular data.
The data for my table is pre-sorted so I don't want the overhead of dataTables doing the first sort. I have set aaSorting to [] so that dataTables does not sort the data.
My problem is that I would like the header style to show which column the data is sorted by and when that column is sorted for it to toggle the sort order.
I tried a cheat of the following which displays the way I want but I have to click twice to change the search to descending.
dataTableOptions.fnInitComplete = function (oSettings, json) {
$table.find('th:first').addClass('sorting_asc');
};
Any suggestions would be greatly appreciated.
Thanks.

You can set the default sort direction of your target column to 'desc' by using asSort as documented here. This would sort your table in descending order on the first click. You would still to set the class of th:first to sorting_asc on init.
// Using aoColumns
$(document).ready( function() {
$('#example').dataTable( {
"aaSorting": [],
"aoColumns": [
{ "asSorting": [ "desc", "asc" ] }, // assumes you are targeting column 1
...// other columns
],
...// other configuration
} );
} );

Related

Vuetify / Vue (2) data table not sorting / paginating upon new bound prop

Keeping the table as basic as possible to figure this out. I am struggling to learn how to create server side sorting/pagination to function in vuetify. When I add the :options or :server-items-length bind the table no longer sorts or paginates.
Without either of those, I get a default listing of 10 items per row - and the sorting all works perfectly fine as well the pagination. However, parameters in the api require a page item count thus forcing a hardcoded number or using the :options bind. If i just place a hard coded number things work fine, but when I bind I get proper items per page but no sorting and pagination.
Very simple data table:
<v-data-table
:items="ItemResults.items"
:headers="TableData.TableHeaders"
:loading="TableData.isLoading"
>
</v-data-table>
//Base data returns, with headers and options as well the array that items are stored in.
data() {
return {
ItemResults:[],
TableData: {
isLoading: true,
TableHeaders: [
{ value: "title", text: "Title" },
{ value: 'artist', text: 'Artist' },
{ value: 'upc', text: 'UPC' },
{ value: "retailPrice", text: "Price/Quantity"},
],
},
options:
{
page: 1,
itemsPerPage: 15
},
}
},
//Then last, my async method to grab the data from the api, and place it in the itemresults array.
async getProducts(){
this.TableData.isLoading = true;
const { page, itemsPerPage } = this.options;
var temp = await this.$axios.get(`Inventory/InventoryListing_inStock/1/${page}/${itemsPerPage}`);
this.ItemResults = temp.data;
this.TableData.isLoading = false;
return this.ItemResults;
},
I have tried following Vuetify Pagination and sort serverside guide, but I'm not sure where they are recommending to make the axios call.
The lead backend dev is working on setting a sorting function up in the api for me to call paramaters to as well - Im not sure how that will function along side.
but I dont know how to have this controlled by vuetify eithier, or the best practice here.
EDIT:
I've synced the following:
:options.sync="options"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
but i think I dont need to sync the last two. My options:
options:
{
page: 1,
itemsPerPage: 15,
sortBy: ['title'],
sortDesc: [false]
},
and in my data I put the array for sort by and sort desc
sortBy: [
'title', 'artist', 'upc', 'retailPrice'
],
sortDesc:[true, false],
pagination is now working, and sort ascending is now working, but when I click to descend the header I get an error that the last two params are empty on update to / / instead of /sortBy/sortDesc result. So its not listing the values on changes.
When your component mounts, you need to fetch the total number of items available on the server and the first page of data, and set these as :items and :server-items-length. The latter will (as you observed) disable paging and sorting, as your server will take care of it, and it is used to calculate the total number of pages given a selected page size.
Now you need to know when to reload data. For this, you either bind options to the v-data-table with two-way binding (.sync) and set a watcher on it, or you listen to the update:options event. And whenever options change, you fetch the selected data from the server.
That's basically all it takes.
In your template:
<v-data-table
:items="items"
:headers="headers"
:loading="true"
:server-items-length="numberOfItemsOnServer"
#update:options="options => loadPage(options)"
/>
In your component:
methods: {
async loadPage(options){
this.items = [] // if you want to show DataTable's loading-text
this.items = await fetch('yourUrl' + new URLSearchParams({
// build url params from the options object
offset: (options.page - 1) * options.itemsPerPage,
limit: options.itemsPerPage,
orderBy: options.sortBy.map((sb,ix) => [sb, options.sortDesc[ix] ? 'desc' : 'asc'])
}))
}
}

Jquery Inline editor plugin saving numbers on dropdown select

Good day,
I have a datatable with the jQuery plugin that makes it editable and transform to text all the table rows.
Need to create a dropdown menu to select and store on database what is selected.
Everything is fine, since the plugin have an option to create a row with select options, the problem here is that the field that i have on the database is based on VARCHAR and the plugin only stores data with ENUM on the selected dropdown field.
So i cannot change the database field to ENUM because its going to delete or alter the already exixting data and could be a problem.
Example of what i see when i click on EDIT and see the dropdown options:
When i hit on SAVE button it shows this on the database:
This happens because the column type on the database is VARCHAR and the plugin needs it to be ENUM to read the data as text.
This is the code to draw the table and the edit plugin data:
$(document).ready(function(){
var dataTable = $('#tabla_clientes').DataTable({
"language": {
"url": "https://cdn.datatables.net/plug-ins/1.10.20/i18n/Spanish.json"
},
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fectch.php",
type:"POST"
}
});
$('#tabla_clientes').on('draw.dt', function(){
$('#tabla_clientes').Tabledit({
url:'action.php',
deleteButton: false,
autoFocus: false,
buttons: {
edit: {
class: 'btn btn-sm btn-primary',
html: '<span class="glyphicon glyphicon-pencil"></span> &nbsp Editar',
action: 'edit'
}
},
dataType:'json',
columns:{
identifier : [0, 'id_customer'],
editable:[[1, 'customerID'], [2, 'RFC'], [3, 'firstname'], [4,'lastname'],[5,'email'],[6, 'tipo_cliente','{"1":"CONTADO","2":"CREDITO"}']]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
}
});
});
I already did some research on the internet but i cannot find anyone with a solution or with this problem.
Like i said, i cannot simply change the field to ENUM because there is a LOT of information that may be changed or deleted because of the type change.
Does anyone know a solution to store the value as text with the VARCHAR type when selecting the dropdown info?
Thanks for the time and patience. Have a excelent day.
I already found a workaround very simple for this.
Instead of adding directly the value as number on database.
Added an IF to compare the number and store text on a variable.
$tipo_cliente = $_POST['tipo_cliente'];
$sitio = $_POST['sitio']
if ($tipo_cliente == 1) {
$tipo_cliente = 'CONTADO';
} else
{
$tipo_cliente = 'CREDITO';
}

How can I override the total sum of the EXTJS summary?

I am using EXTJS 4.2.1 and my application has a grid including paging, the grouping summary and the summary feature. I want to override the sum of the summary feature, because it should display the grand total sum of the whole data set and not only for the current displayed page.
Is that possible to override the summary feature to do so?
Thanky you very much for every advice in advance. :-)
Use summaryRenderer in column configuration. It is an undocummented feature of ExtJS allowing you to show custom data in your summary row.
You will have to summarize the data server-side and send them to client where you will access it in the summaryRenderer.
Like so:
columns: {
items: [
{
text: "Column A",
dataIndex: "field_A",
summaryRenderer: function( value, summaryData, dataIndex ) {
var grid = this;
// Get the value here and return it
var result = functionToGetValue( grid );
return result;
}
},
// ...
}
]
The functionToGetValue is the place where you pass the summarization value you sent to your client from server.
How you do that depens on your code. You have access to store via grid.getStore().
It is possible to add the summary data to each record and then simply use store.getAt(0).get( 'summaryValue' ), it is kind of wasteful, but it is simple and it works.

Integrate Bootstrap typeahead js with Bootstrap Datatable

I am using bootstrap data-tables Datatables and bootstrap-taginput with typehead.js. I am new with bootstrap data-tables.
Here is the layout of my bootstrap data-tables Example and please consider Bootstrap tagging input box on top.
I want to search data-tables records with bootstrap tagging elements. but somehow i am unable to search with bootstrap tagging.
Thanks in advance.
If you start out with an empty array of the data you've got on your table you could do something clever by replacing the built in search box. In the example I'm linking to I don't care about one of the columns and the other columns need a little formatting:
var words = [];
var table = $('#example').DataTable({
"columns": [
null, {
"render": function(data, type, row) {
~words.indexOf(data) || words.push(data);
return data;
}
}, {
"render": function(data, type, row) {
var d = data.replace(/\, /g, " ");
~words.indexOf(d) || words.push(d);
return data.split(", ").join("<br/>");
}
}
],
"initComplete": function() {
var searchBox = $("#example_wrapper").find("input[type='search']");
var searchBoxHolder = searchBox.parent();
searchBox.empty().remove();
searchBoxHolder.append($("<input/>", {
"type": "text"
}).typeahead({
source: words,
afterSelect: function(word) {
table.search(word).draw();
}
}).on("keyup", function(x) {
if (words.indexOf($(x.target).val()) === -1) {
table.search($(x.target).val()).draw();
}
}));
}
});
Basically what we're doing here is creating a blank array of search terms then iterating over each second and third cell and adding the term to the array if it doesn't exist. In the case of the third cell I need to clear some formatting (extra comma). Then we get the original search box and it's parent. Remove the original and append the new one to the parent. We then set it up as a typeahead with the list of search terms. We need to make sure it still acts like the original so we add the keyup function. I hope that makes sense.
Working example is here, hope that helps.

How to format with commas all the valid numbers in all the columns using datatables?

I want to format thousands and millions numbers in all the columns from a table rendered using datatables, however I don't want to change the data on the original table since that data is going to be used for a dynamic chart.
How can I modify just the render of the table and apply that to all the columns?
If someone stumbles with this same need, it is possible to use the columnDefs options initially passed to the dataTable constructor to modify the render side of the datatable without affecting the .data() values.
$('#example').DataTable({
columnDefs: [{
targets: "_all",
render: function ( data, type, full, meta ) {
if(type === 'display' && !isNaN(data*1)){
return (data*1).toLocaleString();
}else{
return data;
}
}
}]
});
Here is a jsfiddle that illustrates the approach.
http://jsfiddle.net/spookmx/7hhfpnxp/