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

Connecting to Oracle?

$
0
0

I'm trying to connect Editor to an Oracle database, but I'm getting this javascript error. It works fine with Mysql, but I can't get the connection to Oracle working. I'm entering the credentials in the php/config.php file the same way that I successfully did for Mysql. I have other php pages that aren't using Editor, they are just using the php function oci_connect(), and they successfully connect to the same Oracle database so I know the credentials I am using are correct. What am I missing or doing wrong? I have removed the username, password, and host from my example here for security purposes, but they are there in my actual code.

    $sql_details = array(
        "type" => "Oracle",  // Database type: "Mysql", "Postgres", "Sqlserver", "Sqlite" or "Oracle"
        "user" => "usernamehere",       // Database user name
        "pass" => "passwordhere",       // Database password
        "host" => "hosthere",       // Database host
        "port" => "",       // Database connection port (can be left empty for default)
        "db"   => "prod",       // Database name
        "dsn"  => "prod"        // PHP DSN extra information. Set as `charset=utf8` if you are using MySQL
    );

Cells that contain "0%" appear blank in Excel

$
0
0

Hi to everyone

My datatable result is;

0 0 0 10%
0 0 0 0%
40 280 320 16%

but excel showing when I export;

0 0 0 10%
0 0 0 <-- 0% missing
40 280 320 16%

How can i fix this?
Have a nice day.

Call datatables standard sorting in custom sorting method

$
0
0

Hello people,

i have defined a custom sorting method which ignores empty cells if the
content is empty. But when there is a content i would like to call the standard datables sorting.

$('#table').dataTable( {
"aoColumnDefs": [{"bSortable": true, "sType": "nullable", "aTargets":['_all']}]
});

$.fn.dataTableExt.oSort['nullable-asc'] = function(a,b) {
if (a == '-')
return 1;
else if (b == '-')
return -1;
else
{
// call datatables standard sorting comparing "a" and "b"
}
}

thanks for your help!

Persisting issue with column visibility/buttons displaying in wordpress

$
0
0

I have a site at testing.uwsinc.net/dashboardtest that uses a datatable. Everything has worked fine with it, but due to the nature of wordpress, some of the inherent datatable code has had to be modified or formatted differently in the past. I'm wondering if that's the issue here as well.

I've implemented the below code but I've tried for days and cannot get the button to show on my site for column visibility. I need any possible way to show/hide columns on this table. This code works on my test site but not this wordpress site. Any ideas?

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css" />
<script type="text/javascript"   src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript"   src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.colVis.min.js"></script>
<script type="text/javascript"   src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js"></script>
<script type="text/javascript"   src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/plug-ins/1.10.15/filtering/row-based/range_dates.js"></script>

</head>
<body>

<label style="font-weight:bold;">Select the table you would like to view:
</label></br>
<select name='tables' id='select-tables'>
<option value="mytable">Survey Test Table</option>
<option value="mytableSurvey">Survey Only</option>
</select>
</br>


<script type="text/javascript">
(function($) {
$(document).ready(function() {

$('#mytable').DataTable({
dom: 'Bfrtip',
  buttons: [
    'copy', 'excel', 'pdf', 'colvis'
]
});


$('#mytableSurvey').DataTable({
dom: 'Bfrtip',
buttons: [
    'copy', 'excel', 'pdf', 'colvis'
]
});
$('.dataTable').wrap('<div class="dataTables_scroll" />');




$(document).on('change' , '#select-tables', function(){
var table = $(this).val();
$('#' + table +'_wrapper').show();
$('[id$="_wrapper"]').not('#' + table +'_wrapper').hide();
});
$("#select-tables").trigger("change");

});
}(jQuery));
</script>

Getting undefined data on button click event

$
0
0

Hello,

I'm using jquery.datatables 1.10.15, jquery 1.12.4 in Visual Studio 2017 Community with an ASP.NET MVC 6 program.

I'm Getting undefined data on button click event.

I already have my own DataTables function running the way I want it to except for this button click event problem. I'm using the following code to display an alert for the data in my datatable:

               var masterTable = $('#master').DataTable({
                    'processing': true,
                    'select': true,
                    'paging': false,
                    'searching': false,
                    'ajax': {
                         'url': "data/mailboxes.txt"
                    },
                    dom: 'B',
                    buttons: [
                         {
                              text: 'My button',
                              action: function (e, dt, node, config) {
                                   alert('Button activated');
                              }
                         }
                    ],
                    'columns': [
                         { 'data': 'Alias' },
                         { 'data': 'User' },
                         { 'data': 'Host' },
                         { 'data': 'Password' },
                         { 'data': 'PromptForPassword' },
                         { 'data': 'Mail' },
                         { "data": 'CommunicationStatus' },
                         { 'data': 'ServerPortNumber' },
                         { 'data': 'PollPeriod' },
                         { 'data': 'UseSsl' },
                         { 'data': 'Edit' }
                    ],
                    "columnDefs": [
                         { "targets": [0, 1, 2], "width": "21%" },
                         { "targets": [3, 4], "visible": false },
                         { "targets": 5, "width": "6%", 'defaultContent': 0 },
                         { "targets": 6, "width": "9%", 'defaultContent': "Communication status undefined ", render: $.fn.dataTable.render.ellipsis(6, false, true) },
                         { "targets": 7, "width": "7%" },
                         { "targets": 8, "width": "9%", render: function (data, type, row) { return data + ' min '; } },
                         { "targets": 9, "width": "6%" },
                         { "targets": -1, "data": null, "defaultContent": "<button>Click!</button>" }
                    ]
               });

               $('#master tbody').on('click', 'button', function () {
                    var data = masterTable.row($(this).parents('tr')).data();
                    alert(data[0] + "'s Port number is: " + data[7]);
               });

.
The alert box looks like the image attached at the end of this post.

You can view it live here: tonygirgenti.biz/. Just select the "DataTable Test" menu option.

I'm pretty sure I have the necessary scripts for buttons loading, because the button link on the upper left of the table works.

Any help that anyone can provide to figure out what I am doing wrong would be gratefully appreciated.

Thanks,
Tony

Update a value Change in a Datatable

$
0
0

Hello , i want to ask about how to update a value in a Datatable .
I change a value (with edit function) and after saving i expect to see the "new_value" all over at the same column .
Thanks for Help :)

Is this misalignment fixable (I have jsfiddle)?

Create new row - use last create row data to be the default value

$
0
0

Now I am able to create new row at end of the data table, but I wish field show default value of editor form when create new row.
The default value of field is dynamic that get from last create new row value.

Please help


Using JS Bin technote examples use dataTables for initialization

Individual column searching DataTale Not Working

$
0
0

hello

i'm new at DataTable ... I've been downloaded & i want to use in my project but it's not working ... this is my whole page code at the attachment ...

Using Editor for the first time in a WordPress site

$
0
0

This is my first time using datatables at all, let alone Editor, but I've been tasked with making these existing datatables editable. This is all taking place on a WordPress site and I've had some headaches in the past getting the tables themselves to work on this specific wordpress site. I'm hoping for some tips on how to get editor working on these tables so that rows can be deleted or edited and the database would update from the edits. One thing to note is that all of my data, including table headers, is loaded from a database and not called explicitly in the code.

I'm just looking for the best way to get this table editable and the delete option for rows for someone who is very much a novice and for this to work in a WP environment.

The tables are at testing.uwsinc.net/dashboardtest and here is the code:

<head>
<script type="text/javascript"   src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript"   src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.colVis.min.js"></script>
<script type="text/javascript"   src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js"></script>
<script type="text/javascript"   src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script type="text/javascript"   src="https://cdn.datatables.net/plug-ins/1.10.15/filtering/row-based/range_dates.js"></script>
</head>
<body>

<label style="font-weight:bold;">Select the table you would like to view:
</label></br>
<select name='tables' id='select-tables'>
<option value="mytable">Survey Test Table</option>
<option value="mytableSurvey">Survey Only</option>
</select>
</br>


<script type="text/javascript">
(function($) {
$(document).ready(function() {

$('#mytable').DataTable({
dom: 'Bfrtip',
  buttons: [
    'copy', 'excel', 'pdf', 'colvis'
]
});


$('#mytableSurvey').DataTable({
dom: 'Bfrtip',
buttons: [
    'copy', 'excel', 'pdf', 'colvis'
]
});
$('.dataTable').wrap('<div class="dataTables_scroll" />');


$(document).on('change' , '#select-tables', function(){
var table = $(this).val();
$('#' + table +'_wrapper').show();
$('[id$="_wrapper"]').not('#' + table +'_wrapper').hide();
});
$("#select-tables").trigger("change");

});
}(jQuery));
</script>

Disable row selection

$
0
0

Hi!
One more question.... I have the following conditional code:
```{

                    "data": "cdi_calendar_changes.active",
                           "render": function (val, type, row) {
                               return val == 0 ?
                                  "<font color=red><b>LOCKED</b></font>"  : "<input type=checkbox className=select-checkbox>"

                               orderable: false
                           }
                       },```

Problem is that the row that displays the Locked message can still be selected. But I need the selection functionality disabled.
Any suggestion?

Thanks!

Datatables Wordpress Media Library Conflict

$
0
0

I am running in a very odd and strange conflict that had be scratching a dent in my head. I have been using DataTables in wodpress plugins for sometime now and have never had any issues. I then tried to use the wordpress media library and data tables on the same page. Here is the interesting part... if I have all the script on the page but don't ever call .DataTable() there is not problem. The second I actually call .DataTable() it breaks the pop up media library and I see a "TypeError: undefined is not an object (evaluating 'n.replace')" coming from underscore.js. Anyone have an advice on this one?

Row grouping with printing

$
0
0

I believe i solved the problem with printing with row grouping. I found a snippet of code on StackOverflow here and was able to fix it up to work with row grouping. This is placed in datatable-buttons.js on line 1564.

Heres some images of it working!
http://prntscr.com/fhx1vu
http://prntscr.com/fhx1ia

    var _exportData = function ( dt, inOpts )
    {

        var config = $.extend( true, {}, {
            rows:           null,
            columns:        '',
            grouped_array_index: [],
            modifier:       {
                search: 'applied',
                order:  'applied'
            },
            orthogonal:     'display',
            stripHtml:      true,
            stripNewlines:  true,
            decodeEntities: true,
            trim:           true,
            format:         {
                header: function ( d ) {
                    return strip( d );
                },
                footer: function ( d ) {
                    return strip( d );
                },
                body: function ( d ) {
                    return strip( d );
                }
            }

        }, inOpts );

        var strip = function ( str ) {
            if ( typeof str !== 'string' ) {
                return str;
            }

            // Always remove script tags
            str = str.replace( /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '' );

            if ( config.stripHtml ) {
                str = str.replace( /<[^>]*>/g, '' );
            }

            if ( config.trim ) {
                str = str.replace( /^\s+|\s+$/g, '' );
            }

            if ( config.stripNewlines ) {
                str = str.replace( /\n/g, ' ' );
            }

            if ( config.decodeEntities ) {
                _exportTextarea.innerHTML = str;
                str = _exportTextarea.value;
            }

            return str;
        };


        var header = dt.columns( config.columns ).indexes().map( function (idx) {
            var el = dt.column( idx ).header();
            return config.format.header( el.innerHTML, idx, el );
        } ).toArray();

        var footer = dt.table().footer() ?
            dt.columns( config.columns ).indexes().map( function (idx) {
                var el = dt.column( idx ).footer();
                return config.format.footer( el ? el.innerHTML : '', idx, el );
            } ).toArray() :
            null;

        var rowIndexes = dt.rows( config.rows, config.modifier ).indexes().toArray();
        var selectedCells = dt.cells( rowIndexes, config.columns );
        var cells = selectedCells
            .render( config.orthogonal )
            .toArray();
        var cellNodes = selectedCells
            .nodes()
            .toArray();

        var grouped_array_index     = config.grouped_array_index;                     //customised
        var no_of_columns           = header.length;
        var no_of_rows              = no_of_columns > 0 ? cells.length / no_of_columns : 0;
        var body                    = new Array( no_of_rows );
        var body_data               = new Array( no_of_rows );                                //customised
        var body_with_nodes         = new Array( no_of_rows );                          //customised
        var body_with_nodes_static  = new Array( no_of_rows );                          //customised
        var cellCounter             = 0;

        for (var i = 0, ien = no_of_rows; i < ien; i++)
        {
            var rows            = new Array( no_of_columns );
            var rows_with_nodes = new Array( no_of_columns );

            for ( var j=0 ; j<no_of_columns ; j++ )
            {
                rows[j]             = config.format.body( cells[ cellCounter ], i, j, cellNodes[ cellCounter ] );
                rows_with_nodes[j]  = config.format.body( cellNodes[ cellCounter ], i, j, cells[ cellCounter ] ).outerHTML;
                cellCounter++;
            }

            body[i]                     = rows;
            body_data[i]                = rows;
            body_with_nodes[i]          = $.parseHTML('<tr class="even">'+rows_with_nodes.join("")+'</tr>');
            body_with_nodes_static[i]   = $.parseHTML('<tr class="even">'+rows_with_nodes.join("")+'</tr>');
        }

        /******************************************** GROUP DATA *****************************************************/
        var row_array                       = dt.rows().nodes();
        var row_data_array                  = dt.rows().data();
        var iColspan                        = no_of_columns;
        var sLastGroup                      = "";
        var inner_html                      = '',
            grouped_index;
        var individual_group_array          = [],
            sub_group_array                 = [],
            total_group_array               = [];
        var no_of_splices                   = 0;  //to keep track of no of element insertion into the array as index changes after splicing one element

        for (var i = 0, row_length = body_with_nodes.length; i < row_length; i++)
        {
            sub_group_array[i]              = [];
            individual_group_array[i]       = [];

            var sGroup                      = '';

            for(var k = 0; k < grouped_array_index.length; k++)
            {
                sGroup                          = row_data_array[i][grouped_array_index[k]];
                inner_html                      = row_data_array[i][grouped_array_index[k]];
                grouped_index                   = k;
                individual_group_array[i][k]    = row_data_array[i][grouped_array_index[k]];
                sub_group_array[i][k]           = sGroup;
            }

            total_group_array[i] = sGroup;


            console.log("grouped_index",grouped_index);

            if ( sGroup !== sLastGroup )
            {
                var table_data              = [];
                var table_data_with_node    = '';

                for(var $column_index = 0;$column_index < iColspan;$column_index++)
                {
                    if($column_index === 0)
                    {
                        table_data_with_node        += '<td style="border-left:none;border-right:none">'+inner_html+'</td>';
                        table_data[$column_index]   = inner_html + " ";
                    }
                    else
                    {
                        table_data_with_node        += '<td style="border-left:none;border-right:none"></td>';
                        table_data[$column_index]   = '';
                    }
                }

                body_with_nodes.splice(i + no_of_splices, 0, $.parseHTML('<tr class="group group_'+grouped_index+' grouped-array-index_'+grouped_array_index[grouped_index]+'">'+table_data_with_node+'</tr>'));
                body_data.splice(i + no_of_splices, 0, table_data);
                no_of_splices++;
                sLastGroup = sGroup;
            }
        }

        return {
            header: header,
            footer: footer,
            body:   body_data
        };
    };

Usage:
Define grouped_array_index in exportOptions

 exportOptions: {
        // Any other settings used
        grouped_array_index: [<place row to use here>],
 },

Editor - Extended ajax URL processing

$
0
0

Currently the ajax processing allows you to specify _id_ in the URL for the row id (based on idSrc option) to be substituted.
e.g.: "/api/resource/_id_" -> "/api/resource/12".

It would be great and much more useful in a REST sense if this could be a bit smarter for more complex URLs.
In many REST API's and following best practices sub resources include a parent resource identifier in the URL.

e.g.: "/api/resource/12/subresource" and"/api/resource/12/subresource/3".

If the ajax URLs could be specified like
"/api/resource/{resourceId}/subresource/{idSrc}" where the string inside {}'s is the name of an Editor data element/field name that would be replaced with the value when resolving the ajax URL.

I currently work around the Editor limitation by using an ajax function to make my own calls to implement the functionality but I think it would be useful to myself and others if something like this was a feature of Editor.


Upload image issue with use .NET ?

$
0
0

# Html Code

Image Column
a b c d d

# Contoller Code

public class CR_AT_ATTACHMENT1Controller : ApiController
{
[Route("api/CR_AT_ATTACHMENT1")]
[HttpGet]
[HttpPost]
public IHttpActionResult CR_AT_ATTACHMENT1()
{
var request = HttpContext.Current.Request;
var settings = Properties.Settings.Default;
string[] pk = new string[5];
pk[0] = "CCT_COUNTRYCODE";
pk[1] = "CCI_CITYCODE";
pk[2] = "CBR_BRANCHCODE";
pk[3] = "CSD_SLIPCODE";
pk[4] = "CIM_IMAGECODE";

        using (var db = new Database(settings.DbType, settings.DbConnection))
        {
            var response = new Editor(db, "CR_AT_ATTACHMENT1", pk)
                 .Where("CCT_COUNTRYCODE", "0001")
                 .Where("CCI_CITYCODE", "0001")
                 .Where("CBR_BRANCHCODE", "0001")
                 .Where("CSD_SLIPCODE", "0000000001")
                //.Where("CIM_IMAGECODE", "0000000001$1")

                .Model<CR_AT_ATTACHMENT1>()
                .Process(request)
                .Data();

            return Json(response);
        }
    }

# Javascript Code

var editor; // use a global for the submit and return data rendering in the CR_AT_ATTACHMENT1s

$(document).ready(function () {
editor = new $.fn.dataTable.Editor({
ajax: "/api/CR_AT_ATTACHMENT1",
table: "#CR_AT_ATTACHMENT1",
fields: [{
label: "First name:",
name: "CCT_COUNTRYCODE"
}, {
label: "Last name:",
name: "CCI_CITYCODE"
}, {
label: "Phone #:",
name: "CBR_BRANCHCODE"
}, {
label: "City:",
name: "CSD_SLIPCODE"
}
,
{
label: "Image:",
name: "image",
type: "upload",
display: function (file_id) {
debugger
return '<img src="' + editor.file('files', file_id).web_path + '"/>';
},
clearText: "Clear",
noImageText: 'No image'
}
]
});

var table = $('#CR_AT_ATTACHMENT1').DataTable({
    dom: "Bfrtip",
    ajax: "/api/CR_AT_ATTACHMENT1",
    columns: [
        { data: "CCT_COUNTRYCODE" },
        { data: "CCI_CITYCODE" },
        { data: "CBR_BRANCHCODE" },
        { data: "CSD_SLIPCODE" }
        ,
        {
            data: "image",
            render: function (file_id) {
                return file_id ?
                    '<img src="' + editor.file('files', file_id).web_path + '"/>' :
                    null;
            },
            defaultContent: "No image",
            title: "Image"
        }
    ],
    select: true,
    buttons: [
        { extend: "create", editor: editor },
        { extend: "edit", editor: editor },
        { extend: "remove", editor: editor }
    ]
});

});

# SQL Data Comes Single Record

CCT_COUNTRYCODE,CCI_CITYCODE,CBR_BRANCHCODE,CSD_SLIPCODE,image
0001 ,0001 ,0001, 0000000001 ,1

Datatables.net throwing TS2339 error with isDataTables on TS 2.3.4

$
0
0

https://stackoverflow.com/questions/44465139/datatables-net-throwing-ts2339-error-with-isdatatables-on-ts-2-3-4

Running Angular 2, Typescript 2.3.4, Node 6.10.3, with datatables.net:

├── @types/jquery.datatables@1.10.36
├── datatables.net@2.1.1
├── datatables.net-buttons@1.3.1
├── datatables.net-buttons-zf@1.3.1
├── datatables.net-responsive@2.1.1
├── datatables.net-responsive-zf@2.1.1
├── datatables.net-zf@2.1.1

The toggleTable code started throwing TS2339:

error TS2339: Property 'isDataTable' does not exist on type '{ (param?: ResponsiveDataTablesSettings): DataTable; (param?: Settings): DataTable; }'.

toggleTable() {
    if (! $.fn.DataTable.isDataTable('#sample-table')) {
        this.setupSampleTable();
    }
    this.table = !this.table;
}

The relevant section of node_modules/@types/jquery.datatables/index.d.ts is:

interface JQuery {
    DataTable(param?: DataTables.Settings): DataTables.DataTable;
}

export interface StaticFunctions {
    /**
    * Check is a table node is a DataTable or not
    *
    * @param table Selector string for table
    */
    isDataTable(table: string): boolean;

How do I fix the type on DataTable?

Column sorting requires 2 clicks

$
0
0

(I'm using the sample code from the site)
On loading a webpage, I can click the first column and it will sort, and after that, all the other column sorting works.
But if I load the webpage and click on column 2+ first, it doesn't sort until I click it again.
It was working yesterday, but today it's not working.
I just tested it again and the problem is more complex, it's hard to determine the exact behavior, some columns won't sort on first click even after sorting the first column if data 1 is at the top.
I'm not using any themes atm to test where this problem is coming from, and it wasn't the theme. I am literally using the sample code provided from the website.
I have a more complex site experiencing this same problem, so I created a test page with only the sample code and the problem is coming from the library, not my code.
Is anyone else experiencing this?

Different column layout for display vs export

$
0
0

Hi there,

I've got a table and it's fairly wide. Because of its width, we've chosen to combine some of the data. For example, the Address, City, State, and Zip variables are all presented in the same column:

[Address]
[City], [State] [Zip]

and similar for the daytime and evening phone numbers.

However, our users want those to be separate columns when they export to Excel or CSV.

At the moment, I'm handling it using the orthogonal attribute:

var spreadsheetOptions = {
  columns: [
    [...]
    'address:name',
    'city:name',
    'state:name',
    'postal:name',
    'workPhone:name',
    'homePhone:name',
    [...]
  ],
  rows: { selected: true },
  orthogonal: 'export'
};

[...]

var t = $('table').DataTable({

  [...]

  columns: [
    [...]
    {
      // Show Address<br/>City, State Zip on page/print,
      // just street address on spreadsheet export
      title: 'Address',
      name: 'address',
      data: {
        '_': function(data, type) {
          return type === 'export'
          ? data.address
          : data.address + ' <br/>' + data.city + ', ' + data.state + ' ' + data.postal;
        },
        sort: 'postal'
      },
      className: 'address'
    },{
      // City column for spreadsheet export
      title: 'City',
      name: 'city',
      data: 'city',
      className: 'hidden-modal',
      visible: false
    },{
      // State column for spreadsheet export
      title: 'State',
      name: 'state',
      data: 'state',
      className: 'hidden-modal',
      visible: false
    },{
      // Zip column for spreadsheet export
      title: 'Zip',
      name: 'postal',
      data: 'postal',
      className: 'hidden-modal',
      visible: false
    },{
      // Show Day<br/>Evening phone number as links on page/print
      title: 'Day<span class="visible-modal-inline">:</span> <br />Evening',
      name: 'phone',
      data: function(data) {
        var phones = '-';
        if(data.workPhone) {
          var phoneLink = parsePhoneLink(data.workPhone),
            phoneDisplay = parsePhoneDisplay(data.workPhone);
          phones = '<a href="tel:' + phoneLink + '">' + phoneDisplay + '</a>';
        }
        phones += ' <br/>';
        if(data.homePhone) {
          var phoneLink = parsePhoneLink(data.homePhone),
            phoneDisplay = parsePhoneDisplay(data.homePhone);
          phones += '<a href="tel:' + phoneLink + '">' + phoneDisplay + '</a>';
        } else {
          phones += '-';
        }
        return phones;
      },
      className: 'phone'    // no num-fmt because sometimes '-'; should center-align
    },{
      // Daytime Phone column for spreadsheet export
      title: 'Daytime Phone',
      name: 'workPhone',
      data: function(data, type) {
        if(type === 'export' && data.workPhone) {
          return parsePhoneDisplay(data.workPhone);
        }
        return '-';
      },
      visible: false,
      className: 'hidden-modal'
    },{
      // Evening Phone column for spreadsheet export
      title: 'Evening Phone',
      name: 'homePhone',
      data: function(data, type) {
        if(type === 'export' && data.homePhone) {
          return parsePhoneDisplay(data.homePhone);
        }
        return '-';
      },
      visible: false,
      className: 'hidden-modal'
    }
    [...]
  ],
  [...]
  buttons: [{
    extend: 'excel',
    exportOptions: spreadsheetOptions
  },{
    extend: 'csv',
    exportOptions: spreadsheetOptions
  }]
});

The downside to this approach is that I'm reading the city, state, postal, workPhone, and homePhone values in twice, and adding them all to the DataTables object in two different places. This has a noticeable impact on performance for larger tables (and some of our users have thousands of rows in their tables).

Is there another way of doing this? Is there a way I can read those values in once, and then combine multiple values into a single column in the browser but put them in separate columns on export?

Thanks.

Dynamically generating columns

$
0
0

I am looking to pivot an MJoined datasource. I have selected Users from my system, and MJoined Schedules related to that user. What I am left with is a dataset of Users, and their associated scheduling (# hours per week). Here's a sample set of my JSON:

{
  "draw": null,
  "data": [
    {
      "DT_RowId": "row_1",
      "User": {
        "ID": 1,
        "firstMidName": "Harry",
        "lastName": "Twyford"
      },
      "Schedule": [
        {
          "week_ending": "2017-05-26",
          "JobID": 14,
          "hours": 40
        },
        {
          "week_ending": "2017-06-02",
          "JobID": 14,
          "hours": 50
        }
      ]
    },
    {
      "DT_RowId": "row_2",
      "User": {

etc...

I want to display this data as one row for each user, with columns extending out for each week_ending entry. I am having trouble coming up with a way to define my DataTables columns.data() columns dynamically, with one column for each week. This is what I have so far:

var builtColumns = [];
$('#schedulingTable').on('xhr.dt', function (e, settings, json, xhr) {
      builtColumns = constructColumns(json);
});
$('#schedulingTable').DataTable({
    dom: "Bfrtip",
    ajax: {
        url: ajaxUrl,
        data: { id: id },
    },
    //is this valid? Assigning an existing array to columns?
    columns: builtColumns,
    });
});

function constructColumns(json) {
    var currentHighest = 0;
    for (var row in json.data) {
        var weekCount = Object.keys(json.data[row].Schedule).length;
        if (weekCount > currentHighest) { currentHighest = weekCount; }
    }
    var column0 =
        {  //first column is always the User
            data: "User",
            render: function (data, type, full, meta) {
                return data.firstMidName + ' ' + data.lastName;
            }
        };
    var columns = [];
    columns[0] = column0;
    //one column for every week_ending entry.
    //as many columns as the highest number of week_endings across all the rows.
    for (var i = 1; i <= currentHighest; i++) {
        columns[i] =
            {
                data: "Schedule[" + i + "].hours"
            };
    };
    return columns;
}

I have a couple of problems:
- is this even possible? Creating an array, then just assigning it to columns?
- the XHR event doesn't seem to be firing at all. Advice?

Edit: I would like for this to eventually become an Editor table, looking like this:

-----------------------------------------------------------------
User                      May 26                 June 3          ...
-----------------------------------------------------------------
Harry Twyford       40                         30
-----------------------------------------------------------------
Bob Smith             40                         30
-----------------------------------------------------------------

Where the hour values can be edited. If you have any advice on how to tackle this, I'd be grateful. Otherwise, I'll just tackle that when I can even get the DataTable running.

Viewing all 82686 articles
Browse latest View live


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