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

How to do child rows sorting


Error passing parameters to Editor global validators

$
0
0

I have a very simple example of a .NET server-side method with a global validator, as specified here. For the sake of simplicity, I made my example exactly the same as the example on that page:

public JsonResult EditorExample(int id)
{
    using (var db = new DataTables.Database("sqlserver", db.Database.Connection.ConnectionString))
    {
    // Allow read only access based on a session variable
    var response = new Editor(db, "table")
        .Model<TableModel>()
        .Validator( (editor, action, data) {
            if ( action != DtRequest.RequestTypes.DataTablesGet && Session["ReadOnly"] ) {
                return "Cannnot modify data";
            }
            return "";
        } )
        .Process(request)
        .Data();
        return Json(response, JsonRequestBehavior.AllowGet);
    }
}

I am having a number of issues with compiling the .Validator() method. The first issue is with the (editor, action, data) parameters; I get an error saying that they don't exist in this context. To resolve this, I specify their types:

 .Validator((Editor editor, DtRequest.RequestTypes action, DtRequest data)

when I do this, I get three different compile errors:
1. Argument 1: Cannot convert from '(DataTables.Editor, DataTables.DtRequest.RequestTypes, DataTables.DtRequest)' to 'Func<Editor, DtRequest.RequestTypes, DtRequest, string>'
2. A declaration is not allowed in this context.
3. Use of unassigned local variable editor/action/data.

I have a general idea of what each of these errors mean, but I don't know how to fix them.
1. Going through the Editor source, I can see that the .Validator method does indeed expect Func<Editor, DtRequest.RequestTypes, DtRequest, string>. But reading about this kind of error online, it seems as if .NET should see that I'm passing Editor, DtRequest.RequestTypes, DtRequest and it should solve this kind of thing on its own
2. I don't really know what's up with this one. Why can't I declare variables inside an Editor declaration? I can declare other variables...
3. This would suggest that I am declaring them, but they don't actually exist in memory as Editor/DtRequest.RequestTypes, DtRequest types.

I'm pretty lost here. Is this a common issue? Is it related to my .NET installation? Any help appreciated!

Confused about when ajax.dataSrc is executed

$
0
0

Hello,

I have an ASP.NET, MVC 5, .Net 4.5, C#, JavaScript, Jquery Datatables web application developed in Visual Studio 2017 Community.

It allows a user to select a datatables mailbox(masterTable) entry and when the user clicks a download button, it gets all of the emails and displays them in another datatables email(detail) table on the same screen. After the emails are downloaded, it displays the date and time it downloaded in the CommunicationStatus column of the masterTable. It does do that.

I am having a problem, when I click the download button the first time, it displays a blank in the CommunicationStatus column of the masterTable. The next time I click the download button, it displays the date and time from the previous download in the CommunicationStatus column. The same with successive downloads, it always displays the previous download status in the CommunicationStatus column.

I started to setup a live.datatables.net test, but after thinking about it, I can't really allow a test without putting in live mailbox data with valid email usernames and passwords. I don't want to do that and I think you know why.

I did put all of my HTML and Javascript code there: live.datatables.net/xohosila/4/edit?html,css,js,console,output and I can tell you that the code for the download button click is this:

                    $('.email-download').click(function () {
                         //alert("made it to email download");
                         masterTable.rows().every(function (rowIdx, tableLoop, rowLoop) {
                              if ($(this.node()).hasClass('selected')) {
                                   var data = this.data();
                                   currentrow = masterTable.row(rowIdx).index();
                                   //masterTable.cell(currentrow, 7).data("Processing");
                                   masterTable.cell(rowIdx, 7).data("Processing");
                                   selected = data.MailboxID;
                                   $('#detail').show();
                                   $('#detail').DataTable(detailsTableOpt).draw();
                                   masterTable.cell(rowIdx, 5).data(mails);
                                   masterTable.cell(rowIdx, 7).data(comm_status);
                                   comm_status = "";
                                   mails = 0;
                              };
                         });
                    });

.
I took it through the F12 debugger and I noticed that it executes all of the above code before executing this:

                              "dataSrc": function (json) {
                                   comm_status = json.data.queryStatus;
                                   mails = json.recordsTotal;
                                   return json.data;
                                   }

.
In the #detail datatable. That's not consistent with the way I interpreted this: https://datatables.net/reference/option/ajax.dataSrc

Does anyone know how I can get the "dataSrc": function (json) to execute before it returns to after the $('#detail').DataTable(detailsTableOpt).draw(); statement?

Any help that anyone can provide to resolve this problem would be gratefully appreciated.

Thanks,
Tony

Bubble Form

$
0
0

Alan,
I have a database which displays driver and vehicle number, however, it show the text. How can I perform the following with my editor.

  1. on a list of rows, enable a user to change the one or more rows of driver and vehicle number, using a drop down which is from a query. Once they submit a form, it changes all of the driver and vehicle number by passing individual id for both driver and vehicle.
  2. enable user to click on the driver or vehicle and use a bubble editor which will show as a drop down , instead of text value, and to be able to update using ajax.
  3. increase the size of the bubble screen size.

I guess I'm having a hard time trying to make it a drop down which the list if generated from a query.

Thanks in advance.

data is truncated at the comma

$
0
0

Hi--

Whenever my cell's data contains a comma, the text after it is truncated. Is there way around this?

I'm getting my data from an Ajax post, and creating the table like this:

var rt=$("#resultsTable").DataTable({
    data:s
});

What I see, for example, is this:

Some Company

Instead of this:

Some Company, Inc.

Any help is appreciated. Thank you!

Filter Datatable from External Link

$
0
0

Hi all,

i want to filter Datatable when coming from an other Page - is this possible??

row.child(true).remove has not effect on memory

$
0
0

Hello,

I have a main datatable with child rows, and each child row has its own datatable.

I use the function row.child(true).remove in order to close the child rows, however the memory seems not to be released. The memory used by Chrome is getting bigger and bigger every time I open and close a child row.

Do you have any idea to help me to solve this problem please ?

Note that I use Ajax (JSON source) for the main and the child datatables.

HTML code for the main datatable :

<table id="tableProcedure" class="display compact" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
                <th>Col 4</th>
            </tr>
        </thead>
 </table>

Javascript code :

    var tabProc = $('#tableProcedure').DataTable(
        {
            ajax: {
                url: "JSON/PROCEDURE.json",
                dataSrc: ""
            },

            columns: [
            { data: "P_OBJ"},
            { data: "P_PDT"},
            { data: "P_ACT_C"},
            {
                data: null,
                orderable: false,
                defaultContent: '',
                className: "details-control-proc"
            }
            ]
        }
    );


    function formatProcedureFils ( rowData ) {
        var div = $('<div/>');

        $.ajax( {
            url: '../detailsProc.php',
            dataType: 'html',
            success: function ( htmlReturn ) {
                div.html( htmlReturn );

                div.find('table').DataTable(
                {
                    ajax: {
                        url: "JSON/PROCEDURE-FILS.json",

                        dataSrc: function ( json ) {
                          return json;
                        }
                    },

                    columns: [
                    { data: "P_PRESTL" },
                    { data: "P_DELMAX" }
                    ]
                });

            }
        } );

        return div;
    }


    $('#tableProcedure tbody').on('click', 'td.details-control-proc', function () {
            var tr = $(this).closest('tr');
            var row = tabProc.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child(true).remove();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child( formatProcedureFils(row.data()) ).show();
            tr.addClass('shown');
            }
    });

Thank you for your help.
Anthony

Search array of numbers for exact match

$
0
0

I am trying to setup the search function on a table I am using. It is working great, except one of the columns (which is hidden) is an array of ids. I then have an "advance" search function where I allow the user to select a list of items, and then I want to use the selected items (array of int) to search through the hidden column. For example, if the column has [2, 3, 4, 11, 12] and the advance search returns [1] The search right now will return the row because it matches on [11, 12]. If I use regex for the exact match, it tries to match on the whole array, instead of just searching the ints in the array. Can someone please help me figure out how I can search an array of ints for exact matches?!


DataTables CSS doesn't always fire up

$
0
0

Hello,

My DataTables CSS doesn't always fire up. I know my click event works, because the JSON I'm parsing is returning data in the table, but the table itself does not have CSS. This issue happens sporadically and I've been unable to pinpoint the issue. I've read that it could be CSS clashing, but I'm not absolutely sure.

I've attached four images; two are images of it not working(mobile and desktop) and two are what it looks like when the CSS is working(Desktop and mobile).

Individual column searching with ColReorder

$
0
0

Hi,

If I use this ColReorder plugin: https://datatables.net/extensions/colreorder
with this Multi filter plugin: https://datatables.net/examples/api/multi_filter.html
It does not works as I expect it, if you load the jsfiddle example below, and grab the age column and move it to the first place, and you try to filter by age 22, it says "No matching records found" if I type 22 in the "Search Name" input it filters the table by age:
https://jsfiddle.net/hujtomi/p55cktxw/1/

What am I doing wrong?

Thanks,
Tomi

Root Element missing in json output

$
0
0

Hi,

I am unable to populate my dataTables due to the missing 'root' element.

Please see below code and help me how to fix it.

Piece 1:

  $('#example').DataTable({
       //"ajax": "density.txt",
       "ajax" : "getProductPropData",
       "dataType": 'json',
       "contentType": "application/json; charset=utf-8",
        "columns": [{
            "data": "densityId"
        }, {
            "data": "densityDescription"
        }, {
            data: null,
            className: "center",
            defaultContent: '<a href="#" id="edit" class="edit" data-toggle="modal" data-target="#myModal">Edit</a> / <a href="#" id="delete">Delete</a>'
                //defaultContent: '<button type="button" class="btn-default" data-toggle="modal" data-target="#myModal">Open Modal</button>'
        }]
    });

Piece 2: What I am in in my Struts 2 action class.

public String execute() throws Exception {

        SessionFactory sf = (SessionFactory) ctx.getAttribute("SessionFactory");
        ProductPropertyDAO pdao = new ProductPropertyDAOImpl(sf);
        List<DensityGroup> dg = pdao.getProductPropListData("Density");

        List<DensityGroup> list = new ArrayList<DensityGroup>();
        System.out.println("SIZE is: " + dg.size());

        for (int i = 0; i < dg.size(); i++) {
            DensityGroup denpojo = new DensityGroup();
            denpojo.setDensityId(dg.get(i).getDensityId());
            denpojo.setDensityDescription(dg.get(i).getDensityDescription());
            list.add(denpojo);
        }

        data = list;

        System.out.println("JSON is :\n" + data);
        return "success";
    }

My JSON Data from Chrome Network tab is:

[{"densityDescription":"16 KG","densityId":"21"},{"densityDescription":"Chitti","densityId":"22"}]

Correct data should be:

{"data" : [{"densityDescription":"16 KG","densityId":"21"},{"densityDescription":"Chitti","densityId":"22"}]}

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

resize search fields when using columns().search()

setFormatter

$
0
0

I managed to format the date in the date field to dd-mm-yyyy, when the user has entered his date. But it is not saved because I don't understand how to use setFormatter. The examples are not very clear (to me that is :-) )
this is what I have:

editor = new $.fn.dataTable.Editor( {
        //ajax: {url: "php/table.deelneming_v2.php"},
        ajax: {url: "data/deeln.txt"},
        table: "#deelnTable",
        idSrc:  'id',
        fields: [ {
                label: "relatienr:",
                name: "client"
            }, {
                label: "naam:",
                name: "naam"
            }, {
                label: "publicatie :",
                name: "publdatum",
                type:   'datetime',
                /*
                def:    function () { return new Date(); },
                format: 'DD-MM-YYYY',
                fieldInfo: 'Verbose date format',
                */
                opts:  {
                    format: 'DD-MM-YYYY',
                    showWeekNumber: true
                }
            }, {
                label: "dividend 2016:",
                name: "div_2016"
            }, {
                label: "opgeofferd bedrag:",
                name: "offer"
            }, {
                label: "verkrijgingsprijs:",
                name: "verkrijgingprijs"
            }, {
                label: "goodwill:",
                name: "goodwill"
            }
        ],
        i18n: {
            create: {
                button: "nieuw",
                title:  "deelneming toevoegen",
                submit: "bewaar"
            },
           edit: {
                button: "wijzigen",
                title:  "deelneming wijzigen",
                submit: "bijwerken"
            },
            remove: {
                button: "verwijder",
                title:  "verwijder deelneming",
                submit: "bevestig",
                confirm: {
                    _: "Weet u zeker om %d te verwijderen?",
                    1: "Deze regel 1 verwijderen?"
                }
            },
            datetime: {
                previous: 'vorige',
                next:     'volgende',
                months:   [ 'Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December' ],
                weekdays: [ 'zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat' ]
            }
        }
    } );      //editor

and serverside:

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'deelnemingen' )
    ->fields(
        Field::inst( 'client' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'naam' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'locatie' ),
        Field::inst( 'offer' )
            ->validator( 'Validate::numeric' )
            ->setFormatter( 'Format::ifEmpty', null ),
        Field::inst( 'verkrijgingprijs' )
            ->validator( 'Validate::numeric' )
            ->setFormatter( 'Format::ifEmpty', null ),
        Field::inst( 'goodwill' )
            ->validator( 'Validate::numeric' )
            ->setFormatter( 'Format::ifEmpty', null ),
        Field::inst( 'div_2016' )
            ->validator( 'Validate::numeric' ),
        Field::inst( 'publdatum' )
            //->setFormatter( 'Format::ifEmpty', null )

            ->validator( 'Validate::dateFormat', array(
                "format"  => Format::DATE_ISO_8601,
                "message" => "Please enter a date in the format dd-mm-yyyy"
            ) )
            ->getFormatter( 'Format::date_sql_to_format', Format::DATE_ISO_8601 )
            ->setFormatter( 'Format::date_format_to_sql', Format::DATE_ISO_8601 )

    )
    ->process( $_POST )
    ->json();

Demo is available on http:\ficos.nl\test\index.html

The setFormatter function is not working for me: I guess DATE_ISO_8601 accepts yyyy-mm-dd only.
What am I doing wrongly?

Adding child rows without toggle sign

$
0
0

I want to dynamically add child rows below each parent rows in HTML table. This link shows how to do it by adding hide/show option:- https://datatables.net/examples/api/row_details.html, but I want to avoid that and display child rows without having to click show/hide option. Also the data are dynamically loaded from ajax call. I parse the JSON response from ajax call and append in HTML table using JavaScript and DataTable in following way:-

function displayFruits() {

$.ajax({

    type: "GET",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    dataType: "json",
    url: "http://www.dummyexample.com",

    success: function(data) {

            tr = $('<tr/>');
            tr.append("<td>" + data[i].name + "</td>");
            tr.append("<td>" + data[i].type + "</td>");
            tr.append("<td>" + data[i].cost + "</td>");
            tr.append("<td>" + data[i].season + "</td>");
            tr.append("<td>" + data[i].vitaminContent + "</td>");
            $('#tableId').append(tr);
        }

            $('#tableId').DataTable();
    },
    error: function(xhr, ajaxOptions, thrownError) {
        // handle your fail response here
}); //end of ajax

} // end of displayFruits() function

In above example, instead of displaying season and vitaminContent in separate column, I want to display them as child row below parent row. How can I achieve that?

Invalid JSON Response from jQuery Server Side

$
0
0

I copied the server-side example files from github.com/DataTables/DataTables/tree/master/examples/server_side:
the HTML file I used was simple.html and the scripts: server_processing.php and ssp.class.php, and I modified the database configuration to my specifications. I inserted mysql.sql (copied from the same location) in my DB also without modification.

They are in the same DB. If I use the default configuration(same $sql_details and $collumns) it works fine. Howerever if I change the $columns(same $sql_details, but diferent $collumns), it gives me the creeping error message:

DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

I followed the advice in http://datatables.net/tn/1 but the network response didn't display the faulty json format but the message: This request has no response data available.

https://i.stack.imgur.com/fk3vo.png

I used the Data Tables debugger which returned the reference: debug.datatables.net/ujutog.

I am greatly thankful if somebody could point out an error, cause there is no response available.

I asked question in Stackoverflow, but there was "no preview answer available".
https://stackoverflow.com/questions/44849202/invalid-json-response-from-datatable-server-side
https://pt.stackoverflow.com/questions/217557/o-que-ocasiona-o-erro-de-json-inv%C3%A1lido
https://pt.stackoverflow.com/questions/216368/resposta-inv%C3%A1lida-json


Editor datetime field works for inline editing but inside modal

$
0
0

If I use the 'date' field type in dataTable.Editor, the HTML5 date picker is displayed in both the inline editor and the editor modal, but when I use the 'datetime' field type, a date picker appears only for the inline editor and not the editor modal.

http://debug.datatables.net/onemox

Restore deleted rows button?

$
0
0

Hi!
Is there any option to restore/show back deleted rows by button click without reloading page?

Here is my example:
http://live.datatables.net/buhiseti/6/

I was trying to use this code example:
https://stackoverflow.com/questions/30086341/datatable-hide-and-show-rows-based-on-a-button-click-event

for "restore deleted" button but it's not working here.

I was thinking about adding "visibility: hidden" to selected rows after "delete selected" button click
and add "toggle visibility" function to "restore deleted" button but I dont know how to connect it with "selected" rows.

Anyone can help me out?
Thanks

Cannot sort column using data-sort attribute for input tag

$
0
0

Example: http://live.datatables.net/jorotifa/4

Using a button, I create rows where I can insert data into an inline <input>. I have a helper function (updater) which enables an onblur event, to update the data-sort parameter, to enable sorting. I cannot get it to work, so I'm wondering if a custom sort function/plugin is required here?

Add a class name to editor control.

$
0
0

Hello,

I would like to add class name to my field type. For example when it comes to my "buttons" in the datatable property this works well

"buttons": [
    { extend: "create"  , editor: editor ,"className": "btn btn-primary"},
    { extend: "edit"    , editor: editor ,"className": "btn btn-info"},
    { extend: "remove"  , editor: editor }
]

I would like to achieve the same effect with my editor controls something almost similar to this.

fields: [
{
    label: "My Label:",
    name: "My Name",
    type: "select",
    options: [{ label: "home", value: 500},{label: "test2", value: 501}],
    className: "My-CSS-Class-Name",
},
]

However for some reason the CSS class name is not being effected. Anything I may be missing?

Uncaught TypeError: Cannot set property '$' of undefined

$
0
0

Hello,

I wanted to use DataTables in my wordpress theme but it doesn't work. I get the error above...

I installed DataTables with npm. My main.js looks like this:

var $ = jQuery;
var dt = require("datatables.net")();


$(document).ready(function() {
    $(".datatable").DataTable();
});
Viewing all 82400 articles
Browse latest View live


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