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

Hello Team

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:


new orthogonal data - export

$
0
0

sometimes, data displayed on screen is not suitable for export. e.g. we have a table where some of the columns display as check-boxes indicating true/false or yes/no. when I export to csv, pdf etc I get nothing, but with an export orthogonal data option e.g.

<TD data-export="Yes">

I would get something sensible in my export.

Or perhaps even to prevent something being exported that shouldn't -

<TD data-export="Not appropriate for export">

You might even want to make it specific to the export type and have

data-export-copy
data-export-csv
data-export-pdf
data-export-excel
data-export-print

with data-export as one that covers all options

thanks for a great utility!

Dynamically populate dropdown list with default value

$
0
0

Hi @allan,

We currently have a large dataset which is filtered by a user's input from a drop down selection on the front end.  To prevent all the data from loading, on first load, the controller is leveraging the default selection that has been manually set in the .CSHTML file.  

The question is, rather than manually typing the contents of the dropdown list, how would we go about dynamically generating the values of the dropdown list based on the data in the table.  And along with this, how do we have the select list automatically default the value in this list to the max value of the list so the initial load of the table is filtered to the max value of this field rather than displaying all of the data?

I have found some sources from datatables about creating column dropdown filter, but that doesn't seem to apply for our case since it would force us to load all the data to generate that dropdown list, which is exactly what we're trying to avoid.

Controller:

public class TestController : ControllerBase
   [HttpGet]
   [HttpPost]
   public ActionResult Test()
   {
           // Minimized code for simplicity

            using (var db = new Database("sqlserver", cnStr))
            {
                var response = new Editor(db, "Test", "id")
                    .Model<TestModel>("Test")
                    .Where(q =>
                    {
                        q.Where(r =>
                        {
                            r.Where("Year", Request.Form["year"], "=");  // filter user's input from dropdown built on front end
                        }
                    });

                return new JsonResult(response);
            }
        }

JS:

var table = $('#Test').DataTable({
       ajax: {
            'url': '/api/Test',
        "type": 'POST',
        "data": function (d) {
        d.year = $('#year').val();
    }

// Minimized code for simplicity
},

// Reload table based on dropdown selection
$('#year').on('change', function () {
    table.ajax.reload();
});

CSHTML (option values are now manually entered and defaulted to max year. We want to dynamically populate it):

<select class="form-select form-select-sm" id="year">
            <option value=2022 selected>2022</option>
            <option value=2021>2021</option>
</select>

Any thoughts on how to tackle this would be highly appreciated.
Thank you

Basic Flask implementation is not working

$
0
0

Hello all.

I am trying to get Editor working in a Python Flask environment.
I am currently using the following technologies:
Postgres as well as PHP for the database connections.
Python and Flask

Description of problem:
whenever I submit a new record, the returned values will not return what I typed. Instead, my table will just duplicate existing values. What is more, the POST call does not persist to the DB, because when I refresh the page, all the values are reset.

BEFORE SCREENSHOT:

MIDDLE SCREENSHOT:

AFTER SCREENSHOT:

The problem seems to be occurring when I perform a POST operation, because the tables perform the GET functionality fine.

application.py file:

@application.route('/emp_php', methods=["POST", "GET"])
def emp_php():
    out = sp.run(["php", "static/emp.php"], stdout=sp.PIPE)
    return out.stdout

HTML

{% extends 'tables.html' %}

{% block table_name %}
<head>
    <script type="text/javascript">

/*
 * Editor client script for DB table emp
 * Created by http://editor.datatables.net/generator
 */

(function($){

$(document).ready(function() {
    var editor = new $.fn.dataTable.Editor( {
        ajax: '/emp_php',
        table: '#emp',
        fields: [
            {
                "label": "fname:",
                "name": "fname"
            }
        ]
    } );

    var table = $('#emp').DataTable( {
        dom: 'Bfrtip',
        ajax: '/emp_php',
        columns: [
            {
                "data": "fname"
            }
        ],
        select: true,
        lengthChange: false,
        buttons: [
            { extend: 'create', editor: editor },
            { extend: 'edit',   editor: editor },
            { extend: 'remove', editor: editor }
        ]
    } );
} );

}(jQuery));

    </script>
</head>
<table id='emp' class='table table-hover' style="width:100%">
    <thead>
    <tr>
        <th>fname</th>
    </tr>
    </thead>
        <tfoot>
    <tr>
        <th>fname</th>
    </tr>
    </tfoot>
</table>
{% endblock %}

emp.php

<?php

/*
 * Editor server script for DB table emp
 * Created by http://editor.datatables.net/generator
 */

// DataTables PHP library and database connection
include( "Editor-PHP/lib/DataTables.php" );

// 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,
    DataTables\Editor\ValidateOptions;

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'emp', 'id' )
    ->fields(
        Field::inst( 'fname' )
    )
    ->process( $_POST )
    ->json();

Nested Data table with Sorting feature without Onclick

$
0
0

Link to test case: https://jsfiddle.net/jordan_josh3184/nrb5h2d3/66/
Description of problem:
I am trying to create Data table inside data table usign jquery. I have achieved creating it with html so far but I want Column sort which isnt possible with my code. Can any one please Guide me how Can I have Data Table inside Data table with Sorting Feature. I have attached Screen Shot for possible Out Come. Where the table in last column should be with Sorting.

I am providing link with Jsfiddle. Some sort of direction would be good. In current implementation I have create nested table with below code which dont give me sorting from Jquery Data table.

function createDataTable() {
    var tableHeader = '<thead class="thead-light"><tr><th>Age</th><th>Location</th><th>nationality</th></tr></thead>';
    var tableRows = '';
        var tableRow = '';
        var firstTd = '<td>32</td>';
        var secondTd = '<td>USA</td>';
        var thirdTd = '<td>American</td>';
  
  
        tableRow = '<tr id="1" name="1">'+tableRow+firstTd+secondTd+thirdTd+fourthTd+'</tr>';
        tableRows = tableRows+tableRow; 
  
  
        var tableRow = '';
        var firstTd = '<td>33</td>';
        var secondTd = '<td>UK</td>';
        var thirdTd = '<td>British</td>';
        tableRow = '<tr id="2" name="2">'+tableRow+firstTd+secondTd+thirdTd+fourthTd+'</tr>';
        tableRows = tableRows+tableRow;   
        return '<table class="table table-bordered" id="1" name="1">'+tableHeader+'<tbody>'+tableRows+'</tbody>'+'</table>';
}

Table from Above function I am assigning to last column of data table.
dtRow[8] = createDataTable();

current Implementation Give out out like below. I need sorting on all Column of Child table.

Please Guide me how can i achieve Sorting on Nested Data table for last row.

Json Error

$
0
0

I got this error now, I can't figure it out but last time it is ok
error: "DataTables warning: table id=example1 - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"

I have this error getting data from editor edit in mvc c # controller

$
0
0

Método no encontrado: 'System.String[] System.String.Split(Char, System.StringSplitOptions)'

[HttpPost]
public ActionResult ClientesNuevos()
{
var settings = Properties.Settings.Default;
using (var db = new Database(settings.DbType, settings.DbConnection))
{
var request = System.Web.HttpContext.Current.Request;

            //var response = new Editor(db, "Com.Usuarios")
            //.Model<ClienteNuevo>()
            //.Field(new Field("Id"))
            //.Field(new Field("Nombre"))
            //.Field(new Field("Paterno"))
            ////.ReadTable()
            //.Process(request)
            //.Data();

            DtResponse response = new Editor(db, "Com.Usuarios")
            .Model<ClienteNuevo>()
            .Process(Request.Form)
            .Data();

            return Json(response);

            //    DtResponse dtResponse = Editor.
          //  return Json(response);
        }




 //       return new JsonResult() { Data = "", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

On Creating Dynamic columns from server and respective data for those columns. But getting error

$
0
0

Referred this link - http://live.datatables.net/qimukefe/1/edit

Error - invalid JSON primitive: draw at Deserialize Primitive Object()

Description - We have different reports - selecting a report name and submitting it - I am getting Data -column names and data

Code
var columnsss =[]; ObjData["Facility_ID"] = $('#Facility_ID').val(); ObjData["Report_Type_Name"] = $("#Report_Type option:selected").text(); ObjData["IsGetReport"] = true;


Editor modal is not closing regardless of where I click. Bootstrap 5

$
0
0

Hello,

I am using Bootstrap 5 and when I open an editor modal it will not close regardless of where I click. I have tried

  • clicking off the modal
  • clicking the close icon
  • clicking the button

None of these clicks close the modal. I saw another post where someone was having the same issue with jQueryUI and it needed corrections in the downloaded files.

Please advise.

Error on creating Dynamically Datatable columns and data

$
0
0

Referred this link - http://live.datatables.net/qimukefe/1/edit

Error - invalid JSON primitive: draw at Deserialize Primitive Object()

Description - We have different reports - selecting a report name and submitting it - I am getting Data -column names and data

Please advice
Code
var columnsss =[];
ObjData["Facility_ID"] = $('#Facility_ID').val();
ObjData["Report_Type_Name"] = $("#Report_Type option:selected").text();
ObjData["IsGetReport"] = true;

var dataProp = { model: ObjData };
$.ajax({
type: "POST",
url: '../GenericReport/_AjaxGenericReport',
data: JSON.stringify(dataProp),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (condition) {
$('#DivtableData').show();
var data = eval(result.data);
for (var i in data[0][0]) {
columnsss.push({
data: i,
title: capitalizeFirstLetter(i)
});
}
$('#btnSubmit').prop('disabled', false);
$('.table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '../GenericReport/_AjaxGenericReport',
type: 'POST',
contentType: "application/json; charset=utf-8"
},
columnDefs: [],
columns: columnsss,
'rowCallback': function (row, data, dataIndex) {

}
});
};
});
function capitalizeFirstLetter(string) {
return string.toString().charAt(0).toUpperCase() + string.slice(1) ;
}

this is controller side
[HttpPost]
public JsonResult _AjaxGenericReport(GenericReportViewModel model)
{
try
{
model.USER_NAME = UserData.username.Trim();
model = _genericReportService.GenericReportSVC(model);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(model.Data);
return Json(
new
{
data = JSONString
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//return Json(new { Success = false, Message = ex.Message },JsonRequestBehavior.AllowGet);
}
}

row group - deactivate specific row

$
0
0

HI, I have this datatable:

$(document).ready(function() {
    $.fn.dataTable.moment( 'DD.MM.YYYY' );
    var collapsedGroups = {};
    var top = '';
    var parent = '';

    var table = $('#table_orders').DataTable({
        dom: "<'toolbarfreig'>Bfrtip",
        ajax: "../../../../../../../DataTables/Editor/controllers/XXX.php",
        columns: [
            { data: "GLT_GLREIHENFOLGE"},
            { data: "Eb1", title: "Ebene 1" },
            { data: "Eb2", title: "Ebene 2" },
            { data: "Eb3", title: "Ebene 3" },
            { data: "Eb4", title: "Ebene 4" },
            { data: "Eb5", title: "Ebene 5" },
            { data: "Eb6", title: "Ebene 6" },
            { data: "SAD_KONTONR", title: "KtoNr" }, //7
            { data: "KTO_KONTOBEZ", title: "KtoBez" },
            { data: "SAD_Saldo" , title:"Betrag",  render: $.fn.dataTable.render.number( '.', ',', 2, '' ),  className: 'dt-body-right' },
            { data: "VJ_saldo" , title:"Betrag Vorjahr",  render: $.fn.dataTable.render.number( '.', ',', 2, '' ),  className: 'dt-body-right' },
            { data: "diff_j_vj" , title:"Differenz",  render: $.fn.dataTable.render.number( '.', ',', 2, '' ),  className: 'dt-body-right' }, //11
     ],
        columnDefs:[
            { type: "num", targets: 0 },
            {targets: [ 0, 1, 2,3,4,5,6,7,8,9,10,11], orderable: false },
            {targets: [0, 1, 2, 3, 4 ,5 ,6 ], visible: false},
    ],
        order: [[0, 'asc']],
        orderable: false,
        stripeClasses: [],
        paging: false,
        select: true,
        "info": "",
        buttons: [
            {extend: 'copy', text: 'kopieren Zwischenablage',},
            {extend: 'csv', text: 'download als csv',}
            ],

        rowGroup: {
            dataSrc: ["Eb1", "Eb2", "Eb3" ],
            startRender: function(rows, group, level) {
                var api = $('#table_orders').DataTable();
              if (level === 0) {
                    top = group;
                    all = group;
                } else if (level == 1) {
                    parent = top + group;
                    all = parent;
// if parent collapsed, nothing to do
                  //  if (collapsedGroups[top]) {return;}
                } else {

// if parent collapsed, nothing to do
                    if (collapsedGroups[parent]) {return;}

                    all = top + parent + group;
                }
                var collapsed = collapsedGroups[all];
                console.log(group, collapsed);

                rows.nodes().each(function(r) {
                    r.style.display = collapsed ? 'none' : '';
                });


                var intVal = function ( i ) {
                    return typeof i === 'string' ?
                            i.replace(/[\$,]/g, '') * 1 :
                            typeof i === 'number' ?
                                    i : 0;
                };

                sum_j = rows.data().pluck("SAD_Saldo").toArray().reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
                sum_j = Intl.NumberFormat('de-DE').format(sum_j);

                sum_vj = rows.data().pluck("VJ_saldo").toArray().reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
                sum_vj = Intl.NumberFormat('de-DE', { maximumFractionDigits: 0}).format(sum_vj);

                sum_diff = rows.data().pluck("diff_j_vj").toArray().reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
                sum_diff = Intl.NumberFormat('de-DE').format(sum_diff);


                return $('<tr/>')
                        .append('<td colspan=2>' + group + '</td><td style="text-align: right">' + sum_j +'</td><td style="text-align: right">' + sum_vj +'</td><td style="text-align: right">' + sum_diff +'</td>')
                        .attr('data-name', all)
                        .toggleClass('collapsed', level === 0 ? false : collapsed);
            }
        },
        initComplete: function () {
            var api = this.api();

            var dataSrc = api.rowGroup().dataSrc();
            console.log(dataSrc);
            api.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
                var data = this.data();

                var key = '';

                for (i=0; i<dataSrc.length; i++) {
                    key += data[dataSrc[i]];
                    collapsedGroups[key] = true;
                }
            } );
            console.log(collapsedGroups);
            api.draw();
        },
    });

    $('#table_orders tbody').on('click', 'tr.dtrg-start', function() {
        var name = $(this).data('name');
        collapsedGroups[name] = !collapsedGroups[name];
        table.draw(false);
    });
});

This always shows Eb1+Eb2 at the beginning, works fine so far. But if GLT_GLREIHENFOLGE == 9999 I would like NOT to show Eb2 as start and also deactivate clicking Eb1, so Eb2 (and the others) never get shown.

Thanks
Max

vue3 serverside

$
0
0

HI can I ask, is it possible to use serverside in vue3 datatables ?, I didn't see an example of how to use it, can you please send me a link on how to use serveride.

I add serverside:true but it did not work

const options = {

  lengthMenu: [ [2, 25, 50, -1], [2, 25, 50, "All"] ],
  serverSide:true
};

Thank you in advance.

Clear search input after hiding column

$
0
0

Hello,

I use extension ColVis and "column search" functionnality on specific column (a classic input text in header).
All columns could be hidden by a dropdown.

My goal : I want to clear the input of a column hidden by user

Example :
Typing "test" in column C : Data filtered with "test" OK
Typing "hello" in column F : Data filtered with "test" AND "hello" OK
Hide column C : Data always filtered with "test" AND "hello" : KO

I make a clear in drawCallback, but it doesn't work

    $('#dataList').on( 'column-visibility.dt', function ( e, settings, column, state ) {
        //Trigger draw event when a column is hidden/displayed
        $($.fn.dataTable.tables(true)).DataTable().rows().invalidate().draw();
        $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
    } );
$.extend( true, $.fn.dataTable.defaults, {
    "search": true,
    "searching": true,
    "stateSave": true,
    drawCallback: function(){
        var table = this.api();
        var container = table.table().container();
        //Loop on each thead tr
        $( container ).find("thead tr").each( function () {
            //Loop on each column of headers
            $('th', this).each( function (i) {
                //If column is hidden, we clear the input filter
                if(table.column(i).visible() === false){
                    table.column(i).search( null ).draw();
                }
                //On each input, if user type something, we get the value and trigger the search() method
                $( 'input', this ).off().on( 'change', function () {
                    var value = this.value;
                    if ( table.column(i).visible() === true && table.column(i).search() !== value) {
                        table.column(i).search( value ).draw();
                    }
                } );
            })
        });
    }
} );

It's a datatable ajax sourced. When i debug the object sent to the server, i see every column with the property "value" filled, in despite of the visibility.

Thanks for your help

Can Datatable Customize Export Column?

$
0
0

Can we add new column into the export page? This is because I have few many columns came with combined data e.g:
My columns header:

<th>Name /<br />Age</th>

This is how my columnDefs looks like:

columnDefs:[{
        targets: 0,
        "render": function(data, type, full, meta) {
                 return full.Name + "<br/>" + full.Age;
         }
}]

And I want them to be in separated columns when come to export. How can I achieve it? I can't use hidden columns to decide which to show because they are too many columns. Thank in Advance!

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

$
0
0

I want to dynamically change column visible based on a variable. For this I run the code after the ajax request is successful and it works. But I am also getting the following error.

if (!userObj.IsManagment) {
s.columns(4).visible(false);
}

Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at db (datatables.min.js:89:39)
at sa (datatables.min.js:41:375)
at B.<anonymous> (datatables.min.js:163:438)
at B.iterator (datatables.min.js:134:423)
at B.<anonymous> (datatables.min.js:163:409)
at Function.adjust (datatables.min.js:137:349)
at B.<anonymous> (datatables.min.js:163:208)
at B.iterator (datatables.min.js:134:423)
at B.<anonymous> (datatables.min.js:162:483)
at B.visible (datatables.min.js:137:349)


Disable the highlighting when selecting rows by checkboxes

$
0
0

Hello, is there a way to disable the highlighting when selecting rows by checkboxes?

The message: “Your trial has now expired"

$
0
0

Hi.
We have purchased a license for a DataTables Editor, but when we run the Editor from within a *.war file we receive an alert. In the war-file the Editor is embedded as the source of an iframe, located at an outer Apache2 web server. The browser’s cache is cleaned.
The Editor still does its job, but we want to remove the alert. The message: “Thank you for trying DataTables Editor. Your trial has now expired. To purchase a license for Editor, please see https://editor.datatables.net/purchase”.
Thank you for your former replies, hope you to answer.
Best regards

Show Entries

$
0
0

Hello could you tell me where to find the CDN's to customize the show entries option? I was looking to do something like this

$('#example').DataTable( {
"lengthMenu": [ 25, 50, 75, "All" ]
});

Unable to get uploadMany work

$
0
0

Hello!
I'm trying to upload many documents following the example in editor, but I guess I'm having the error while joining the two tables.

Editor::inst( $db, 'staff' )
    ->fields(
        Field::inst( 'name' ),
        Field::inst( 'position' ),
        Field::inst( 'office' ),
        Field::inst( 'ext' ),
        Field::inst( 'salary' )
            ->validator( Validate::numeric() )
            ->setFormatter( Format::ifEmpty(null) ),
        Field::inst( 'start_date' )
            ->validator( Validate::dateFormat( 'Y-m-d' ) )
            ->getFormatter( Format::dateSqlToFormat( 'Y-m-d' ) )
            ->setFormatter( Format::dateFormatToSql('Y-m-d' ) )
    )    
            ->join(
                Mjoin::inst( 'files' )
                    ->link( 'staff.id', 'files.id' )
                    ->link( 'files.id', 'staff.id' )
                    ->fields(
                        Field::inst( 'id' )
                            ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/uploads/__ID__.__EXTN__' )
                                ->db( 'files', 'id', array(
                                    'filename'    => Upload::DB_FILE_NAME,
                                    'filesize'    => Upload::DB_FILE_SIZE,
                                    'web_path'    => Upload::DB_WEB_PATH,
                                    'system_path' => Upload::DB_SYSTEM_PATH
                                ) )
                                ->validator( Validate::fileSize( 500000, 'Files must be smaller that 500K' ) )
                                ->validator( Validate::fileExtensions( array( 'png', 'jpg', 'jpeg', 'gif' , 'pdf' ), "Please upload a file" ) )
                            )
                    )
            )
->process( $_POST )
->json();

These are the tables I'm using

CREATE TABLE files (
id int(11) NOT NULL,
filename varchar(200),
filesize int(4) UNSIGNED,
web_path varchar(100),
system_path varchar(200),
PRIMARY KEY (id)
)

CREATE TABLE staff (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100),
position varchar(100),
office varchar(100),
ext int(2) UNSIGNED,
start_date date,
salary int(4) UNSIGNED,
files varchar(100),
PRIMARY KEY (id)
)

sAjaxSource URL too long

$
0
0

Hi, I'm currently working on a Django project which makes use of a server-side data table. Just to give a background on how the tool works, before generating the data table and its contents, users are given the option to select columns which would be included in the data table. So far this is working if the user selects < = 18 columns but if they select more than that, I get the 404-error message. Indicated below is a part of my code for the data table and I saw that by changing the method to post, it should work but I'm not really sure how to apply it in this setup. When I tried changing sAjaxSource to ajax: url... type..., I got a different error message related to iDisplayStart. I was hoping someone could give me any insights on how to resolve this and I was also wondering if it's possible to remove some of the parameters automatically included in the url. Also, here's a link to the package I used for the server-side table just in case it may be related to the problem: https://pypi.org/project/django-serverside-datatable/

       var table = $('#table').DataTable( {
            scrollX: true,
            scrollY: "500px",
            lengthChange: false,
            pageLength:5000, 
            buttons: [ 'excel' ],
            serverSide: true,
            sAjaxSource: "http://IP/sctagging/materialtaggingdata/",  
            columns: columndata,
       })
Viewing all 82321 articles
Browse latest View live


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