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

where condtition with arrays - serverside

$
0
0

Hi!

I've got the following code.

include(dirname(__FILE__)."/../Editor-PHP-1.9.2/lib/DataTables.php");

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

$my_id=$_POST['my_id'];
$timepoolid=$_POST['timepool_id'];

//$yourQueryArray = join(',',$timepoolid);
// Build our Editor instance and process the data coming from _POST
$editor = Editor::inst($db, 'crapper_vulnerability', 'crapper_vulnerability.id')
//    ->order('ip')

    ->fields(

        Field::inst('crapper_vulnerability.outputtool'),
        Field::inst('crapper_vulnerability.testtypeid'),
        Field::inst( 'crapper_vulnerability.toolid' ),
        Field::inst( 'crapper_vulnerability.scanid' ),
        Field::inst( 'crapper_vulnerability.fp' )
            ->setFormatter( function ( $val, $data, $opts ) {
                return ! $val ? 0 : 1;
            } ),
        Field::inst( 'crapper_vulnerability.cvss_temp' ),
        Field::inst( 'crapper_vulnerability.cvss_env' ),
        Field::inst( 'crapper_vulnerability.cvss_base_new' ),
        Field::inst( 'crapper_vulnerability.not_in_report' )
            ->setFormatter( function ( $val, $data, $opts ) {
                return ! $val ? 0 : 1;
            } ),
        Field::inst( 'crapper_vulnerability.ip' ),
        Field::inst( 'crapper_vulnerability.mac' ),
        Field::inst( 'crapper_vulnerability.netbiosname' ),
        Field::inst( 'crapper_vulnerability.os' ),
        Field::inst( 'crapper_vulnerability.start' ),
        Field::inst( 'crapper_vulnerability.stop' ),
        Field::inst( 'crapper_vulnerability.plugin_id' ),
        Field::inst( 'crapper_vulnerability.plugin_name' ),
        Field::inst( 'crapper_vulnerability.port' ),
        Field::inst( 'crapper_vulnerability.protocol' ),
        Field::inst( 'crapper_vulnerability.cve' ),
        Field::inst( 'crapper_vulnerability.cvss_base_score' ),
        Field::inst( 'crapper_vulnerability.service_name' ),
        Field::inst( 'crapper_vulnerability.description' ),
        Field::inst( 'crapper_vulnerability.solution' ),
        Field::inst( 'crapper_vulnerability.kundenr' ),
        Field::inst( 'crapper_vulnerability.rapport' ),
        Field::inst( 'crapper_vulnerability.filename' ),
        Field::inst( 'crapper_vulnerability.tp_key' ),
        Field::inst( 'crapper_vulnerability.plugin_output' ),
        Field::inst( 'crapper_vulnerability.timepool' ),
        Field::inst( 'crapper_vulnerability.id' )

    )
    ->where('crapper_vulnerability.kundenr', $my_id)


    ->where( function ( $q ) use ( $timepoolid) {
        $q->where( 'crapper_vulnerability.timepool', '(SELECT crapper_vulnerability.timepool FROM crapper_vulnerability WHERE crapper_vulnerability.timepool LIKE :timepool)', 'IN', false);
        $q->bind( ':timepool', '%'.$_POST['timepool_id'].'%' );}
)

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

I'm trying to use an array $timepool in a where condition, but I'm getting the following error:

Notice: Array to string conversion

How do I resolve this?

Kind regards,
Svendber


style the excel export by class

$
0
0

I have site with many dynamic tables. I am creating these with the Datatables jQuery plug-in.
I want to modify the design of the Excel export - for instance border, background, header.
the problem:
Because the table is dynamic, I cannot explicitly specify the columns I want to edit.
Is there a way to style rows by a class?

Search keywords

$
0
0

I wanted to know which & where search keywords are stored.

Inline Editing Submit onChange instead of onBlur

$
0
0

I have my table nice and happy. Only certain fields are editable inline, they are editable with a drop down select list.

If I edit a field and click off the datatable (or click a non-editable filed) all is ok.
But if I click off a select editable field straight onto another editable select field, then I get this error in the console:

TypeError: g is undefined

To fix it, I thought I could change the line below:
editor.inline( this, { onChange: 'submit' } );

To this:
editor.inline( this, { onChange: 'submit' } );

But it didnt work. Any ideas or alternative thoughts?

pass param to drawcallback after adding a new row that sets the min value for rendering

$
0
0

Here is my code for adding a new row. the data from getJSON also returns the min value that i have to set for Qty upon rendering but im not sure how to pass this to drawback. not even sure if drawback is the answer.

function UpdateTableView(e) {
        var posUrl = '@Url.Action("UpdateTableView","Invoice")';
        var tblCount = pDt.rows().count()+1;
        $.getJSON(posUrl, { id: e.id, productTypeId: $('#ProductTypeId').val() }, function (data) {
            if (!data) {
                return;
            }
            dtbl.row.add({
                "No": data.ArticleNo,
                "Description": data.DisplayName,
                "Price": data.Price,
                "Qty": 1,
                "SubTotal": data.Price
            }).draw();
            
        });
        
        $('#dgAddProduct').modal('hide');
        
    }//

here is my code for my init. The existing onkeyup function works. Note that it is like a POS type page. how can i render the min value to Qty.

var dtbl = $('#example').DataTable({
        paging: false,
        searching: false,
        info: false,
        ordering: false,
        language: {
            "emptyTable": "No product selected."
        },
        
        columns: [
            
            { data: "No",width:"20%" },
            { data: "Description", width: "40%" },
            { data: "Price", render: $.fn.dataTable.render.number(',', '.', 0, '₱'), width: "15%" },
            {
                data: "Qty", width: "10%",render: function (data, type, row) {
                    return '<input class="form-control hello" id="Qty" name="Qty"  type="text"  value = ' + row.Qty + '  >';
                }
            },
            { data: "SubTotal", render: $.fn.dataTable.render.number(',', '.', 0, '&#8369;'), width: "15%",className:'dtRight' },
            
        ],
        "drawCallback": function (settings) {
            $(".hello").on('keyup', function () {
                var $row = $(this).parents("tr");
                var rowData = dtbl.row($row).data();

                rowData.Qty = $(this).val();
                console.log(rowData.Qty);

            });
          
        }
    });

Filter by td attribute added via columnDef

$
0
0

I am using something like this https://jsfiddle.net/an5kbx0z/ to filter my entries by a custom data attribute. Using this with the data attribute added directly in my template works flawlessly. However after changing DataTables to ajax mode and adding the data attribute via columnDefs -> createdCell the filter is no longer working.

How can I filter by data attributes added via columnDefs?

This is the columnDefs section of my script:

columnDefs: [
{
targets: [1],
createdCell: function (td, cellData, rowData, row, col) {
if(cellData === 'Info') {
$(td).attr('data-doctype', 'infoItem')
}
if(cellData === Document') {
$(td).attr('data-doctype', docItem')
}
}
}
]

I want to show child rows with responsive view

$
0
0

Hi all, i want to show responsive view and another child row for ajax data. I want to implement something like this https://www.datatables.net/blog/2017-03-31#Ajax-request but with a button.

I tried to add a button with a class but the button does nothing.

i'm using aoColumns to render data, and i have several links for button. My button is actually a dropdown with many links.

$('#lc_dt body').on('click', 'manMrIf', function () {
    var tr = $(this).closest('tr');
    var row = table.row( tr );

    if ( row.child.isShown() ) {
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        row.child( format(row.data()) ).show();
        tr.addClass('shown');
    }
} );

nothing happens, my table is responsive so when i click on more info it has to close responsive but that does not work, i alos add alert(1) after

$('#lc_dt body').on('click', 'manMrIf', function () {

but i cant see alert

DataTable Reload blink

$
0
0

Hello again, I would like one last help, good at the moment I have a DataTable that has an auto refresh if the button is 'checked=true' but what happens is the following I have to destroy the DataTable so she doesn't return the error V3, and with that she blinks, what disturbs my users, I would like a help so she doesn't have this "blink", a way to atultimate it without her blinking, thank you in advance :)


Select, Info settings and jquery-datatables-checkboxes

$
0
0

Hi,

I'm using Datatables Select with jquery-datatables-checkboxes

I edited datatables select plugin so info default value is false
(because I don't us it much and I have a tons of tables)
var info = false;
This working fine the info does not appear on my tables
except it appear on the table where I use the Select & jquery-datatables-checkboxes plugin
which is fine but I did not enable it yet ?

"select": {
    'style': 'multi',
    'selector': 'td:nth-child(2),td:nth-child(10)',
    //'info': true,
},

So is this mean that jquery-datatables-checkboxes enable to display info by default and bypassed the Datatables settings?
Or there is the Datatables Select plugin behavior
I just want to understand how it suppose to work

Thanks

Sort the results after search

$
0
0

Hello everybody,
I have a problem and I hope it can be implemented with datatables.

I want to sort the results of my search:
The result with the most suitable search criteria should be at the top and then sort in descending order.

At the beginning the table is sorted by ID - 1-30

I have already tested so much that I have lost track of everything.

Is that possible? And if so, how?
Can anyone give me food for thought?

Thank you and best regards!

DataTables warning: table id=example1 - Cannot reinitialise DataTable.

$
0
0

Are you all right?
I'm having a problem and I need your help.
My application displays this error message: "DataTables warning: table id = example1 - Cannot reinitialize DataTable. For more information about this error, please see http://datatables.net/tn/3".
I have read in some places that it is important to start "Datatables" only once, but could not find a good solution. I've tried it in many ways, but in most of them I miss the translation to my language (Brazilian Portuguese). My code is following.
Can you tell me what I'm doing wrong?
Thank you all in advance!

<script>
  $(document).ready(function() {
    $('#example1').DataTable( {
        "oLanguage": {
          "sEmptyTable": "Nenhum registro encontrado",
          "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
          "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
          "sInfoFiltered": "(Filtrados de _MAX_ registros)",
          "sInfoPostFix": "",
          "sInfoThousands": ".",
          "sLengthMenu": "_MENU_ resultados por página",
          "sLoadingRecords": "Carregando...",
          "sProcessing": "Processando...",
          "sZeroRecords": "Nenhum registro encontrado",
          "sSearch": "Pesquisar",
          "oPaginate": {
              "sNext": "Próximo",
              "sPrevious": "Anterior",
              "sFirst": "Primeiro",
              "sLast": "Último"
          },
          "oAria": {
              "sSortAscending": ": Ordenar colunas de forma ascendente",
              "sSortDescending": ": Ordenar colunas de forma descendente"
          },
          "select": {
              "rows": {
                  "_": "Selecionado %d linhas",
                  "0": "Nenhuma linha selecionada",
                  "1": "Selecionado 1 linha"
              }
          }
        },  

        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],
        language: {
            buttons: {
                copyTitle: 'Copiado para área de transferência',
                copyKeys: 'Pressione <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> para copiar os dados da tabela para a área de transferência. <br> <br> Para cancelar, clique nesta mensagem ou pressione Esc.',
                copySuccess: {
                    _: '%d linhas copiadas',
                    1: '1 linha copiada'
                }
            }
        }
        
    } );
    // Setup - add a text input to each footer cell
    $('#example1 thead tr').clone(true).appendTo( '#example1 thead' );
    $('#example1 thead tr:eq(1) th').each( function (i) {
        
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Procurar '+title+'" />' );
 
        $( 'input', this ).on( 'keyup change', function () {
            if ( table.column(i).search() !== this.value ) {
                table
                    .column(i)
                    .search( this.value )
                    .draw();
            }
        } );
    } );
    
    var table = $('#example1').DataTable( {

        orderCellsTop: true,

    } );
} );
</script>

jquery-datatables-checkboxes savestate question

$
0
0

Hi,

I'm using https://github.com/gyrocode/jquery-datatables-checkboxes/

And trying to save the statesave

In console.log on page load, there is no checkbox selected
using stateSaveCallback or stateSaveParams

the result for the checkbox state is

checkboxes: (2) [empty, {…}]
checkboxes: Array(2)
1: {}
length: 2
__proto__: Array(0)

I guess the problem come from this [empty, {…}] instead of displayed this [{…}]
I'm sending the table state like this "tablestate": JSON.stringify(data)
because I'm saving the state into DB and only the checkbox statevalues are not saved the other Datatables are saved ok

I'm using Datatables 1.10.11 (cannot update to latest for now)
Any idea what is going wrong and recommendation to fix this.

Handle millions of records

$
0
0

Hey there,

I'm working on a project which handles about 4 million users. I'd like to make a more interactive list and this is why I decided to use DataTables.

The thing is that load 4M of records at once consumes a lot of resources and isn't efficient at all. I was wondering work with pagination but i don't find how to make this approach. This is what i am testing:

$('#apiResults').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "api/search/username",
type: 'POST'
}
});

'api/search/username' returns 4millions of record. I always get errors related to memory because it is a lot of data.
With a small dataset, it works perfectly.

I'm pretty sure I'm missing some parameter to maybe, load X number of first pages and then, load the rest with ajax or something like that.

I hope you can help me.

Thanks in advance.

DataTable flicker

$
0
0

Hello, I need a hand in updating DataTable.

I have a timer that updates every 10 seconds my table, but I have a flicker, I would like to receive the data from my monitoring screen without this flicker as it hinders my users

I found this question looking around but the guy didn't give me a solution because I don't have the code so I don't know what each function is doing and how it's doing it: https://datatables.net/forums/discussion/11780/to-flicker-or-not-to-flicker

Inline Editor, Dropdown list, bind data to list

$
0
0

I have went through discussion and doc but can not seem to find a solution to my problem. I have a column that is tied to a second table. I have built the data from the table to be displayed in the dropdown list but I can not seem to connect the collection to the list. When looking at the json data I can see the collection called 'Location'. Basically I get the drop arrow but when click it there is nothing in the list.

I would appreciate any help I can get.

This the controller:

        using (var dbe = new DataTables.Database(Globals.DbType, Globals.DbConnection))
        {
            int tripmasterID = Convert.ToInt32(Session["tripmasterID"]);

            var response = new Editor(dbe, "MasterStops", "ID")
                .Model<ViewModels.JoinModelMastStops>("MasterStops")
                .Model<ViewModels.JoinModelSMSStops>("sms_stops")

                .Field(new Field("MasterStops.USPSTrip"))
                .Field(new Field("MasterStops.SMS_Stage"))
                .Field(new Field("sms_stops.LOCATIONNM", "Location")
                    .Options(new Options()
                        .Table("sms_stops")
                        .Value("ID")
                        .Label("LOCATIONNM")
                    )
                )
                .Field(new Field("sms_stops.STOPTYPE"))
                .Field(new Field("sms_stops.Nass_Code"))
                .Field(new Field("MasterStops.SchArvTime"))
                .Field(new Field("MasterStops.SchDepTime"))
                .Field(new Field("MasterStops.DayNumber"))
                .Field(new Field("MasterStops.StopNumber"))
                .LeftJoin("sms_stops", "MasterStops.ID", "=", "sms_stops.ID")
                .Where("MasterStops.TripMastID", tripmasterID)
                .Process(request)
                .Data();
            return Json(response, JsonRequestBehavior.AllowGet);
        }

The Java script:

document.getElementById("Loading").style.display = "none";
$(document).ready(function () {
    $(function () {
        $(".checkinout").mask("99:99");
        $(".time").mask("99:99", { placeholder: "0" });
        //$(".miles").mask("9999.99", { placeholder: "_" });
        $(".hours").mask("999.99", { placeholder: "0" });
        $(".initials").mask("aaa");
    });
    $(".dtp").datepicker();
    var editor = new $.fn.dataTable.Editor({
        ajax: '@Session["RootFolder"]' + '/TripMasters/Table',
        table: '#schedtable',
        fields:
            [
                { label: 'POTRIP', name: 'MasterStops.USPSTrip' },
                { label: 'Stage', name: 'MasterStops.SMS_Stage' },
                { label: 'Stop Name', name: 'MasterStops.SMS_StopsID', type: "select" },
                { label: 'StopType', name: 'sms_stops.STOPTYPE' },
                { label: 'Nass', name: 'MasterStops.Nass_Code' },
                { label: 'Arrive', name: 'MasterStops.SchArvTime' },
                { label: 'Depart', name: 'MasterStops.SchDepTime' },
                { label: 'Day #',
                    name: 'MasterStops.DayNumber',
                    type: "select",
                    options:
                        [
                            { Label: '1', value: '1' },
                            { Label: '2', value: '2' },
                            { Label: '3', value: '3' }
                        ]
                },
                { label: 'Stop Order', name: 'MasterStops.StopNumber' }
            ]
    })

    $('#schedtable').on('click', 'tbody td.editable', function (e) {
        editor.inline(this, {
            onBlur: 'submit'
        });
    });

    $('#schedtable').DataTable({
        dom: 'Bfrtip',
        ajax: '@Session["RootFolder"]' + '/TripMasters/Table',
        model: 'JoinMastStops',
        "scrollY": "300px",
        "scrollCollapse": true,
        "paging": false,
        "bFilter": false,
        "paging": false,
        "bFilter": false,
        "order": [[8, 'asc']],
        columns:
            [
                { data: 'MasterStops.USPSTrip', className: 'editable' },
                { data: 'MasterStops.SMS_Stage', className: 'editable' },
                { data: 'sms_stops.LOCATIONNM', className: 'editable', editField: "MasterStops.SMS_StopsID" },
                { data: 'sms_stops.STOPTYPE', className: 'editable' },
                { data: 'MasterStops.Nass_Code', className: 'editable' },
                { data: 'MasterStops.SchArvTime', className: 'editable' },
                { data: 'MasterStops.SchDepTime', className: 'editable' },
                { data: 'MasterStops.DayNumber', className: 'editable' },
                { data: 'MasterStops.StopNumber', className: 'editable' }
            ],
        columnDefs:
            [
                { "targets": [0], "orderable": false },
                { "targets": [1], "orderable": false },
                { "targets": [2], "orderable": false },
                { "targets": [3], "orderable": false },
                { "targets": [4], "orderable": false },
                { "targets": [5], "orderable": false },
                { "targets": [6], "orderable": false },
                { "targets": [7], "orderable": false },
                { "targets": [8], "orderable": false },
            ],
        select: true,
        //select: {
        //    style: 'os',
        //    collection: 'Location'
        //},
        buttons:
            [
                //{ extend: "create", editor: editor },
                //{ extend: "edit", editor: editor },
                //{ extend: "remove", editor: editor }
            ]
    })
});

Leaving data alone

$
0
0

I'm sure this is out there somewhere I'm just not using the right search criteria. If we input something like January 21-23 into a text field (using latest DT & Editor) it converts that to a date. Is there a universal way to tell DT / Editor to treat the data as verbatim and not convert to a date (or an int ... etc.)?

How to get text input from a column filter?

$
0
0

I have html that creates input boxes on my dataTable for filtering my column.

Everything works great, but when my webpage is refreshed the user input disappears however the dataTable stays filtered (I'm assuming as a result of state save).

I would like to get each columns filtered value to re-populate my input boxes so my users aren't confused on refresh.

console.log(table.columns(1, 2).search() ) gives me an object and I can clearly see the value within the object string. How can I simply get that value to assign it to my html element?

Apologies in advance as I'm still new to HTML and Javascript

For example, I am getting the below but I want to simply get the text "EDI" so I can assign it
Object { 0: "EDI", context: (1) […], length: 1, selector: {…}, tables: g(), table: g(), draw: g(), page: g(), ajax: {…}, rows: g(), … }

Thank you for any help you can provide

Computed Values for Table in Editor

$
0
0

He there,

I am using Editor and would like to add a computed value to the JSON string for being displayed in the table. It just needs to be displayed in the table - there is no need for saving it in the Database (there is no corresponding field in the Database ;-)).

How can I add such a computed value to the JSON string with Editor?

Thanks in advance!

how to pass param to server side by html5 data-attributes ?

$
0
0

<table class="table table-striped- table-bordered table-hover table-checkable table-data" id="table-product" data-ajax="../../sql/common/get-product-info.php" data-data="checking()"> <thead> <tr> <th data-data="lanID" style="min-width:50px" class="text-center lan-id">ID</th> <th data-data="lanID" style="min-width:16rem" class="lan-product-name">Product Name</th> <th data-data="lanID" style="min-width:6rem" class="text-right lan-sold">Sold</th> <th data-data="lanID" style="min-width:6rem" class="text-right lan-price">Price</th> <th data-data="lanID" style="min-width:6rem" class="text-right lan-cost">Cost</th> <th data-data="lanID" style="min-width:6rem" class="text-right lan-profit">Profit</th> <th data-data="lanID" style="min-width:6rem" class="text-center lan-status">Status</th> <th data-data="lanID" style="min-width:8rem" class="lan-reg-date">Reg Date</th> <th data-data="lanID" style="min-width:7rem" class="lan-reg-time" data-visible="false">Reg Time</th> <th data-data="lanID" style="min-width:6rem" class="lan-action">Action</th> </tr> </thead>

i dn want to use jquery to pass the params, i want write like data-ajax='php file' data-param='request_param()' and i make the params value in the function. how can i do it ?

Problem with Reload callback

$
0
0

I have a method which uploads data to the server using Ajax and returns a json object on success that says whether to reload the table or not. The object returned is:

{"reload": true, "afterReload": "updateOnReload"}

The afterReload value can be any function name with the right signature.

The important part of the method is

table = $("mytable").DataTable();

//repsonse is the parsed json

if (response.reload) {
   table.ajax.reload(function(json){eval(response.afterReload(table)});
};

this works as expected and the function called is as follows

function updateOnReload(table) {

 if (!table.rows().count()){
    table.button("big_step:name").disable();
    table.button("filter_step:name").disable();
 }
 else {
    table.button("big_step:name").enable();
    table.button("filter_step:name").enable();
 };
};

The issue I am having is that table.rows().count() is not returning the correct count - it seems to call the row count prior to loading the data, rather than after.

any ideas?

Viewing all 81906 articles
Browse latest View live