Quantcast
Channel: DataTables 1.9 — DataTables forums
Viewing all 1816 articles
Browse latest View live

How do you reverse the rowOrdering sequence so that the new item get added as a last item?

$
0
0

My form code:

  {
    label: "Order",
    name: "articles.rowOrder",
    type: "hidden",
    default: 1,
  },

How do you reverse the ordering sequence so that when you add a new item it gets the rowORder # as the highest number rather than #1 (which pushes everything else down)?

  // ROWORDER BLOCK
  ->on('preCreate', function ($editor, $values) {
    if (!$values['articles']['rowOrder']) {
      $next = $editor->db()->sql('select IFNULL(MAX(rowOrder)+1, 1) as next FROM articles')->fetch();
      $editor->field('articles.rowOrder')->setValue($next['next']);
    } else {
      $editor->db()
      ->query('update', 'articles')
      ->set('rowOrder', 'rowOrder+1', false)
      ->where('rowOrder', $values['articles']['rowOrder'], '>=')
      ->exec();
    }
  })
  ->on('preRemove', function ($editor, $id, $values) {
    $order = $editor->db()
    ->select('articles', 'rowOrder', array('id' => $id))
    ->fetch();

    $editor->db()
    ->query('update', 'articles')
    ->set('rowOrder', 'rowOrder-1', false)
    ->where('rowOrder', $order['rowOrder'], '>')
    ->exec();
  })
  // ROWORDER BLOCK

Sorting Date column that includes time zone will not work

$
0
0

Is there anyway to sort this date column that includes the time zone? Example of it is below. If I remove the time zone i.e. "US/Central" then it does work fine. However, it was requested to include it.

2022-05-18 09:23:47 PM US/Central
2022-05-18 09:22:11 PM US/Central

I could just move the time zone into a new column but as of now, the client perfers it all in one.

Can editor work on json txt file as data source?

$
0
0

We don't want to use a database for this since the information is very minimal. We have a txt file that contains json objects to load that datatables. I have that working, very similar to this URL below. Can we allow datatables editor to work with an json txt file as the data source where I can add new rows or edit existing ones?

https://datatables.net/examples/ajax/objects.html

Here is my code that includes the editor portion:

editor = new $.fn.dataTable.Editor({
    ajax: 'config_clientsVersion2.txt',
    table: "#table",
    fields: [ 
        {
            label: "G Number:",
            name: "gNumber"
        }, 
        {
            label: "Diagram Types:",
            name: "diagramTypes"
        },
        {
            label: "Require Gleason Score:",
            name: "showGleasonScore"
        },
        {
            label: "Require Percentage:",
            name: "showPercentage"
        },
    ]
});

$('#table').DataTable({
    dom: 'Bfrtip',
    ajax: 'config_clientsVersion2.txt',
    columns: [
        { data: 'gNumber' },
        { data: 'diagramTypes' },
        { data: 'showGleasonScore' },
        { data: 'showPercentage' }
    ],
    buttons: [
        { extend: "create", editor: editor },
        { extend: "edit",   editor: editor },
        { extend: "remove", editor: editor }
    ]
});

On editor 1.96 question

Input field to scan barcodes to quickly select multiple rows to edit

$
0
0

Editor 1.96 being used.

I tried searching in the forums but didn't see anything on this topic yet, just wanted to check if there is an existing api for this something like this:

  1. Have an input field, where we can enter in data (in our case we will scan a barcode) to search in the first column, if there is a match, select that row.
  2. Repeat step 1, and continue to add to the selection of rows.
  3. When finished searching, we then hit edit to do whatever task is needed for all selected rows.

If it does not exist, I'll just write something up that searches in the first column based on the entered input text, if there is a match we just select the row, something similiar to this code below

$('#example tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});

Found on this example page:
https://datatables.net/examples/api/select_row.html

Formatted Date using Moment with AM/PM and TimeZone does not sort in FireFox

$
0
0

Using this code:

$.fn.dataTable.moment('YYYY-mm-dd HH:mm:ss tt zz');

To format the date and it works and sorts fine in Chrome, but the sort button does nothing in FireFox, it does display the date correctly in both. I'm assuming I need to render it somehow, but I've been unable to solve it.

                columnDefs: [
                    { 
                        targets: 6, 
                        render: [DATETIME AM/PM TIMEZONE]
                    }],

How to set the default number of rows displayed

$
0
0

I have tried using "pageLength": 50, to set the fault number of records displayed in a datatables page, but it's not working. The page only displays 5 records per pagination. Any ideas?

var table = $( '#program_table' ).DataTable( {
                responsive: true,
                "pageLength": 50,
                columnDefs: [ {
                    targets: [1],
                    render: $.fn.dataTable.render.ellipsis( 100, true )
                } ],
                ajax: "program_data/program_data.php",
                dom: "Bfrtip",
                columns: [ {
                    data: "program_name"
                }, {
                    data: "program_details"
                }, {
                    data: "modified"
                }, {
                    data: "modified_by"
                } ],
                select: {
                    style: 'os',
                    selector: 'td:first-child'
                },
                buttons: []
            } );

Ellipsis renderer that can expand column to show full text

$
0
0

Is there somthing similiar to ellipsis renderer for long text columns that if we click into the column that would expand the column to display the full text?


How to put/insert/update/modify bonus to all employees in the table based on input amount

$
0
0

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

DataTables-Editor-Server.dll and MySql.Data

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem: I have version 1.9.6 of DataTables-Editor-Server.dll and would like to know what is the highest version of the .Net connector for Mysql.data that is compatible with that version of your DT component. I keep getting version conflict errors in Visual Studio saying it's expecting v8.0.33. I'm using 8.1.0. Thanks.

Possible bugs with Opera browser v102.0.4880.56

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem: Hi, I use Opera and presumably this is the same issue with Chrome and it is now throwing errors where it wasn't before with older versions. The browser updated itself 2 days ago. It does not like the way for tags are added by DT to labels when creating editor forms. See code and screenshots below. Please advise.

table: '#tblDataTable1',
    //template: $('#divEditorForm1').clone(),
    template: '#divEditorForm1',
    fields: [
        {
            label: '',
            name: 'ContactTrans.id',
            type: 'hidden'
        }, {
            label: captionsarray.filter(p => p.label == 'lblContactType')[0].value + '*:',
            name: 'ContactTrans.ContactType',
            type: 'select',
            options: [],
            def: '-1'
        }
        }
    ],


Slow footerCallback

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem: I am using the code below but without the footerCallback, loading takes 20 sec. With it it takes 10mins. Any idea how it can be improved. Many thanks.
```

```dataTable1 = $('#tblDataTable1').DataTable({

    order: [[1, 'desc']],
    pageLength: 10,
    dom: 'Bfrtip',
    ajax: {
        url: '/' + strAccountIdx1 + '/Admin/ContactTrans/CRUDContactTrans/',
        data: function (d) {
            return $.extend({}, d, {
                intContTpe: booIsGlobal1 == 1 ? -1 : intContTpe1
            });
        },
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        async: true,
        cache: false
    },
    responsive: true,
    processing: true,
    deferRender: true,
    orderClasses: false,
    paging: true,
    //serverSide: true,
    columns: [
        {
            data: null,
            defaultContent: '',
            orderable: false
        },
        {
            data: 'ContactTrans.id',  //1
            className: 'text-left'
        }
        //...
    ],
    rowCallback: function myRowCallback(row, data) {

        if (IsTransTypeInvoiceLike(data.ContactTrans.TransType)) {
            $('td:eq(0)', row).removeClass();
            $('td:eq(0)', row).addClass('details-control');
        }
        else {
            $('td:eq(0)', row).removeClass();
            $('td:eq(0)', row).addClass('nodetails-control');
        }
    },
    footerCallback: function (row, data, start, end, display) {

        var api = this.api(), data;
        // Remove the formatting to get integer data for summation
        var intVal1 = function (i) {
            return typeof i === 'string' ?
                i.replace(/[\$,]/g, '') * 1 :
                typeof i === 'number' ? i : 0;
        };
        var intVal2 = function (i) {
            return typeof i === 'string' ?
                i.replace(/[\$,]/g, '') * 1 :
                typeof i === 'number' ? i : 0;
        };
        var intVal3 = function (i) {
            return typeof i === 'string' ?
                i.replace(/[\$,]/g, '') * 1 :
                typeof i === 'number' ? i : 0;
        };
        // Total over all pages
        dblNetTotal = api
            .column(19, { search: 'applied' })
            .data()
            .reduce(function (a, b) {
                return intVal1(a) + intVal1(b);
            }, 0);
        dblTaxTotal = api
            .column(20, { search: 'applied' })
            .data()
            .reduce(function (a, b) {

                var dblTaxAmount = 0;

                $.each(data, function (i, e) {
                    $.each(e.ContactTransTaxes, function (i, e) {
                        dblTaxAmount += e.TaxAmount;
                    });
                });

                return dblTaxAmount;
            }, 0);
        dblGroTotal = api
            .column(21, { search: 'applied' })
            .data()
            .reduce(function (a, b) {
                return intVal3(a) + intVal3(b);
            }, 0);
        // Update footer
        $('tr:eq(0) th:eq(1)', api.table().footer()).html((booIsGlobal1 == 0 ? strCurrency1 + ' ' : '') + ManageDecimals(4, dblNetTotal));
        $('tr:eq(1) th:eq(1)', api.table().footer()).html((booIsGlobal1 == 0 ? strCurrency1 + ' ' : '') + ManageDecimals(4, dblTaxTotal));
        $('tr:eq(2) th:eq(1)', api.table().footer()).html((booIsGlobal1 == 0 ? strCurrency1 + ' ' : '') + ManageDecimals(4, dblGroTotal));
    },
    select: {
        style: 'os',
        selector: 'td:not(:first-child)'
    },
    initComplete: function () {
        var dt = new Date();
        var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
        PrintToOutput('Open complete: ', time);
    }
});

Grabbing upload in-server validation errors

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem: Hi all, please let me know if there is an event available in a client for the above. I have used things like ajax's submitError event to no avail. Thanks.

Error "An item with the same key has already been added."

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem: I'm working with MVC c# and Editor Datatables from http://editor.datatables.net. i'm getting the error below on line 'editor.Process(formData);' of my server code:

An item with the same key has already been added.

What could be the cause and how can i debug the error to identify what keys are being added?

Here's my code:

  • A class:
public class VoiceMYTABLEDataDBModel
{
    public class VoiceMYTABLEData
    {
        public long id { get; set; }
        public string Customer_ID { get; set; }
    }

    public class VoiceMYTABLEInvoice
    {
        public long id { get; set; }
        public long CustomerID { get; set; }
        public long MYTABLEDataID { get; set; }
        public string InvoiceNumber { get; set; }
    }
}
  • Controller code:
        public DtResponse CRUDRatedVoiceMYTABLEData(string strFromDate, string strToDate, int intExportToFile, MYTABLEDataUISettings lblo)
        {
            Editor editor = null;
            NameValueViewModel[] arrNVVM = null;
            Task t;

            try
            {
                HttpRequest formData = HttpContext.Current.Request;

                CustomersModel CM = new CustomersModel();
                arrNVVM = CM.GetAllCustomerIDsNbrs_arr();
                CM = null;

                if (arrNVVM == null) arrNVVM = new NameValueViewModel[] { };

                using (Database db = new Database(SetGetDbType2, SetGetDbConnection))
                {
                    editor = new Editor(db, "VoiceMYTABLEData", "VoiceMYTABLEData.id").Model<VoiceMYTABLEDataDBModel.VoiceMYTABLEData>("VoiceMYTABLEData");
                    editor.Field(new Field("VoiceMYTABLEData.id")
                        .Set(false)
                    );
                    editor.Field(new Field("VoiceMYTABLEData.Customer_ID")
                        .Set(false)
                    );
                    editor.LeftJoin("VoiceMYTABLEInvoice", "VoiceMYTABLEData.id", "=", "VoiceMYTABLEInvoice.MYTABLEDataID")
                        .MJoin(new MJoin("VoiceMYTABLEInvoice")
                        .Model<VoiceMYTABLEDataDBModel.VoiceMYTABLEInvoice>()
                        .Name("VoiceMYTABLEInvoice")
                        .Link("VoiceMYTABLEData.id", "VoiceMYTABLEInvoice.MYTABLEDataID")
                        .Order("VoiceMYTABLEInvoice.InvoiceNumber ASC")
                        .Field(new Field("id")
                            .Options(new Options()
                                .Table("VoiceMYTABLEInvoice")
                                .Value("id")
                                .Label("InvoiceNumber")
                                .Order("InvoiceNumber ASC")
                                .Render(row =>
                                {
                                    return dicPCEAValues["InvoiceNumber"].ToString();
                                }).Order("InvoiceNumber ASC")
                            )
                            .Set(false)
                        )
                        .Set(false)
                    );

                    editor.Where("VoiceMYTABLEData.Date_Time_Called", CommonUtilities.ToDate2(strFromDate + " 00:00:01"), ">=");
                    editor.Where("VoiceMYTABLEData.Date_Time_Called", CommonUtilities.ToDate2(strToDate + " 23:59:59"), "<=");

                    editor.TryCatch(false);
                    editor.Debug(true);
                    editor.Process(formData);
                }
                arrNVVM = null;
            }
            catch (Exception ex)
            {
                
            }
            return editor.Data();
        }
  • client js code:
function CRUDRatedVoiceMYTABLEData(strFromDate1, strToDate1, intExportToFile1) {

    var strSelOpt = '';
    var strSelSta = '<select class="form-control">';
    var strSelEnd = '</select>';

    var token = $('input[name="__RequestVerificationToken"]').val();

    dataTable2 = $('#tblRatedVoiceMYTABLEDataTable').DataTable({

        destroy: true,
        responsive: true,
        processing: true,
        deferRender: true,
        select: true,
        order: [[0, 'desc']],
        pageLength: 10,
        columnDefs: [
            { 'bVisible': false, 'targets': 0 },
            {
                'targets': [0, 1, 2],
                className: 'text-center'
            }
        ],
        dom: 'Bfrtip',
        ajax: {
            url: '/users/' + strAccountIdx1 + '/Admin/MYTABLEData/CRUDRatedVoiceMYTABLEData/',
            data: function (d) {
                return $.extend({}, d, {
                    strFromDate: strFromDate1,
                    strToDate: strToDate1,
                    intExportToFile: intExportToFile1,
                    __RequestVerificationToken: token
                });
            },
            //type: 'GET',
            type: 'POST',
            dataType: 'json',
            //contentType: 'application/json; charset=utf-8',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            async: true,
            cache: false
        },
        columns: [
            {
                data: 'VoiceMYTABLEData.id',
                className: 'text-left'
            },
            {
                data: 'VoiceMYTABLEData.Customer_ID',
                className: 'text-left'
            },
            {
                data: 'VoiceMYTABLEInvoice',
                className: 'text-left'
            }
        ],
        buttons: [
            { extend: 'edit', editor: editor3, formButtons: [] }
        ]
    });
}
  • create script for the db tables:
CREATE TABLE IF NOT EXISTS `[DBNAME]`.`VoiceMYTABLEData` (
  `ID` BIGINT NOT NULL AUTO_INCREMENT,
  `Customer_ID` BIGINT DEFAULT '0',
  PRIMARY KEY (`ID`),
  UNIQUE INDEX `Index_PrimaryKey` (`ID`),
  INDEX `Index_Customer_ID` (`Customer_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

DROP TABLE IF EXISTS `[DBNAME]`.`VoiceMYTABLEInvoice`;;
CREATE TABLE IF NOT EXISTS `[DBNAME]`.`VoiceMYTABLEInvoice` (
  `ID` BIGINT NOT NULL AUTO_INCREMENT,
  `CustomerID` BIGINT DEFAULT '0',
  `MYTABLEDataID` BIGINT DEFAULT '0',
  `InvoiceNumber` VARCHAR(55) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE INDEX `Index_PrimaryKey` (`ID`),
  INDEX `Index_CustomerID` (`CustomerID`),
  INDEX `Index_MYTABLEDataID` (`MYTABLEDataID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

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

How do I do calculated fields on the server of a record being created or updated?

$
0
0

I have a very simple table with a few fields. The table has another six or so fields that are calculated on the server and saved as part of a record being created or updated. The calculated fields do not need to be returned to the client, though they can. However, they do need to be calculated on the server and some fields involve numerical methods. These are very fast running. However, I'm unsure how to do this or hook into this with datatables. The DTO class contains all edited fields and all calculated fields. The calculations could be done via a method that returns an instance of the DTO with the calculated fields. i.e, dto = GetCalcValues(dto).

I'm using the .net code for the table that looks like this:

using (var db = new Database(dbType, dbConnection))
{
    var response = new Editor(db, "J")
        .Model<DTO>()
        .Field(new Field("Re")
            .Validator(Validation.Numeric())
        )
        .Field(new Field("J")
            .Validator(Validation.Numeric())
        )
        .TryCatch(false)
        .Process(Request)
        .Data();
    return Json(response);
}

How do you pass a customer's id to a datatable editor form?

$
0
0

This is in laravel. I have a users table and form and in a column a link to pass the $uid to another DTE page:

``return '<a href=/bin/inspections2?uid=' + data.users.id + ' target="_new">Report</a>';

It correctly drops the $uid into the URL of the next table but it is invisible to the next DTE page. The URL displays as:

``/bin/inspections2?uid=2

Seems great. However in the laravel controller file, I cannot get the variable out of the URL. It comes up empty:

$uid = $request->input('uid'); // Get `uid` from the request \Log::debug("Received UID: " . $uid);

The $uid is necessary to set a where statement to limit result's to those of that user. Any ideas?

Viewing all 1816 articles
Browse latest View live


Latest Images