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

Datatables daterange filter not working with column().index()

$
0
0

Hi guys,

I'm using the daterange filter on my Datatables: https://datatables.net/plug-ins/filtering/row-based/range_dates

This works perfectly when the variables are set to numbers like in the original JS plugin.

But when I'm changing the 'var iStartDateCol' or 'var iEndDateCol' numbers to the selector $('table').DataTable().column('.filter-start-date').index() i get a Cannot set property '_DT_CellIndex' of undefined error when selecting a new date.

Am I using the wrong type of selector or am I doing something different wrong?


Select input with options provided from database

$
0
0

Hello there!
I'm creating opne PHP system, currently i'm using datatables (not the editor) to create my tables.
To add, edit and delete content, i'm using ajax request and making it "by hand". I'm testing the editor to make my development faster...
Some of my fields are <select> and his options often was retrieved from database.

This is an example of my current select:

<select id="slEstado" name="slEstado" class="form-control form-control form-control-sm input-sm selectpicker" required="" data-show-subtext="true" data-live-search="true" tabindex="-98">
<option value="">Selecione...</option><option value="AC">AC - Acre </option>
<option value="AL">AL - Alagoas </option>
<option value="AP">AP - Amapá </option>
<option value="AM">AM - Amazonas </option>
<option value="BA">BA - Bahia </option>
<option value="CE">CE - Ceará </option>
<option value="DF">DF - Distrito Federal </option>
<option value="ES">ES - Espírito Santo </option>
<option value="GO">GO - Goiás </option>
<option value="MA">MA - Maranhão </option>
<option value="MT">MT - Mato Grosso </option>
<option value="MS">MS - Mato Grosso do Sul </option>
<option value="MG">MG - Minas Gerais </option>
<option value="PA">PA - Pará </option>
<option value="PB">PB - Paraíba </option>
<option value="PR">PR - Paraná </option>
<option value="PE">PE - Pernambuco </option>
<option value="PI">PI - Piauí </option>
<option value="RJ">RJ - Rio de Janeiro </option>
<option value="RN">RN - Rio Grande do Norte </option>
<option value="RS">RS - Rio Grande do Sul </option>
<option value="RO">RO - Rondônia </option>
<option value="RR">RR - Roraima </option>
<option value="SC">SC - Santa Catarina </option>
<option value="SP">SP - São Paulo </option>
<option value="SE">SE - Sergipe </option>
<option value="TO">TO - Tocantins </option>
</select>

In datatables editor, i need to make same thing. Get the options from database and show it like that, option description with more details and the value that will be stored in DB it's the option value.

Has anyway to do it?

Datatables Editor and normal Datatables

$
0
0

Hello there!

In my current project i'm using normal datatables, to use the editor, it already has all options from normal datatables?
It's necessary to remove comum version and use only editor? Or i need to use both?

Orthogonal editor php

$
0
0

Hi there,

Is there a php function in editor to provide orthogonal data?
If not, would it be possible to provide a subarray instead of the value for a field?
Providing the different data types in php would be mich easier for me, because I have already many of the needed functions... how do you handle this „problem“?

Thx!
Bernhard

While loading page i get Uncaught TypeError: reportTable.column(...).search(...).column is not a fun

$
0
0

my code is below.

$('#ReportDetailsDiv').ready(function () {
        itemType = $('#selectedItemType').data('itemtype');
        projType = $('#selectedStoreType').data('storetype');
        month = $('#selectedMonth').data('month')
        year = $('#selectedYear').data('year');


        GetReportDetailsData(token, itemType, projType, month, year);

    })



    $('#btnReportFilter').on('click', function (e) {
        event.preventDefault();
        itemType = $('#selectedItemType').data('itemtype');
        projType = $('#selectedStoreType').data('storetype');
        month = $('#selectedMonth').data('month')
        year = $('#selectedYear').data('year');

        var colStore = $('#searchOpenItemByStoreId').attr('data-column');
        var colItem = $('#searchOpenItemByItemId').attr('data-column');

        var valStore = $('#searchOpenItemByStoreId').val().toLowerCase();
        var valItem = $('#searchOpenItemByItemId').val().toLowerCase();

        GetReportDetailsData(token, itemType, projType, month, year, colStore, valStore, colItem, valItem);

    })


    var GetReportDetailsData = function (token, itemType, projType, month, year, colStore, valStore, colItem, valItem) {

      
        $.fn.dataTable.ext.errMode = 'none';

        var ReportDetailsDivToUpdate = $('#ReportDetailsDiv');

        ReportDetailsDivToUpdate.html("");

        var table = '';
        table += '<table id="reportTable" class="table table-condensed table-bordered table-responsive table-hover dash-card-table" style="font-size:10px;">';
        table += '<thead style="font-size:10px; background-color:#495c89; color:#fff">';
        table += '<tr>';
        table += '<td>Fixture</td>';
        table += '<td>Store</td>';
        table += '<td>City</td>';
        table += '<td>State</td>';
        table += '<td>Project</td>';
        table += '<td>Coordinator</td>';
        table += '<td>Item Type</td>';
        table += '<td>Item</td>';
        table += '<td>Request Date</td>';
        table += '</tr>';
        table += '</thead>';
        table += '</table>';

        ReportDetailsDivToUpdate.html(table);


        //server side

        var reportTable = $('#reportTable').DataTable({
            "ajax": {
                url: "/myproject/Dashboard/Reports",
                headers: { "__requestverificationtoken": token },
                type: "POST",
                data: {
                    "itemType": itemType,
                    "projectType": projType,
                    "month": month,
                    "year": year
                },
                datatype: "json"
            },
            "columns": [
                    { "data": "Fixture", "name": "Fixture", "autoWidth": true, "searchable": false, },
                    { "data": "Store", "name": "Store", "autoWidth": true },
                    { "data": "City", "name": "City", "autoWidth": true, "searchable": false, },
                    { "data": "State", "name": "State", "autoWidth": true, "searchable": false, },
                    { "data": "ProjectType", "name": "ProjectType", "autoWidth": true, "searchable": false, },
                    { "data": "Coordinator", "name": "Coordinator", "autoWidth": true, "searchable": false, },
                    { "data": "ItemType", "name": "ItemType", "autoWidth": true },
                    { "data": "Item", "name": "Item", "autoWidth": true, "searchable": false, },
                    { "data": "RequestedDate", "name": "RequestedDate", "autoWidth": true, "searchable": false, }

            ],
            lengthMenu: [[200, 500, 1000], [200, 500, 1000]],
            responsive: true,
            order: [0, "asc"],
            paging: true,
            fixedHeader: true,
            autoWidth: false,
            responsive: true,
            serverSide: true,
            dom: "<'row'<'col-sm-6'l><'col-sm-3'i><'col-sm-3'p>>" +
                 "<'row'<'col-sm-12'tr>>"
        });


        $("select[name='myTable_length']").addClass('selectShowEntries');


        reportTable.column(colItem).search(valItem).column(colStore).search(valStore).draw();


    }

row.data(new_data) redraws the table, even if .draw() is not called.

$
0
0

Hi,

in the docs for row.data() it states that

Note that when used as a setter, this method sets the data to apply to the table, but does not update the table's internal caches of data until the draw() method is called.

This is exactly what I wish to achieve since I would like to collect changes and then update everything together for better performance. But setting new data, seems to trigger a drawing as demonstrated here: https://jsfiddle.net/5tsu07yf/16/ (a klick on Update).

Thank you!

Serverside data and filtering from external control

$
0
0

Hi
I have a Datatable with bServerSide:true and its corresponding sAjaxSource set. I've also enabled ordering in some columns and search. My question is:

Would it be possible to add a <select> with some static options and trigger on select.change a filtering and make this Datatable to filter the data by the option selected in this external select ?

If so, how should I change the code (corresponding to the ajax url) that gets the data and outputs the json?
Please lemme know if you'd need the serverside code

Thanks a lot in advance

hello members how can i add values in row one and put its total in actual column thanks


Select which columns will be marked as Child rows (show extra / detailed information)

$
0
0

I have a datatable with a couple of columns like "comments" and extra details that will probably contain a lot of text. I would like to choose which columns will be visible by default and mark the ones that will contain a lot of text as extra information so that they will not visible when the datatable loads at first but will be visible once the user clicks on the + button to show the extra columns.

Here is screenshot of the issue I'm having at the moment.

Caption displaying below table, why?

$
0
0

Has anyone experienced their table caption appearing below the table? I can't seem to figure out how to get it on top. I am using a straightforward datatable initialization (nothing out of the ordinary).

<table cellpadding="0" cellspacing="0" class="dataTable table table-striped compact" style="width:100%" id="deliveries-table">
     <caption class="lead">Deliveries</caption>
</table>
var deliveriesTable = $("#deliveries-table").DataTable({....});

Datatables Editor: CSRF protection with regenerating CSRF Tokens and HTTP Only cookies possible?

$
0
0

We have a security audit for a web application that uses Datatables Editor.

The requirements are:
* provide CSRF protection using tokens as usual
* generate new CSRF Token for every response/request pair
* use HTTP Only cookies

All these are just config settings in the php framework we use (codeigniter).

https://editor.datatables.net/manual/security says to use:

new $.fn.dataTable.Editor( {
    ajax: {
        url: '...',
        data: function ( d ) { d.CSRFToken = TOKEN; }
    }
} );

The "TOKEN" would need to change with every request.
After the page using datatables editor gets loaded there can be any number of editor post requests on the same page. So the TOKEN cannot be "hardcode".
I guess usually I would use javascript to read the csrf cookie and set the TOKEN accordingly? However since for security reasons we are asked to use the HttpOnly flag on cookies we cant read them from javascript.

Is this scenario supported by datatables editor ? Any hints appreciated!

Thanks!

Ajax Reload keep the Child rows open but also writes data to another child,

$
0
0

I somehow managed to make it working, but now i have a situation where i had opened two parents and adding the data in one parent and reloading, it shows in both now even after refresh it shows it been added in one, how can i fix that

$('body').on('click', '#add', function() {
 var id= $("#id").val();
$.ajax({url:page.cfm',type:post,data : {id: id},async:false,datatype:'json',success: function(data) {
if (data.status == 1) {
                            swal('', data.statusmsg, 'success');
                            table.ajax.reload(function () {
                            //Iterate through all the open rows and open them again 
                            table.rows(rowIds).every(function (row, index, array) {
                                table.row(row).child(Format(ID)).show(); - ID coming from post call
                                this.nodes().to$().children('td:first').html('<i class="fa fa-minus-square text-danger fa-2x" aria-hidden="true"></i>');
                            });
                            //Set to false if you don't want the paging to reset after ajax load,otherwise true
                        }, false);

}
});
});

now after the success call, the format Function will be called as many times as the parent row is opened and redrawn, but it is always sending the same ID

how can fix it

If you reload the page is it ok? - YES

When you say you have 2 parents you mean 2 different rows? - YES

The Issue is happening on table redraw of Datatables

how to update datatables ajax params, when i click save in the browser.

$
0
0

hello everyone! i'm trying to update the one row with button save, but i get no parameters when i click save button!
please if u have any idea help me!

function loadTable() {
$.ajax({
url: "/rest/Inventory/List",
method: "GET",
dataType: "json",
cache: false,
success: function (r) {
var data = r.items,
persons = r.persons,
types = r.types,
locations = r.locations,
dataSet = [];

        for ( var i = 0; i < data.length; i++) {

            var typeOptions = "<option value=\"0\">No type</option>";
            var personOptions = "<option value=\"0\">No Person</option>";
            var locationOptions ="<option value=\"0\">No Location</option>";
            if (data[i].type == undefined)
            var type_name = ''
            else {
                var type_name = data[i].type.name;
            }
            if (data[i].location == undefined)
            var location_name = ''
            else {
                var location_name = data[i].location.name;
            }

            for (var t = 0; t < types.length; t++){
                if (data[i].type != undefined && types[t].id === data[i].type.id){
                    typeOptions += "<option selected=\"selected\" value=\"" + types[t].id + "\">" + types[t].name + "</option>";
                    } else {
                    typeOptions +=  "<option value=\"" + types[t].id + "\">" + types[t].name + "</option>";
                }
            }

            for(var a = 0; a < persons.length; a++) {
                if (data[i].person != undefined && persons[a].id === data[i].person.id) {
                    personOptions += "<option selected=\"selected\" value=\"" + persons[a].id + "\">" + persons[a].name + "</option>";
                    } else {
                    personOptions += "<option value=\"" + persons[a].id + "\">" + persons[a].name + "</option>";
                }
            }

            for(var l = 0; l < locations.length; l++) {
                if (data[i].location != undefined && locations[l].id === data[i].location.id) {
                    locationOptions += "<option selected=\"selected\" value=\"" + locations[l].id + "\">" + locations[l].name + "</option>";
                    } else {
                    locationOptions += "<option value=\"" + locations[l].id + "\">" + locations[l].name + "</option>";
                }
            }

            dataSet.push([
                data[i].id,
                "<input value=\"" + data[i].device + "\"></input>",
                "<select>" + typeOptions + "</select>",
                "<input value=\"" + data[i].additionalInfo + "\"></input>",
                "<input value=\"" + data[i].serialNumber + "\"></input>",
                "<select>" + personOptions + "</select>",
                "<select>" + locationOptions + "</select>",
                "<button class='save'>Save</button><button class='delete'>Delete</button>"
            ]);
        }   
        $('#data-table').DataTable({
            data: dataSet,
            columns: [
                { title: "Id" },
                { title: "Device" },
                { title: "Type"},
                { title: "Additional Info" },
                { title: "Serial Number" },
                { title: "Person" },
                { title: "Location" },
                { title: "Actions" }
            ],
            "rowCallback": function (row, data) {
                $(row).find("button.save").off("click").on("click", function () {
                    save_row(data[0]);
                    console.log(data)
                });
                $(row).find("button.delete").off("click").on("click", function () {
                    delete_row(data[0]);
                });
            }
        });
    },
    statusCode: {
        401: function (){
            window.location.href = "login.php";
        }
    }
});

}

function save_row(id){
$.ajax({
type: 'PUT',
url: '/rest/Inventory/updateItem/'+ id,
data: {data: "", id: "", device: "", type: "", additionalInfo: "", serialNumber: "", person: "", location: ""},
dataType: 'json',
success: function (r){

        if (r == "success"){
            alert("data are updated!");
        }
    }
});

}

Alphabet input search - stateSave

$
0
0

I implemented Alphabet input search plugin from the blogs
https://datatables.net/blog/2014-09-22

But can't figure how to modify it so it can store the search in savestate.
My table has stateSave on and it saves items in the search and pagination information but it will not store th letter clicked on. Any ideas how to make that work?

Editor changing array/object format on a dynamic table

$
0
0

Hi

I have a datasource which has an array as part of the data source.

An example of the JSON is:

{
    "data": [
        {
            "DT_RowId": 0,
            "PackageType": 1,
            "SalesPrice": "250",
            "Suppliers": [
                "Supplier 1",
                "Supplier 2"
            ],
            "Tariffs": [
                "1",
                "3"
            ],
            "CostPrices": [160,0],
            "IDs": [146,110]
        }
    ]
}

I am using the following script to add the columns and fields to the datatable/editor

    function constructTable(json,extraColumnsRequired) {
        
        //columns for DataTables
        var columns = [];

        columns[0] =    {targets: [0], data: "PackageType"};  
        columns[1] =    {targets: [8], data: "SalesPrice"};            
             
        $("#table").find('thead tr').html(     "<th>Package Type</th>"+
                                                    "<th>Std SP</th>");

        var columnIndex = 2;
        
        for (i = 0; i < extraColumnsRequired; i++) {
            columnIndex++
            columns[columnIndex] = {targets: [columnIndex], data: "CostPrices."+i, editField: "CostPrices."+i,
                                        render: function(data, type, row) {
                                            return displayAsMoney(parseInt(data)/100);
                                        }
                                    };
                $("#andysTable").find('thead tr').append(
                    "<th>"+json.data[0].Suppliers[i]+"<br/>"+json.data[0].Tariffs[i]+"</th>"
                );
        }

        for (i = 0; i < extraColumnsRequired; i++) {
            columnIndex++
            columns[columnIndex] = {targets: [columnIndex], data: "IDs."+i, "visible": false, "searchable": true};
                $("#andysTable").find('thead tr').append(
                    "<th>ID."+i+"</th>"
                );
        }
    
        //fields for Editor
        var fields = [];
        
        fields[0] =
            {
                label: "SalesPrice",
                name: "SalesPrice"
            };

        var fieldIndex = 0;

        for (i = 0; i < extraColumnsRequired; i++) {
            fieldIndex++

            fields[fieldIndex] =
                {
                    label: "CostPrices."+i,
                    name: "CostPrices."+i
                };
        }
    
        return [columns, fields];
    }

The table displays correctly.

However when I edit I am getting a few errors. The first is that sometimes the editor (I tried both popup and inline) does not know what column it is in and I get an error to define column names.

The second issue (and more important to me) is that on submit it changes the costPrices array to:

"CostPrices": ["0":160, "1":0],

I am not sure what I am doing wrong.

Any help would be very appreciated.

Thanks

Dov


Trouble with PHP and Editor w/ 500 errors + cannot manipulate object

$
0
0

I would like to manipulate and alter the data being sent through Editor on the server-side. It appears this might be possible through something like within the initialization of Editor like so:
->on( 'preCreate', function ( $e, $id, $values, $row ) {
echo 1;
error_log("Test");
})

The ajax php examples provided are very strange. Anytime I attempt to print to a debug output, 500 errors are being thrown without any error messages. Even just trying to work anywhere in the php Editor/ajax file causes 500 errors to be thrown.

What I would really like to understand is where the actual entry point is to work with the data and have access to my other PHP libraries I have built.

I may just be getting confused by the shorthand being used by the code that I am finding quite troubling to use. I'm really not sure and help would be appreciated. I can provide more information as we go along. Below is the ajax php request that both the DataTable and Editor are using ajax for. Without any ->on code, it works and writes back as expected. My actual code has multiple leftjoins that do not write back correctly despite being built as the documentation describes.

I'd really appreciate getting to the point I can use other code to manipulate this object. If I can get that far I can probably figure out what I need to do from there.

<?php

/*
 * Example PHP implementation used for the index.html example
 */
 
require_once($_SERVER['DOCUMENT_ROOT'] .'path/to/file/Id/like/to/include');//This file has static methods I'd like to use.  Any calls to them just fail.
 
// DataTables PHP library
include( $_SERVER['DOCUMENT_ROOT']. '/php/DataTables.php' );
//At this point any echo/system log print for $_POST['action'] just to even check the action causes 500 error


// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Options,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;

    
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'table' )
    ->fields(
        Field::inst( 'table.id' ),
        Field::inst( 'table.first_name' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'table.last_name' )->validator( 'Validate::notEmpty' )
    )
        ->on( 'preCreate', function ( $e, $id, $values, $row ) {
        echo 1;
        error_log("Test");//etc..Doing anything besides what this example initially did just throws 500 errors constantly
        })
    ->process( $_POST )
    ->json();

Sorting Numeric String with $, comma and dot

$
0
0

i have a string column with dollar sign($) separated with commas and have dot for decimal numbers. Currently am using datatable V 1.8. but the sorting is working as string even after i have used formatted-num plugin.
$100.00
$124.00
$2,345.00
$2.51
$230.00
$250.00
This is how it is sorting now.
Below is the code i am using in my javascript.
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"formatted-num-pre": function ( a ) {
a = (a === "-" || a === "") ? 0 : a.replace( /[^\d-.]/g, "" );
return parseFloat( a );
},

"formatted-num-asc": function ( a, b ) {
    return a - b;
},

"formatted-num-desc": function ( a, b ) {
    return b - a;
}

} );

searchResuluts= $("#summarResult").dataTable({
aoColumnDefs : [
{"sType" : "formatted-num", "aTargets": [5] }
]
)};
Could you please help me on how i can get sorted order in a proper way.Your help is really appriciated. Thank you.

custom button and exportOptions

$
0
0

how can i use exportOptions with custom button?

Property Pane type of DataTable + Editor

$
0
0

Hi

Using Visual Studio, Android Studio, Eclipse etc there is usually some kind of property window with two columns.

The left column has a name and the right column has a value.

The value can be either of:
TextField with different validation rules
Dropdown
ON/OFF slider

Can this type of table be done with DataTables and DataTables.Editor easily or is it not fit for purpose?

I love the layout of the DataTable but I understand that there will not be a single line a like in this scenario, is it suitable for this?

Kind regards
Jens

Create multiple rows with multiSet().

$
0
0

Hi !
I've got a question about editor.multiset() - see the code below.

function impNmapDataMultiSet (dataNmap, j) {
        customElement.text(j + "/" + dataNmap.length);
        tableCust=   $('#customer').DataTable();

        editorNessus.create(dataNmap.length, false)
            .multiSet('ip', dataNmap[j]['ip'])
            .multiSet('mac', dataNmap[j]['mac'])
            .multiSet('netbiosname', dataNmap[j]['netbiosname'])
            .multiSet('os', dataNmap[j]['os'])
            .multiSet('start', dataNmap[j]['start'])
            .multiSet('stop', dataNmap[j]['stop'])
            .multiSet('plugin_id', dataNmap[j]['plugin_id'])
            .multiSet('plugin_name', dataNmap[j]['plugin_name'])
            .multiSet('port', dataNmap[j]['port'])
            .multiSet('protocol', dataNmap[j]['protocol'])
            .multiSet('cve', dataNmap[j]['cve'])
            .multiSet('cvss_base_score', dataNmap[j]['cvss_base_score'])
            .multiSet('service_name', dataNmap[j]['service_name'])
            .multiSet('description', dataNmap[j]['description'])
            .multiSet('solution', dataNmap[j]['solution'])
            .multiSet('kundenr', dataNmap[j]['kundenr']);
        
                console.log(dataNmap[j]);
                j++;
                if (j < dataNmap.length) {
                    setTimeout(function () {
                        impNmapDataMultiSet(dataNmap, j);
                    }, 100);
                }
                else {
                    editorNessus.submit();
                    $('#nmapTable').busyLoad("hide");
                    $.busyLoadFull("hide");
                }
        tableCust.draw();
    }  

I'm trying to use multiSet() to create several rows imported from a file. The code above works, but it creates the same data for all the rows.. I've read some other posts which says that I need to have the Count of rows to create, as I've done with the lenght of my array (dataNmap.lenght), in my create method (editorNessus.create(dataNmap.length, false)).

What am I missing?

Have a great day!

Viewing all 82536 articles
Browse latest View live


Latest Images

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