Hi guys, I need to create a condition or simply limitation when in my table has 10 records,
the idea is only allow 10 records no more.
do you have any idea?
thank you.
Hi guys, I need to create a condition or simply limitation when in my table has 10 records,
the idea is only allow 10 records no more.
do you have any idea?
thank you.
I'm having trouble with the sorting of a date column.
It seems that it only sorts the day but not the year.
I've made a jsfiddle with the issue if you sort the startdate there are records of 2019 between records of 2020
https://jsfiddle.net/obswu4tk/
Hi
I have added a checkbox with the prepend method to an editir form. what is the correct syntax for grabing the click event. Tried these but they won't work:
$('input:checkbox').on('click', function () {
alert('aaa');
});
$("#chkDoNotInsertDistributorPOSCommission").click(function () {
alert('aaa');
})
I tried looking on the forum but couldn't find anything. Thanks.
I have seen people asking a few times how to use datatables serverside with MVC and EF with paging sorting and searching etc. I had some code lying around so I thought its time to give back and share a simple implementation.
Unfortunately I don't have time right now to create a sample solution for download so I just hacked out the code and pasted it in here as a guide.
For the dynamic searching (where clause) you will need linqkit for the predicate building.
First map the datatable inbound JSON requests to classes
Start - JSon class sent from Datatables
public class DataTableAjaxPostModel
{
// properties are not capital due to json mapping
public int draw { get; set; }
public int start { get; set; }
public int length { get; set; }
public List<Column> columns { get; set; }
public Search search { get; set; }
public List<Order> order { get; set; }
}
public class Column
{
public string data { get; set; }
public string name { get; set; }
public bool searchable { get; set; }
public bool orderable { get; set; }
public Search search { get; set; }
}
public class Search
{
public string value { get; set; }
public string regex { get; set; }
}
public class Order
{
public int column { get; set; }
public string dir { get; set; }
}
/// End- JSon class sent from Datatables
Next implement your action in a standard controller (note in this example we are not using a Web-API controller)
This method just grabs the data sent from the table and calls YourCustomSearchFunc()
before returning a formatted json obj for Datatables to consume.
public JsonResult CustomServerSideSearchAction(DataTableAjaxPostModel model)
{
// action inside a standard controller
int filteredResultsCount;
int totalResultsCount;
var res = YourCustomSearchFunc(model, out filteredResultsCount, out totalResultsCount);
var result = new List<YourCustomSearchClass>(res.Count);
foreach (var s in res)
{
// simple remapping adding extra info to found dataset
result.Add(new YourCustomSearchClass
{
EmployerId = User.ClaimsUserId(),
Id = s.Id,
Pin = s.Pin,
Firstname = s.Firstname,
Lastname = s.Lastname,
RegistrationStatusId = DoSomethingToGetIt(s.Id),
Address3 = s.Address3,
Address4 = s.Address4
});
};
return Json(new
{
// this is what datatables wants sending back
draw = model.draw,
recordsTotal = totalResultsCount,
recordsFiltered = filteredResultsCount,
data = result
});
}
YourCustomSearchFunc()
is very simple it just sets up the sort column and sort direction before calling the database search functionality. In this example we are only allowing sorting on a single column but you could easily implement multi column sorting.
public IList<YourCustomSearchClass> YourCustomSearchFunc(DataTableAjaxPostModel model, out int filteredResultsCount, out int totalResultsCount)
{
var searchBy = (model.search != null) ? model.search.value : null;
var take = model.length;
var skip = model.start;
string sortBy = "";
bool sortDir = true;
if (model.order != null)
{
// in this example we just default sort on the 1st column
sortBy = model.columns[model.order[0].column].data;
sortDir = model.order[0].dir.ToLower() == "asc";
}
// search the dbase taking into consideration table sorting and paging
var result = GetDataFromDbase(searchBy, take, skip, sortBy, sortDir, out filteredResultsCount, out totalResultsCount);
if (result == null)
{
// empty collection...
return new List<YourCustomSearchClass>();
}
return result;
}
This is the main meat of the functionality. In it we simply select from the dbase but instead of using a fixed where
clause we use a dynamic expression built using the wonderful LinqKit to generate the predicate.
Additionally we use Take and Skip to allow us to page through the data. Notice we use the where clause twice. Once to select the data and pick a page, the second time to count how many items we could have returned.
public List<YourCustomSearchClass> GetDataFromDbase(string searchBy, int take, int skip, string sortBy, bool sortDir, out int filteredResultsCount, out int totalResultsCount)
{
// the example datatable used is not supporting multi column ordering
// so we only need get the column order from the first column passed to us.
var whereClause = BuildDynamicWhereClause(Db, searchBy);
if (String.IsNullOrEmpty(searchBy))
{
// if we have an empty search then just order the results by Id ascending
sortBy = "Id";
sortDir = true;
}
var result = Db.DatabaseTableEntity
.AsExpandable()
.Where(whereClause)
.Select(m => new YourCustomSearchClass
{
Id = m.Id,
Firstname = m.Firstname,
Lastname = m.Lastname,
Address1 = m.Address1,
Address2 = m.Address2,
Address3 = m.Address3,
Address4 = m.Address4,
Phone = m.Phone,
Postcode = m.Postcode,
})
.OrderBy(sortBy, sortDir) // have to give a default order when skipping .. so use the PK
.Skip(skip)
.Take(take)
.ToList();
// now just get the count of items (without the skip and take) - eg how many could be returned with filtering
filteredResultsCount = Db.DatabaseTableEntity.AsExpandable().Where(whereClause).Count();
totalResultsCount = Db.DatabaseTableEntity.Count();
return result;
}
Here is the predicate builder function that just plugs in a where clause dynamically. You will need to install (nugget) in linqkit for this.
In this example I am searching where the searchterm appears in either the firstname or lastname
private Expression<Func<DatabaseTableMappedClass, bool>> BuildDynamicWhereClause(DBEntities entities, string searchValue)
{
// simple method to dynamically plugin a where clause
var predicate = PredicateBuilder.New<DatabaseTableMappedClass>(true); // true -where(true) return all
if (String.IsNullOrWhiteSpace(searchValue) == false)
{
// as we only have 2 cols allow the user type in name 'firstname lastname' then use the list to search the first and last name of dbase
var searchTerms = searchValue.Split(' ').ToList().ConvertAll(x => x.ToLower());
predicate = predicate.Or(s => searchTerms.Any(srch => s.Firstname.ToLower().Contains(srch)));
predicate = predicate.Or(s => searchTerms.Any(srch => s.Lastname.ToLower().Contains(srch)));
}
return predicate;
}
The only left to show is the datatable itself
var table = $('#SearchResultTable').DataTable({
"proccessing": true,
"serverSide": true,
"ajax": {
url: "@Url.Action("CustomServerSideSearchAction", "Home")",
type: 'POST'
},
"language": {
"search": "",
"searchPlaceholder": "Search..."
},
"columns": [
{ "data": "Firstname" },
{ "data": "Lastname" }
]
});
Hope this helps
Could someone help me with right use of "onerror" while I return images?
Here is my example:
http://live.datatables.net/cayafasi/1/edit
it still shows the default "broken/notfound" image instead of the one I defined. Why?
The datatable contains child rows.
The table's data should refresh after 5 seconds, but, as soon as the page refreshes, the rows that are in row.show() state revert back to their hidden state. I want to refresh the table values such that the state of the table is maintained. Django is used for backend which is reading the data from a mysql database.
{% extends "tableviewer/base.html" %}
{% block content1 %}
<!-- head section -->
<style>
@import url('//cdn.datatables.net/1.10.2/css/jquery.dataTables.css');
td.details-control {
background: url('http://www.datatables.net/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('http://www.datatables.net/examples/resources/details_close.png') no-repeat center center;
}
</style>
{%endblock%}
{% block content %}
<!-- body section -->
<!-- <button type="button" class="refresh">Reset Table</button> -->
<table id = "table1">
<thead class = "thead">
<tr>
<th></th>
<th>
AUTHOR ID</th>
<th>AUTHOR NAME</th>
<th>Article</th>
<th>Random Values</th>
</tr>
</thead>
<tbody>
{% for aob in obj %}
<tr data-child-value="abcd">
<td class="details-control"></td>
<td>{{aob.authId}}</td>
<td>{{aob.authName}}</td>
<td>{{aob.article}}</td>
<td><font color = {{color}}>{{random_nos}}</font></td>
<!-- <td><font color = {{color}}><div id = "autochange">{{random_nos}}</div></font></td> -->
<!-- <td id = "autochange"><font color = {{color}}>{{random_nos}}</font></td> -->
</tr>
{%endfor%}
</tbody>
</table>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script type="text/javascript">
function format(value) {
reVal = '<div>Hidden Value: ' + value + '</div>';
return reVal;
}
$(document).ready(function () {
var table = $('#table1').DataTable({});
// Add event listener for opening and closing details
$('#table1').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
//alert("inside isShown == True");
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
//alert("inside isShown == False");
// Open this row
row.child(format(tr.data("data-child-value"))).show();
tr.addClass('shown');
}
});
});
</script>
{% endblock %}
How to use datatable editor from generator to codeignator 3, would you give me tutorial or article ?
Hello,
I am facing an issue when I try to import several consecutive CSV file in my tables.
I look into your example : https://editor.datatables.net/examples/extensions/import
The issue also exists : if you import a CSV file into the table, and then try to import another CSV file the import form will open but you cannot load a file from your computer.
Do you have any clue to correct this issue ?
Thanks
Here
when I order for the given column, it doesn't execute the order correctly.
I feel a bit stupid, but i can't get it working.
I have 2 int fields, (purchase, marge) and i want to display this computed value:
purchase*((100+marge)/100)
Trying:
{ data: null,
render: function ( data, type, row ) {
return ( row.tbl_article.purchase + row.tbl_article.marge )}},
{ data: null,
render: function ( data, type, row ) {
return ( row.tbl_article.purchase * row.tbl_article.marge )}},
{ data: null,
render: function ( data, type, row ) {
return ( row.tbl_article.purchaseb*b((b100 + row.tbl_article.marge) / 100) )}}
When purchase would be 40 and marge would be 10:
outcome:
first example = 4010
second example = 400 = what to expect
third example = 4004
it seems the + sign combines the field instead of computing the value, but the multiply works correct.
What am i doing wrong here?
Following this question, due to the difficulty in creating advanced custom filtering, I decided to follow standard filter() api route.
I successfully created a regex to match strings different from one or more strings (with this regex: ^((?!string1|string2).)*$
) but i'm stuck in building the following regex:
Could someone please provide support in doing so? I'm quite new to regex patterns...
When using ScrollY the header becomes locked and will sometimes mis-align. The main issue is when scrolling horizontally the header does not move and if there are headers off screen you never see them.
HTML:
(example table from https://datatables.net/examples/basic_init/zero_configuration.html)
CSS:
td { white-space: nowrap; }
th { white-space: nowrap; }
js:
$("#example").DataTable({
dom: 'Bfrtip',
"scrollY": "35vh",
"scrollCollapse": true,
"paging": false
});
Example showing the issue:
http://jsfiddle.net/Cyberjetx/hgvtqxux/34/
Thsi is kind of a confusing thing to explain so here's an example:
http://live.datatables.net/kixurigu/1/
Basically I have a client that want to tag one row with multiple items. For example they have a row that has "Offices" and for each row they want to be able to add multiple, e.g. "Sydney, Tokyo" but still have separate items in the dropdown search.
Try searching the "Offices" dropdown.
Any help would be appreciated!
I have a datatable where I want to allow deleting all records (usually between 100 and 200 records). I get an error when the user clicks 'Delete'. I see the following discussion, but not sure how to use it in my asp.net MVC project.
https://datatables.net/forums/discussion/58944
Where do I use: response.Unvalidated ?
Hello all. I have a datatable and I have successfully implemented the drop down column filters as shown in this example: https://datatables.net/examples/api/multi_filter_select.html
However, because I am using the server side processing, only the visible options on the first page are populated in the drop down boxes.
I'm using PHP on my server side. How can I pass the options into my JSON and access them in the initComplete function to prefill my select options?
$("#registrations").dataTable( {
"ajax": '{!! route('ajax.registrations') !!}',
processing: true,
serverSide: true,
select: true,
stateSave: true,
columns: [
{data: "product.name"},
{data: "alcohol"},
{data: "reg_type.type"},
{data: "status"},
{data: "reg_date"},
{data: "renew_date"},
],
initComplete: function () {
this.api().columns([0,2,3]).every( function () {
var column = this;
var select = $('<select class="form-control"><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $(this).val();
column.search( this.value ).draw();
} );
// Only contains the *visible* options from the first page
console.log(column.data().unique());
// If I add extra data in my JSON, how do I access it here besides column.data?
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
});
Hi @all
When trying to do that the $POST array send to GetData.php does not contain field set, just action=>edit...
I have a one row table and best visualization was to transpose it.
I've done everything i need to manage it so now i have a table with many rows and 3 columns:
* id (hidden)
* field name
* field value
I can edit them and manage to save everything correctly but now i have a problem: i need some field values to be edited as a date field, some as a select2 type and some others as a text. Since while initing editor i can specify just one type for column, i can't set an editor specific for cell.
Is there a way i can set the editor field type for specific row? With datatable we can pass a function to the render method to change its behaviour dynamically, is it possible to do something similar with editor fields' type or is it possible at runtime via events hook (i looked for such solution but wasn't able to solve it)
Thanks in advance
Greetings
I'm using quill field type for html input.
When Inserting an image, it is formed like this:
<img src="data:image/png;base64,iVBORw0K...."/>
But in the database I find the value is changed into:
<img src="denied:data:image/png;base64,iVBORw0K..."/>
I tried to use simple PHP Sqlite PDO to handle the insertion with prepared Statement. and it inserted the html as it is without changing anything.
By the way I'm separte method to send the creation ajax request, mimicking the orignial datatable editor parameters, and here is my code:
let data = {};
let primary_key=0;
data[primary_key] = {
key: '-',
name: '---'
...
manual_result: manual_result,
};
let formData = new FormData();
formData.append('action', primary_key ? 'edit' : 'create');
formData.append('data', JSON.stringify(data));
And here is the sent request from chrome console:
action: create
data: {"0":{"key":"-","name":"---","manual_result":"<p><img src=\"data:image/png;base64,iVBORw0KGgoA...}}
User select multiple transaction like the picture below and then upload 5 image so per transaction X 5 if they select 1000 transaction its equivalent of 5000 image. My problem is I get a error “Maximum execution time of 30 seconds exceeded”, I resolve it by editing php.ini and put this max_execution_time = 3000, but still I get a error.
here's my code in uploading
$.ajax({
type: 'PUT',
url: "{{ url(config('laraadmin.adminRoute') . '/update_occ_multi') }}",
data: data_value,
dataType: "json",
success: function (data) {
success(output);
var html = '<div class="alert '+data.status+'" role="alert" id="alert-show"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.msg+'</div>';
$('#success_message').fadeIn().html(html);
setTimeout(function(){
$('#success_message').fadeOut(1000);
}, 5000);
},
});
I have a table view which is always filtered by an "interest" controlled by a select widget outside of the table. In this particular table, the user should only be allowed to configure one row per interest, so the table display should show zero or one rows depending on whether this has been configured for the particular interest.
Because of this, I'd like the New button to be sensitized or desensitized depending on whether zero or one rows are displayed respectively.
I see there is a class, ui-state-disabled, that I might be able to use to control this. But I was wondering if there is an API I should be using to control the sensitization.
(for my reference: https://github.com/louking/runningroutes/issues/90)