Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all 81389 articles
Browse latest View live

Server side paging and Elixir/Phoenix


Editor - split a database column data into two editor fields

$
0
0

I have a database column, "start", defined as type DATETIME.

In the editor I would like to split "start" into two editor fields, date and time, so I can use separate "pickers".

Likewise, once created/edited I would like to combine the date and time editor fields back into the database column "start".

I would like the date in "MM/DD/YYYY" format and time in "hh:mm a" format.

Being a bit new to Datatables and Editor, I'm not sure where to start..

Any examples would be welcome.

Regards,
Jim

How to not close edit form after submiting data and show success alert instead

$
0
0

I would like to not close the edit form modal after submitting data and show a success alert instead. onComplete: 'none' ( https://editor.datatables.net/reference/type/form-options ) should do the trick for the first part. But how exactly? That's my button:

    editor.edit( editRow, {
        buttons: ( [
            {
                label: 'Edit',
                fn: function () {
                    this.submit();
                }
            }
        ] )
    } );

Editor: avoid table reloading after an inline edit

$
0
0

I use the DataTables plugin for managing a table with the server-side data source https://datatables.net/examples/data_sources/server_side.html + the Editor plugin.

After some field is edited, submitted and a response from the editor's server handler is returned, the table always completely reloads itself, sending an extra AJAX request to the server, even though there's no need to do that since only one field in only one row was changed and all the data required to redraw the table row have already been received in the previous inline edit response.

So the question is whether it's possible to get rid of the extra AJAX call and redraw the edited row only, rather than completely refreshing the whole table.

Infinite Scroll with Refresh Every 5 Seconds

$
0
0

Hi, I am trying to setup my datatable to sort of be an infinite scroll with server side processing refreshing the data every 5 seconds.

Basically what I want is to initialize the data with the first 20 rows. When the user scrolls to the last row it needs to add the next 20 rows to the datatable. I also need the functionality to refresh the data every 5 seconds through an ajax call to the database. Is there any way that I can accomplish this?

I've been looking at this example currently: https://datatables.net/extensions/scroller/examples/initialisation/simple.html

Thanks for any information.

Using the PHP data() method to access data before it is output

Force Child Row Column on Static Data Table

$
0
0

Hi. First off thanks for DataTables -- a neat and excellent plugin.

My question seems simple but I'm not sure if it's possible. I'm outputting a flat HTML table and activating a responsive DT on it. In order to improve the text display I'd like to force the last td in each row to be a show/hide child row. As this is a static table I don't have access to raw json to create a dynamic show/hide function. So, can this be accomplished with a resonsive DT table? Thanks!

Editor type "datetime" exits as soon as a day is selected withou allowing time to be selected

$
0
0

I am using the "datetime" type for a field in the Editor.

All seems to work well except that:

  1. as soon as I select a date in the calendar portion of the widget the widget closes without allowing me to select a time

  2. if I select a time first (bad human factors as it is at the bottom of the widget) then I can move up to the calendar and select a date.

It would seem that I should be able to select both date and time and when the cursor moves outside the widget it should close or there should be OK/Cancel buttons in the widget.

Am I missing something?

Regards,
Jim


update rows with array of data using draw()

$
0
0

Hi can you please help me on iterating an array to update row using draw().

modalInstance.result.then(function (editRecapGYORVal) {
var rowsData = vm.dataTableInstance.rows({selected:true}).data();
for(var i=0;i<rowsData.length;i++){
rowsData[i].gyor = editRecapGYORVal;
dtRow.data(rowsData[i]).draw();
}
//dtRow.data(rowsData).draw();
//console.log(rowData);
}

I am using above code but it is updating rows with one object data.
for an example my rowsData object holding 2 objects for but when I am iterating the array it always draw 2nd object datas.

Server side pagination using limit 10 or 25

$
0
0

How to add Server Side Pagination in this function, using per page limit 10 or 25

$('#example1').DataTable({
"columnDefs": [
{ "visible": false, "targets": 1 }
],
"order": [[ 0, 'asc' ]],
"displayLength": 10,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;

            api.column(1, {page:'current'} ).data().each( function ( group, i ) {
                if ( last !== group ) {
                    $(rows).eq( i ).before(
                        '<tr style="background-color:    #e5e7e9  ; color:black;font-weight:bold "><td colspan="6">'+group+'</td></tr>'
                    );
                    last = group;
                }
            });
        }
    });

On handling NULL values

$
0
0

When developing a multi-database solution, Editor seems to be ambivalent with NULL.
This conversation mentions that as of 1.7, Editor treats NULL as an empty string: https://datatables.net//forums/discussion/comment/9706/#Comment_9706

Empty strings don't really work for many situations. Take for example the nullable integer field, "FavoriteNumber".

  • User opens an edit form with "FavoriteNumber" and 50 other fields. "FavoriteNumber" and other null (and empty but not null) values are shown as an empty string.
  • User changes some fields but does not modify "FavoriteNumber".
  • When user submits, Oracle interprets the empty string as NULL and writes a NULL. This non-standard and quirky behavior is actually useful in this one case.
  • When user submits to Microsoft SQL, the empty string is interpreted as 0 (zero), so the user has changed the value of the field even though they did not intend to.
    This to me is not ideal, and I can't really find an easy way to deal with it. For example, if I set fields.defto null, an empty string still appears to be sent.

I think Editor should handle NULLs, which are absolutely a reality of database interaction.
This begs the question, "How can Editor handle NULLs?!"
Some ways that come to mind include:

  1. For nullable fields (specified in Editor init or something), generate a checkbox for NULL. I kind of dislike this.
  2. def:null sets the value to null instead of an empty string (or maybe def:undefined or similar)
  3. Interpret some probably user-specified sentinel value as NULL, for example, "(null)", and set the field to this value when the incoming JSON for that entry is null.

I am sure it's more complex than this, for example, how can null be specified in HTML or over an HTTP POST or GET.
Perhaps an internal sentinal value of Ø, which is HTML &#216; or URL-encoded as %C3%98 (not to be confused with ø, ∅, or ⌀ ...Ah, Unicode).

Any thoughts on how to handle NULLs, anyone?

Datatable rendering taking 10 sec to load 2000 rows

$
0
0

Hi
We are using jquery datatable to render about 2300 records.we have 15 columns in it and out of 15 , 8 columns are using custom renderers like placing images in it. We are also having client side pagination.What can we make to decrease the grid load time.Below is example of one column renderer. We have similar renderers across 8 columns.I heard about deferRender attribute.Does it help my case.And also am doing some operation on createdRow

{
"render": function ( data, type, row ) {
var catetatus = row.categoriesStatus;
var output = convertTimeFromMs(data, type, row );

                                                                            var imageStr = '<img alt="5:" src="/IpvodWebApp/resources/images/white.gif" height="1" width="1"/>';
                                                                            var sortingTime;

                                                                            if(data == undefined)
                                                                                 data = "";
                                                                            else
                                                                                sortingTime = millitoMinutes(data);

                                                                            if(catetatus == 'Posted' && output.length > 0)
                                                                                imageStr = '<img alt="1:'+ sortingTime +'" src="/IpvodWebApp/resources/images/whitecircle.png" />';
                                                                            if(catetatus == 'Queued' && output.length > 0)
                                                                                imageStr = '<img alt="2:'+ sortingTime +'" src="/IpvodWebApp/resources/images/waitcircle.png" />';
                                                                            if(catetatus == 'Working' && output.length > 0)
                                                                                imageStr = '<img alt="3:'+ sortingTime +'" src="/IpvodWebApp/resources/images/loading_image.png" />';
                                                                            if(catetatus == 'Completed' && output.length > 0)
                                                                                imageStr = '<img alt="4:'+ sortingTime +'" src="/IpvodWebApp/resources/images/green.png" />';

                                                                            return  imageStr + '<p title=\"'+ convertUTCDatetoLocalDate(data) +'\">' + output + '</p >';
                                                                     },
                                                                    "data": "categoriesTime",
                                                                    "defaultContent": "",
                                                                    "type": "alt-string",
                                                                    "targets": [10],
                                                                    "width": "97px"
                                                                },

One Search button for two categories

$
0
0

Hi,

I have different categories in my table and I want to implement one search button to show two categories (of 5).

Actually I use this code:

{
                text: 'Purchased',
                action: function ( e, dt, node, config ) {
                    var table = $('#sites').DataTable();
                    table.columns( 1 ).search( "Purchased" ).draw();
                }
            },{
                text: 'Sold',
                action: function ( e, dt, node, config ) {
                    var table = $('#sites').DataTable();
                    table.columns( 1 ).search( "Sold" ).draw();
                }
            }

And I tried to change it into this (which doesn't work also with enabled regex):

{
                text: 'Purchased or Sold',
                action: function ( e, dt, node, config ) {
                    var table = $('#sites').DataTable();
                    table.columns( 1 ).search( "Purchased|Sold" ).draw();
                }
            }

Have anybody an idea to merge the to buttons without changing the categories?

Thanks in advance

Patrick

jQuery anti cache paremeter

$
0
0

I have seen it written that to disable the jQuery anti cache parameter, you should set ajax.cache = true. Is this a configuration parameter for the table or something global? Can someone give a code example?

Datatables - Responsive Row Trigger

$
0
0

https://datatables.net/reference/event/responsive-display

I'm having a issue where the ajax reload function is causing the datatables responsive plugin to close the open row details.
table.ajax.reload( null, false );

I'm aware of a workaround for select2 fields by listening for the ajax request (below) and I am confident I'll have to use this approach with this issue.
table.on('xhr.select2Fix', function(){

My question is can I trigger the responsive plugin to open a row ID manually (for my problem here I can simply record the rowID on this event)
table.on( 'responsive-display', function ( e, datatable, row, showHide, update ) {

or do I only have the option of using the button beside the row to toggle the expansion/retraction of the responsive display?


Is it possible to clear a prior field when using the 'Duplicate' button in Editor?

$
0
0

I am utilizing the Duplicate Button feature to enable adding entries to an existing (master) item, by capturing the item's master ID. However, I wish to 'erase' the text from the prior entry when the Editor window opens. My searches haven't led me to a solution. Can you point me in the right direction?

Implement excel style edit and auto update using ajax.reload() in a drawCallback

$
0
0

Allen,

I am trying to provide a table which behaves somewhat like excel, in that if you edit a cell, other cells will update based on a formula. I implemented a php function which recalculates and updates all table elements which were impacted by the POST data

I then need to have this RUN as a post edit event. This failed, so I thought I could do an ajax.reload using a drawCallback, but I cannot get that to function either

I seem to be wrestling with 2 issues:

1

        var affordTable;
    $(document).ready(function() {
        var affordTable = $("#affordTable").DataTable( {
                        dom: "Bt",
            "drawCallback": function( settings ) {
                affordTable.ajax.reload();
            },
                       ......

results in: TypeError affordTable is undefined
What am i doing wrong?

In the server side
```
->on( 'postEdit', function ( $editor, $id, $values )
{
updateSubtotals();
})

Which calls php function to calculate and update subtotal columns in a mysql table, causes a
Lock wait timeout exceeded error in mysql (the query executes just fine from phpMyAdmin)

Any idea why this occurs?

Sorted select list with selectize.js?

$
0
0

Hi,

I use selectize.js and the following code

$(document).ready(function() {
  editor = new $.fn.dataTable.Editor( {
    ajax: '/online-erfassung/edit-table.php',
    table: '#kledit',
    fields: [
      { label: '1. Verfasser',
        name:  '_100_1_a',
        options: [],
        type: 'selectize',

        opts: {
          valueField: 'NAMEN',
          labelField: 'NAMEN',
          searchField: 'NAMEN',
          sortField: 'NAMEN',  // Sorting does not work ??
          create: true,
          load: function( query, callback ) {
                  if ( query.length <= 1 ){ return callback()};
                  $.ajax({
                    url: "/cgi-bin/online-erfassung/2014/select-data.pl",
                    type: 'GET',
                    dataType: 'json',
                    data: { start: query,  col: "NAMEN", table: "PERSONENNAMEN", endtrunkierung: "1" },
                    error: function() { callback(); },
                    success: function(res) { callback(res); },
                    // success: function(res) { alert( "Press Enter" ); callback(res); },
                    create: function (input){ return {name: _100_1_a, text: input }}
                  });
                }
        }


      { label: more labels ... }

    }
    formOptions: {
      main: {
        onReturn: false,
        onBlur: "submit"
      }
    }
    more code ...
  });
});

my problem is that the select list returned is not sorted even though the JSON response from the server is sorted alphabetically. An excerpt of the JSON data is for example:

[{"NAMEN":"Grasso, Elsa"},{"NAMEN":"Grasso, Giuseppe"},{"NAMEN":"Grasso, Luciana"},{"NAMEN":"Grasso, Maurizio"},{"NAMEN":"Grasso, Paolo"}]

Alas, when I activate the commented line 26 containing "Press Enter", and deactivate the previous line 25, the select list will be sorted. Besides the fact that I con't understand why, I generally would prefer a sorted select list since a sorted list is better understandable by the user.

Is there any possibility to get a sorted list without the otherwise unnecessary alert command?

Thanks,
Eberhard
~
~

Sample implementation of serverside processing in C# MVC, EF with paging/sorting/searching

$
0
0

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

Unable to add additional columns due to ajax error

$
0
0

Hello!

At the moment I'm attempting to add another column to my page. However, I will get an ajax error whenever I do. It's fine with 10 columns, but as soon as I add the 11th, the ajax error will appear.

Here's my debugger
http://debug.datatables.net/ewolon

And the console error shows:
responded with a status of 403 (Forbidden)

Viewing all 81389 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>