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

Displaying Master - Child table

$
0
0

Hi,

I am new to data table and developed a page which displays master-child table based on example given on datatables.net .
On click of + sign on row, I do a ajax call to server and binds the returned records to a child table. My issue is function's return statement is fired prior to finishing the ajax call and on the the first hit I don't get any record. Onward second call it returns the records of first call and so on. Below is the code I have written. Any hep is highly appreciated.

   function ShowContainerData(obj) // this function is called on click of + sign of row.
    {

            var tr = $(obj).closest('tr');
            var row = table.row(tr);

            //console.log(row.data().ContainerNumber);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                $(obj).attr('src', '/Content/web/images/details_open.png')
                //tr.removeClass('shown');
            }
            else {
                // Open this row
                row.child(format(row.data())).show();
               // tr.addClass('shown');
                $(obj).attr('src', '/Content/web/images/details_close.png')
            }

         //child table --end
    }

    /* Formatting function for row details - modify as you need */
    function format(d) {
        // `d` is the original data object for the row

        $.ajax({
            type: "POST",
            url: "/landside/generic/AwaitingBooking.aspx/GetDetailTableData",
            data: "{ ContainerNumber: '" + d.ContainerNumber + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "false",
            cache: "false",
            success: function (output) {
                ordertable = '';
                ordertable = '<table class="display table table-bordered table-striped table-condensed table-hover nowrap">' +
                '<tr>' +
                    '<thead><th>Order Number</th>' + '<td>Lot</th>' + '<th>Priority</th><thead>'
                '</tr>';
                for (var order = 0;order<JSON.parse(output.d).length; order++)
                    {
                    ordertable = ordertable + '<tr>'
                        + '<td>' + JSON.parse(output.d)[order].OrderNumber + '</td>'
                        + '<td>' + JSON.parse(output.d)[order].Lot + '</td>'
                        + '<td>' + JSON.parse(output.d)[order].Priority + '</td>'
                        + '</tr>'

                    }
                    ordertable = ordertable+'</table>';
            },
            Error: function (x, e) {
                // On Error
            }
        });
        //alert(ordertable);
        return ordertable;

}

Thanks in advance ,
Ram


fixed column update- update footer values

$
0
0

thanks for datatable is awesome
i have a question, i have a table with a sum of columns values in the footer and fixed columns, so when the data changes the footer values should change but they don't. in the documentation of fixedColumns().update() state that we should update the new table which was created to deploy fixed column. example in the doc.

var table = $('#myTable').DataTable();

table.cell( 0, 0 ).data( 'New data' ).draw();
table.fixedColumns().update();

but i need to update the footer values of the new fixed table and the main table.
thanks in advanced

Server Side paging has no effect on backend using PHP DataTables Editor class

$
0
0

DataTable Settings: serverSide: true, processing: true, lengthChange: false, select: true
Ajax request sent: [draw] => 1 [start] => 0 [length] => 10
Query generated by Editor class has no limits and is selecting the ~92k records.
Observing the response - entire lot of 92k records is sent back.

footer disorder after filtering

$
0
0

greetings and thanks for this awesome plugin
i have enabled fixed column and i find a solution to use fixed header and fixed column at the same time.
https://jsfiddle.net/azcmd76r/
i have a problem in my datatable footer, after filtering i have my datatable like this. i have a footer disorder i don't know why?

Mapping json response array and reloading ajax

$
0
0

I have a date selector used for a "WHERE" condition in a SELECT statement...the json encoded result is received back to the ajax calling script.for loading the datatable.
1) HTML table

Member Name Cash Check Check Detail Credit Card Paypal Click on Receipt

2) js
$(document).on("click","#btnSubmitDateSummary",function() //Click a submit button after selecting the date
{
var summaryDate = $("#summaryDate").val(); //MM/DD/YYYY
var url_get_data = "xxxxxxxx/get_day_summary.php?summaryDate=" + summaryDate;

  var table = $('#table_members').DataTable({
    "retrieve": true,  //table will be reloaded with different data
    "paging": true,
    "lengthChange": true,
    "searching": true,
    "ordering": true,
    "info": true,
    "responsive": true,
    "autoWidth": false,
    "pageLength": 10,
     "columns": [
    { "data": "name" },
    { "data": "cash" },
    { "data": "check_amount" },
    { "data": "check_detail" },
    { "data": "creditCard" },
    { "data": "paypal_amount" },
    { "data": "test" }
    ]
  });
 table.ajax.url(url_get_data).load();

});

3)json response is good and as expected:
{"name":"Leota Dilliard","cash":"45","check_amount":"0","check_detail":"","creditCard":"0","paypal_amount":"0","test":"test"}

Success: can select different dates, and will get different response...that is good.
Failure : No data in the table..."No data available in table"

What am I doing wrong ?

Export PDF and Excel With Decimal Separator

Data fetching Url calling twice

$
0
0

data Fetching url calling twice. script attached.

$(document).ready(function () {
    $('#tCity').DataTable(
    {
        "order": [[2, "asc"]],
        "pagingType": "numbers",
        "columnDefs": [
            { "className": "text-center custom-middle-align", "targets": [0], "width": "7%", "searchable": false, "orderable": false },
            { "className": "text-center custom-middle-align", "targets": [1], "width": "10%", "searchable": true, "orderable": true, "visible": false },
            { "className": "text-left custom-middle-align", "targets": [2], "searchable": true, "orderable": true },
            { "className": "text-center custom-middle-align", "targets": [3], "width": "10%", "searchable": true, "orderable": true, "visible": false },
            { "className": "text-left custom-middle-align", "targets": [4], "searchable": true, "orderable": true },
            { "className": "text-center custom-middle-align", "targets": [5], "width": "8%", "searchable": false, "orderable": false },
        ],
        "language":
            {
                "processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
            },
        "processing": true,
        "serverSide": true,
        "ajax":
            {
                "url": "City.aspx/GetCityList",
                "contentType": "application/json",
                "type": "GET",
                "dataType": "JSON",
                "data": function (d) { return d; },
                "dataSrc": function (json) {
                    json.draw = json.d.draw;
                    json.recordsTotal = json.d.recordsTotal;
                    json.recordsFiltered = json.d.recordsFiltered;
                    json.data = json.d.data;
                    return json.data;
                }
            },
        "columns": [
                    { "data": "RowNumber" },
                    { "data": "iCityId" },
                    { "data": "strCity" },
                    { "data": "iStateId" },
                    { "data": "strState" },
                    { "data": "Action" }
        ]
    });
});

Change cell backgrondColor with ajax

$
0
0

I want to do this something like this

$(document).ready( function () {
  var table = $('#example').DataTable({
    "createdRow": function( row, data, dataIndex ) {
             if ( data[2] == "London" ) {
         $(row).addClass('red');
       }
    }
  });
} );

example : http://live.datatables.net/tohehohe/1/edit
but in this example the table is all ready in HTML how can y do this if I send the info in ajax?

MyCode:

 $('#InventarioDataTable').dataTable({
            "order": [[2, "asc"]],
            ajax: "Inventario/GetList",
            columns: [
                {
                    data: "Ingrediente1",
                    render: function (data, type, row) {

                        return row.Ingrediente1+'  <input  type="hidden" id="Id" name="Id" value="' + row.Id + '">';// ('<input type="checkbox" class="editor-active" value="true" ' + checked + ' disabled>');

                    }
                },
                { "data": "Tipo" },
                { "data": "Prefijo" },
                {
                    "data": "CantidadMinima"
                },
                {
                    data: "Cantidad",
                    //try
                    render: function (data, type, row) {
                        if (row.Cantidad >= row.CantidadMinima + (row.CantidadIdeal - row.CantidadMinima) / 2) {
                            $('td', row).eq(4).css('background', 'green');
                        }
                        if (row.Cantidad< row.CantidadMinima + (row.CantidadIdeal - row.CantidadMinima) / 2) {
                            $('td', row).eq(4).css('background', 'orange');
                        }
                        if (row.Cantidad <= row.CantidadMinima) {
                            $('td', row).eq(4).css('background', 'red');
                        }
                        return row.Cantidad;
                    }
                },
                { "data": "MichoacanaId" }
            ]
        });~

How to display the Message in datatable?

$
0
0

I am getting the Json response {"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[["","","","",""]]} , the datatable is converting the null values to empty string, so i want to show the message "No recordings found" for that record.

please help,Thanks in advance!

Set columns width

$
0
0

Hello.

I'm using DataTables 1.10.16 with Bootstrap 3 integration.

I initialize datables as follow:

$('#dataTable').DataTable({
"paging": false,
"searching": true,
"dom": "t",
"autoWidth": false,
"language": {
"url": "/js/dataTables.Russian.json"
},
// Тюнинг размеров колонок
"columnDefs": [
{ "width": "150px", "targets": 1}
]
});

But in result i've got rendered column width 173 px (by browser devtools measurement). In TH style there is width:150px. What i should to do, to have 150px width rendered?

Thannks.

Set ORDER BY on server side

$
0
0

Hi,
Is there any way to order the columns initially in the PHP server file? (using the PHP library)
I have found the order('col1,col2') function, however it seems I cannot use it within Editor::inst()->... calls.
This would help to order the columns by name instead of index.
Thanks and best regards

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

Add more button on editor form

$
0
0

Hello Allan,
I have a use case where the user should be able to add more fields to a form when he clicks a button shown on the form itself,

but there is no field type : button ... can u please help me figure this out.. is there a way to achieve that . ??

Standalone editor - without datatables but with database read/write

$
0
0

Is it possible to have functionality (standalone editor) like this:
* I can generate any html page (i.e. google maps), and object identified by table row_id
* I can open editor main form using api, sending row_id (editor.edit(row_id) )
* however, form is not initialised (because datatable is missing - standalone mode)
* when I put values in the form and save, it's ok, values are saved in the correct record on server

Can I initialize form somehow smartly ? I can see only two options now:
* I can write form values into html elements during the page generation
* I can make some ajax call (preferably same one as for datatables init) and fill the values via editor.set calls

I really would like to open same editor form as for datatables mode (which can be complex, with select2, upload forms)
Is it possible ?

MJoin tables

$
0
0

Hello Alan.
I need your help to connect two tables together using the same generator Id.
For example, one employee has certain generator Id and when he/she starts to create a new row of the table, this row will have the same generator id connect this employee and his rows.
When I want to open this form it should show me only his/her rows that connect to his/her form. The Database will store all rows from employees. I try to figured it for couple weeks already and I am stuck on it. Please give me idea what do I need to use here to resolve this issue.
I tried to use in Controller table "Where" statement but it didn't work.
There are my code for Table js:

(function($){

$(document).ready(function() {
var editor = new $.fn.dataTable.Editor( {
ajax: '/api/Table',
table: '#Table',
fields: [
{
"label": "GeneratorID:",
"name": "generatorid",
"className": "formidne"

        },
        {
            "label": "MATExample#:",
            "name": "mate_example"
        },
        {
            "label": "Description:",
            "name": "description",
            "type": "textarea"
        },
        {
            "label": "Example2",
            "name": "example2"
        },
        {
            "label": "Example3:",
            "name": "example3"
        },
        {
            "label": "Example4",
            "name": "example4"
        }
    ]

});

editor.on('open', function () {

    var id1 = $("#thisid").val();
    var id2 = $("#thisid2").val();
    if (id1 != "") {
        var id = $("#thisid").val();


    }
    else {
        var id = $("#thisid2").val();

    }

    $("#DTE_Field_generatorid").val(id);
    $(".formidne").hide();



});

var table = $('#Table').DataTable({
    columnDefs:[
       {visible:false,targets:0}
    ],
    dom: 'Bfrtip',
    ajax: {
        url: '/api/Table',
        type:"post",
        data: {"generatorid": formId}
         data:function(data){
           data.generatorid = $("#thisid2").val();
            var formId = data.generatorid;


         }

},

    columns: [
        {
            "data": "generatorid"

        },
        {
            "data": "mate_example"
        },
        {
            "data": "description"
        },
        {
            "data": "example2"
        },
        {
            "data": "example3"
        },
        {
            "data": "example4"
        }
    ],

    select: true,
    responsive:true,

    buttons: [
        { extend: 'create', editor: editor },
        { extend: 'edit',   editor: editor },
        { extend: 'remove', editor: editor }
    ]
});

} );

}(jQuery));

Code for Controller:

public class AdjustmentTableController : ApiController
{
private readonly string dbCon = " Example";
[Route("api/Table")]
[HttpGet]
[HttpPost]
public IHttpActionResult Table()
{

        var request = HttpContext.Current.Request;

        using (var db = new Database("sqlserver", dbCon))
        {

            var response = new Editor(db, "Table","generatorid").Where(q => q.Where("generatorid", " ", "="))
                .Model<TableModel>()
                .MJoin(new MJoin("Form").Model<Model>()
                 .Link("Table.generatorid", "Form.generatorid"))
                .Process(request)
                .Data();

            return Json(response);
        }
    }
}

}

Using Mjoin should give me results from both tables but don't working.

Also, have cshtml and model class that they are easy.

Please give me ideas what do I need to use, maybe "LeftJoin " statement I can use. Let me know if you need anythin else.

Thank you very much!!


How do I scroll to a specific column?

$
0
0

It looks like this question has been asked a number of times before, but the discussions are all closed with no response. Please let me know if this is possible. I'm trying to do it in the columnDefs[createdCell...] function.

sort indicators don't show up in thead-section

$
0
0

new to datatables .... I don't see the sort indicators in the thead-section ..

Replacing text with icons

$
0
0

Using datatable on SharePoint Online, is there a way to replace the text with icons based on values?
Example: Value = In, display <img src='/_layouts/images/KPIDefault-2.GIF'/>

I was using client side rendering but can't figure out how to do this in datatable.

(function() {
    var oFldCtx = {};
    oFldCtx.Templates = {};
    oFldCtx.Templates.Fields = {"InOut": {"View": overrideStatus} };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(oFldCtx);
})();

function overrideStatus(ctx) {
    var oStatus = ctx.CurrentItem.InOut;

    if (oStatus == 'In')    {
        return "<img src='/_layouts/images/KPIDefault-0.GIF'/>";
    }
    if (oStatus == 'Out-A')     {
        return "<img src='/_layouts/images/KPIDefault-2.GIF'/>";
    }
    if (oStatus == 'Out-P')     {
        return "<img src='/_layouts/images/KPIDefault-1.GIF'/>";
    }

}

boot strap datatable with child rows and export to excel

$
0
0

Hi all
can any one pls give an example for boot strap datatable with child rows and export to excel

dynamically adding a field and submitting new field to server

$
0
0

Hello,
I am working on a contact management solution and need to have the ability to dynamically add input fields to capture contact information for multiple people. At the time the form is initialized I can only assume there will be at least one contact, but I do not know if there are 2 or 10 more contacts my users would like to enter. From a UI perspective, when the user starts typing in contact information, I am able to use editor add() to add a new field for the second contact, third etc. However when the data is submitted to the server, the dynamically created fields do not show in the JSON string.

I assume it is because the newly created fields have been added to the UI but editor object is unaware of them.

Any thoughts or ideas? I would assume the editor add() function would add it to the UI and the data object.

Viewing all 79535 articles
Browse latest View live




Latest Images