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

Button Actions Quit Working When Using Web Service

$
0
0

I am using SmartAdmin Angular 5 framework 1.9.1, which provides DataTables capabilities. I have installed DataTables 1.10.18, and Select 1.2.6.

My app can use either test data, or data from a web service. When I use test data, all works fine with the Delete and Archive buttons - meaning, the button action events are fired. But, when using web service data, the Delete and Archive buttons do not fire the button actions.

You can try my app at:
tanglemydata.com

To see problem, do this:

  1. Use latest Chrome or Firefox (no mobile), make browser window wide enough to see the buttons (as shown below).
  2. Login - I've hard-coded in the login credentials.
  3. Click Notifications in left pane.
  4. Expand General Messages, wait for table to display. Data comes from web service.
  5. Select one or multiple rows.
  6. Click Delete or Archive buttons - you should see a YES/NO dialog, it does not work.
  7. Expand Colleagues, then expand Colleague Messages, wait for table to display. Test data is hard-coded.
  8. Select one or multiple rows.
  9. Click Delete or Archive buttons - you should see a YES/NO dialog, it does work.

Looking at the .ts code line 145, you see that I go through a table.clear().rows.add(data_from_web_service).draw() operation. I tried it w/wo clear(), but same problem.

I have the following component.ts code:

import { NgModule, Component, OnInit, Injectable, Inject, ViewChild, DoCheck } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';

import { FadeInTop } from "../shared/animations/fade-in-top.decorator";
import { NotificationsService } from './notifications.service';
import { NotificationService } from '../shared/utils/notification.service';
import { DatatableComponent } from '../shared/ui/datatable/datatable.component';

declare let $:any;

@FadeInTop()
@Component({
  selector: 'sa-datatables-case',
  templateUrl: './notifgenmsg.component.html',
  styleUrls: ['../../assets/css/tmd_basic.css']
})
  
@Injectable()  
export class NotifGenMsgComponent implements OnInit, DoCheck {
  @ViewChild(DatatableComponent) ngxDatatableComponent: DatatableComponent;
  
  public genMsgs: any;
    
  constructor(
    private router: Router,  
    private notificationsService: NotificationsService, //TMD version
    private notificationService: NotificationService   //SA version used for dialogs
  ) {}
  
  ngOnInit() {  
    //###console.log("NotifGenMsgComponent ngOnInit - ENTRY");
  
    //this allows the router.navigate to re-call this component, providing fresh data
    this.router.routeReuseStrategy.shouldReuseRoute = function(){
       return false;
    };
    
    //this kicks-off the web service call for data, when data is returned the (val) block is reached then refreshDataTable() is called 
    this.getNotifGenMsgData();
        
    //###console.log("NotifGenMsgComponent ngOnInit - EXIT");
  }
  
  ngDoCheck() {
    //this is called after ngOnInit - see https://codecraft.tv/courses/angular/components/lifecycle-hooks/
  }
   
  handleButtons() {
    //###console.log('handleButtons');
    if($(this.ngxDatatableComponent)) {   
      if($(this.ngxDatatableComponent).DataTable) {
         console.log('processing button clicks');
        
         const ngxDataTable = $($(this.ngxDatatableComponent).DataTable.tables()).DataTable();
        
         const deleteBtnNum = 4;
         const archiveBtnNum = 5;
        
         ngxDataTable.button(deleteBtnNum).action(() => { //lambda expression provides access to outer this, but inner this is not accessible
            //###console.log( this.text() +' button was clicked' ); //will not work when using lambda expression
            console.log('Delete button clicked');
                       
            const selection = ngxDataTable.rows({ selected: true } ).data().toArray();
            this.doSelection(selection, 'Delete');
         });
                  
         ngxDataTable.button(archiveBtnNum).action(() => { //lambda expression provides access to outer this, but inner this is not accessible
            //###console.log( this.text() +' button was clicked' ); //will not work when using lambda expression
            console.log('Archive button clicked');
                       
            const selection = ngxDataTable.rows({ selected: true } ).data().toArray();
            this.doSelection(selection, 'Archive');
         });
        }    
      }
   }
           
   doSelection(selection: any, buttonName: String) {
     
     //remove after testing
     let rowStr = "";     
     for (const row of selection) {
       rowStr += row.rowid +",";
     }
     rowStr = rowStr.substring(0, rowStr.lastIndexOf(","));
     
     const content = "Do you want to " +buttonName +" the " +selection.length +" rows selected?";
     this.notificationService.smartMessageBox({
       title : "<i class='fa fa-question-circle txt-color-yellow'></i> " +buttonName +" <span class='txt-color-white'><strong>" + $('#show-shortcut').text() + "</strong></span>",
       content : content,
       buttons : '[No][Yes]'

     }, (ButtonPressed) => {
       if (ButtonPressed === "Yes") {
         //###console.log(buttonName +' selected rows');
         //call appropriate web service
        
         for(let i=0; i<selection.length; i++) { 
           //###console.log("row having database ID " +selection[i].rowid +" selected for " +buttonName); 
         }
       }
     });
    }
  
   getNotifGenMsgData() {  
      //###console.log("NotifGenMsgComponent getNotifGenMsgData - ENTRY");
          
      const TESTING = false;        
      if(TESTING) {
        //###console.log("NotifGenMsgComponent getNotifGenMsgData - ############# USING TEST DATA");
        const resStr = '['
                     + '{"checked":null,"rowid":"14","personID":"ALL","senderID":"ADMIN","message":"TEST DATA10 - TangleMyData has an outage planned for November 15, 2018 from 1:00 UTC until 2:00 UTC.","messageStatus":"NEW","messagePrimType":"SYSTEM","messageSubType":"GENERAL","dateExpires":"2018-11-15 09:02:37","dateCreated":"2018-11-05 09:02:37","dateLastUpdate":"2018-11-08 01:19:10"},'
                     + '{"checked":null,"rowid":"15","personID":"ALL","senderID":"ADMIN","message":"TEST DATA11 - TangleMyData has an outage planned for November 15, 2018 from 1:00 UTC until 2:00 UTC.","messageStatus":"NEW","messagePrimType":"SYSTEM","messageSubType":"GENERAL","dateExpires":"2018-11-15 09:02:37","dateCreated":"2018-11-05 09:02:37","dateLastUpdate":"2018-11-08 01:19:10"},'
                     + '{"checked":null,"rowid":"16","personID":"ALL","senderID":"ADMIN","message":"TEST DATA12 - TangleMyData has an outage planned for November 15, 2018 from 1:00 UTC until 2:00 UTC.","messageStatus":"NEW","messagePrimType":"SYSTEM","messageSubType":"GENERAL","dateExpires":"2018-11-15 09:02:37","dateCreated":"2018-11-05 09:02:37","dateLastUpdate":"2018-11-08 01:19:10"}'
                     + ']';
        this.genMsgs = JSON.parse(resStr);
      } else {
          this.notificationsService.getNotifGenMsgData().then(
            (val) => {
               this.genMsgs = this.notificationsService.genMsgs;
               if (this.genMsgs) {
                  console.log("NotifGenMsgComponent getNotifGenMsgData - genMsgs is not null");
                  this.refreshDataTable();
               } else {
                  //###console.log("NotifGenMsgComponent getNotifGenMsgData - genMsgs is null");
               }  
               this.router.navigate(['/notifgenmsg']);  
            },
            (err) => {
               //###console.log("NotifGenMsgComponent getNotifGenMsgData - error: " +err);
            }
          );        
      }
          
      //###console.log("NotifGenMsgComponent getNotifGenMsgData - EXIT");
   }
  
   refreshDataTable() {
     if($(this.ngxDatatableComponent)) {   
       if($(this.ngxDatatableComponent).DataTable) {
         console.log('refreshing ngxDataTable #####################');
        
         const ngxDataTable = $($(this.ngxDatatableComponent).DataTable.tables()).DataTable();   
         ngxDataTable.clear().rows.add(this.genMsgs).draw();
       }
     }
   }
        
}

Here's a screen shot of my General Messages table:

Thanks,
Bob


Creating DataTable inside a child row where main table uses row grouping

$
0
0

Hi,

Has anyone else come across a situation where you are creating a DataTable in a childrow on the fly and if the main table uses RowGrouping - every time you initialize the DT in the child row it adds an extra RowGroup header to the parent.

I thought the child data was a separate instance and wouldn't affect the parent, but it seems not to be? Or is the rowGroup on the parent being confused by the child table existing..

Any suggestions for workarounds would be appreciated.

2 table droag and drop

$
0
0

Hi guys

Hope you are all well.

Hope you can help me with this again. Can i have 2 tables then from 1 table to another table drag and drop multiple selected records. Please help. thanks so much for always helping me.
Hope you all enjoy your christmas. be happy always.

Cannot Commit Changes

$
0
0

I followed the blog post about parent child tables and I am able to get the two tables to reflect each other however when I make changes to the child table no errors are thrown and no changes committed.

                $( document ).ready( function () {
                            var schedEditor = new $.fn.dataTable.Editor( {
                                ajax: "rest/getScheds2.php",
                                table: "#schedTable",
                                idSrc: 'schedules.idschedules',
                                fields: [ {
                                    label: "id:",
                                    name: "schedules.idschedules"
                                },{
                                    label: "Name:",
                                    name: "schedules.schedname"
                                },{
                                    label: "From:",
                                    name: "schedules.seasonfrom"
                                },{
                                    label: "To:",
                                    name: "schedules.seasonto"
                                } ]
                            } );
                
                            var schedTable = $( '#schedules' ).DataTable( {
                                dom: "Bfrtip",
                                ajax: "rest/getScheds2.php",
                                idSrc: 'schedules.idschedules',
                                columns: [ {
                                    data: 'schedules.idschedules'
                                }, {
                                    data: 'schedules.schedname'
                                },{
                                    data: 'schedules.seasonfrom'
                                } ,{
                                    data: 'schedules.seasonto'
                                }],
                                select: {
                                    style: 'single'
                                },
                                buttons: [ {
                                    extend: "create",
                                    editor: schedEditor
                                }, {
                                    extend: "edit",
                                    editor: schedEditor
                                }, {
                                    extend: "remove",
                                    editor: schedEditor
                                } ]
                            } );
                
                
                            var timesEditor = new $.fn.dataTable.Editor( {
                                ajax: {
                                    url: 'rest/getTimes.php',
                                    data: function ( d ) {
                                        var selected = schedTable.row( {
                                            selected: true
                                        } );
                                        if ( selected.any() ) {
                                            d.idsched = selected.data().id;
                                        }
                                    }
                                },
                                table: '#times',
                                fields: [ {
                                    label: "Day:",
                                    name: "schedtimes.dayofweek"
                                }, {
                                    label: "From:",
                                    name: "schedtimes.fromtime"
                                }, {
                                    label: "To:",
                                    name: "schedtimes.totime"
                                },{
                                    label: "id:",
                                    name: "schedtimes.idsched"
                                }
                                        ]
                            } );
                
                            var timesTable = $( '#times' ).DataTable( {
                                dom: 'Bfrtip',
                                ajax: {
                                    url: 'rest/getTimes.php',
                                    type: 'post',
                                    data: function ( d ) {
                                        var selected = schedTable.row( {
                                            selected: true
                                        } );
                                        if ( selected.any() ) {
                                            //console.dir(selected.data());
                                            //alert(selected.data()['schedules']['idschedules']);
                                            d.idsched = selected.data()['schedules']['idschedules'];
                                        }
                                    }
                                },
                                columns: [ {
                                    data: 'schedtimes.dayofweek'
                                }, {
                                    data: 'schedtimes.fromtime'
                                }, {
                                    data: 'schedtimes.totime'
                                }],
                                select: true,
                                buttons: [ {
                                    extend: 'create',
                                    editor: timesEditor
                                }, {
                                    extend: 'edit',
                                    editor: timesEditor
                                }, {
                                    extend: 'remove',
                                    editor: timesEditor
                                } ]
                            } );
                
                
                            schedTable.on( 'select', function () {
                                timesTable.ajax.reload();
                
                                timesEditor
                                    .field( 'schedtimes.idsched' )
                                    .def( schedTable.row( {
                                        selected: true
                                    } ).data().id );
                            } );
                
                            schedTable.on( 'deselect', function () {
                                timesTable.ajax.reload();
                            } );
                
                            timesEditor.on( 'submitSuccess', function () {
                                schedTable.ajax.reload();
                            } );
                
                            schedEditor.on( 'submitSuccess', function () {
                                timesTable.ajax.reload();
                            } );
                        } );
                    </script>

I have also enabled debug mode but when I attempt to update a value no data is sent. I am lost. Any help would be appreciated.
Thanks!

the code are not worked at my table

$
0
0

// DataTable
var table = $('#finder').dataTable({
processing: true,
serverSide: true,

ajax: {
    url: "../jecom_api/xhr_finder_datatables",
    type: "POST"
    }
}

});

// Apply the search
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on('keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );

Datatable - Sorting not working and icon are not coming

$
0
0

please help me in this. I have tried my level best to for SORTING to work. Whenever any column header is clicked, I goes to server side but all the values comes as NULL e.g. start, length, draw, sortColum. this is happening when clicked on header only. Pagination is working fine.

Any help is appreciated.

Client side code

var dataTable = $('#SettlementTable').DataTable({
    "processing": true, // for show progress bar
    "serverSide": true, // for process server side
    "filter": true, // this is for disable filter (search box)
    "orderMulti": false, // for disable multiple column at once
    destroy: true,
    "language": {
        "zeroRecords": "<center>No record(s) found !</center>"
    },
    "ajax": {
        "url": "http://localhost/Payments.Productization.GlobalPaymentUI/Home/LoadData",
        "type": "POST",
        "datatype": "json",
        "data": function (d) {
            d.region = $("#region").val();
            d.country = $("#country").val();
            d.paymentType = $("#paymentType").val();
            d.searchGroup = $("#SearchGroup").val();
            d.searchValue = $("#txtSearch").val();
        },
        dataSrc: function (response) {
            if (response.status === "success") {
                $("#seachResult").show();
                return response.data;
            } else {
                $("#SettlementTable_processing").hide();
                showErrorMessage(response.error);
                return null;
            }
        }
    },
    "columns": [
        {
            "class": "details-control",
            "data": null,
            "orderable": false,
            "defaultContent": ""
        },
        { "data": "country", "orderable": true },
        { "data": "boNumber", "orderable": true },
        { "data": "foNumber", "orderable": true},
        { "data": "dpid", "orderable": true},
        { "data": "customer", "orderable": true},
        { "data": "totalAmount", "orderable": true },
        { "data": "invoiceNumber", "orderable": true},
        { "data": "creditMemo", "orderable": true },
        { "data": "orderStatus", "orderable": true },
        { "data": "orderDate", "orderable": true }
    ],
    "order": [[3, "desc"]]
});

Server SideCode

var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
// Skiping number of Rows count
var start = Request.Form["start"].FirstOrDefault();
// Paging Length 10,20
var length = Request.Form["length"].FirstOrDefault();
// Sort Column Name
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
// Sort Column Direction ( asc ,desc)
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
// Search Value from (Search box)
var searchValue = Request.Form["search[value]"].FirstOrDefault();

Apostrophe in saved text input

$
0
0

Using Editor Datatables if I enter:

Testing Apostrophe's out

It is saved as

Testing Apostrophe\'s out

I saw some forum posts about Magic Quotes, but I'm using PHP 7.14 so that should rule that feature out.

Any ideas about this appreicated.

Thanks

Bootstrap 4.2.1 doesn't work with DataTables

$
0
0

A few days ago was realised a new version of Bootstrap (4.2.1) and it doesn't work with DataTables 1.10.19. Can you make a correction, or tell me what to change to get back working? Thx


http://datatables.net/tn/7

$
0
0

staff.php is not found (error 404)
the path is correct and i edited config.php
and the problem is still
the project is here is google drive
https://drive.google.com/drive/folders/1YRqifiPNuMzgT6sySoKs_fBGheUre2sz?fbclid=IwAR0dUqDGFsJkoTN5utZIYuSgglFu78CT4bnoGYTUARNGrx2pTV-pOPi6sf8
staff.php
[code]
<?php

/*
* Example PHP implementation used for the index.html example
*/

// DataTables PHP library
include( "../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, 'students' )
->fields(
Field::inst( 'name' )
->validator( Validate::notEmpty( ValidateOptions::inst()
->message( 'A first name is required' )
) ),
Field::inst( 'std_code' )
->validator( Validate::notEmpty( ValidateOptions::inst()
->message( 'A code is required' )
) ),
Field::inst( 'id_num' ),
Field::inst( 'birth_date' )
->validator( Validate::dateFormat( 'Y-m-d' ) )
->getFormatter( Format::dateSqlToFormat( 'Y-m-d' ) )
->setFormatter( Format::dateFormatToSql('Y-m-d' ) ),
Field::inst( 'address' ),
Field::inst( 'phone' ),
Field::inst( 'enroll_date' )
->validator( Validate::dateFormat( 'Y-m-d' ) )
->getFormatter( Format::dateSqlToFormat( 'Y-m-d' ) )
->setFormatter( Format::dateFormatToSql('Y-m-d' ) )

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

[/code]

config.php
[code]
<?php if (!defined('DATATABLES')) exit(); // Ensure being used in DataTables env.

// Enable error reporting for debugging (remove for production)
error_reporting(E_ALL);
ini_set('display_errors', '1');

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Database user / pass
*/
$sql_details = array(
"type" => "Mysql", // Database type: "Mysql", "Postgres", "Sqlserver", "Sqlite" or "Oracle"
"user" => "root", // Database user name
"pass" => "", // Database password
"host" => "localhost", // Database host
"port" => "", // Database connection port (can be left empty for default)
"db" => "fac_sys", // Database name
"dsn" => "charset=utf8mb4", // PHP DSN extra information. Set as charset=utf8mb4 if you are using MySQL
"pdoAttr" => array() // PHP PDO attributes array. See the PHP documentation for all options
);

// This is included for the development and deploy environment used on the DataTables
// server. You can delete this block - it just includes my own user/pass without making
// them public!
if ( is_file($_SERVER['DOCUMENT_ROOT']."/datatables/pdo.php") ) {
include( $_SERVER['DOCUMENT_ROOT']."/datatables/pdo.php" );
}
// /End development include

[/code]

How can I change the text "No data available in table"

$
0
0

Hi all!

I try to change the text "No data available in table".
I tried:
$(".dataTables_empty").text("There are currently no xyz available for this.");

and

$(".dataTables_empty").html("There are currently no xyz available for this.");

but no success :(

best greetings and thank you in advance!

Wait until the table is completly loaded -> Than hide the loading div

$
0
0

Hi!

I show up a loading message (show_loading_message();) before I perform an ajax action. After the ajax was successfully done I reload the datatable.

than I am hiding the loading message (hide_loading_message();). The Problem is that I am hiding it too early. How could I wait hiding the loading messsage until the datatable is completly loaded?

    show_loading_message();   

                $.ajax({
                    url:          'data.php?job=mass_cond',
                    type:         'POST' , 
                    data:         {
                        id : res.val() , conditionselected : conditionselected2,
                    } , 
                    success : function(response){
                      console.log(response);
                      var res = $.parseJSON(response);
                      if (res.result) {
                        table_xyz.ajax.reload(function(){

                        } , false);
                      show_message('success.', 'success');
                      }
                      else{

                      }
                      hide_loading_message();

how could I fix this? thank you in advance!

different design in Forms to create/view new records.

$
0
0

Hi, I need to create a form, but the form to create a new record, should be distributed in different columns, different rows, and the data show in the same form, with the pagination to go to the next one.
that is, I do not want the view in tables.

How to fix data not displaying on DataTable

$
0
0

I've just recently discovered DataTables and would like to implement in my web. Followed the instructions for SSP data but it failed to output my data.

I've tried some of the solutions from several other websites but none works.

index.php

<script>
function() {
$('#staff').DataTable( {
    processing: true,
    serverSide: true,
    ajax: {
        url: 'data.php',
        type: 'POST'
    };
} );
}
</script>

data.php

<?php

$table = 'staff';

$primaryKey = 'staff_id';

 $columns = array(
array( 'db' => 'staff_id', 'dt' => 0 ),
array( 'db' => 'grade',  'dt' => 1 ),
array( 'db' => 'name',   'dt' => 2 ),
array( 'db' => 'position',     'dt' => 3 ),
array( 'db' => 'cost_centre',     'dt' => 4 ),
array( 'db' => 'station',     'dt' => 5 ),
array( 'db' => 'ic_number',     'dt' => 6 ),
array( 'db' => 'status',     'dt' => 7 )
);

// SQL server connection information
$sql_details = array(
'user' => 'root',
'pass' => '',
'db'   => 'feldatransport',
'host' => 'localhost'
);

require( 'ssp.class.php' );

echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
?>

I would like the data to display in my staff table.

Is it possible to have paging on footer?

$
0
0

I want to know if is it possible to do it, due I would like to have thead and tfoot sticky with paging on footer.

Editor Manuel İnsert command

$
0
0

do I use the datatables in database class manually

insert 
update 
delete
select 
row count 

how use this ?

how to get the error codes ?


My filter by column doesn't work

$
0
0

I really appreciate if anyone could help me with my datatable because it is not working and I don't know why, Post my code below.

                detalle = $("#detalle-table").DataTable({
                    "ajax": {
                        url: "ajax/cargar_reportedetalle",
                        type: "POST",
                        data: {
                            idsocio: idsocio,
                            idusuario: idusuario
                        },
                        dataSrc: "",
                        complete: function(data){
                            if(Object.keys(data.responseJSON).length == 3){
                                var mensaje = data.responseJSON.mensaje;
                                if(mensaje != null){
                                    alert(mensaje);
                                }
                            }
                        }
                    },
                    columns: [
                        { data: "contador" },
                        { data: "idtipounidad" },
                        { data: "idunidad" },
                        { data: "idcarroceria" },
                        { data: "noeconomico" },
                        { data: "marca" },
                        { data: "modelo" },
                        { data: "placas" },
                        { data: "tipounidad" },
                        { data: "socio" },
                        { data: "km" },
                        { data: "estatus" },
                        { data: "serie"}
                    ],
                    columnDefs: [
                        { className: "cssbold text-center", targets: [0] },
                        { className: "text-center", targets: "_all" },
                        { "targets": [ 1 ], "visible": false },
                        { "targets": [ 2 ], "visible": false },
                        { "targets": [ 3 ], "visible": false }
                    ],

                    initComplete: function () {
                        var r = $('#detalle-table tfoot tr');
                        r.find('th').each(function(){
                            $(this).css('padding', 8);
                        });
                        $('#detalle-table thead').append(r);
                        detalle.columns().every( function () {
                            var that = this;

                            $( 'input', this.footer() ).on( 'keyup change', function () {
                                if ( that.search() !== this.value ) {
                                    that
                                    .search( this.value )
                                    .draw();
                                }
                            } );
                        } );
                    },
                    autoWidth: false,
                    searching: false,
                    info: false,
                    pageLength: 10,
                    pagingType: "full_numbers",
                    fixedHeader: {
                        header: true,
                        footer: true
                    }
                });
            });

            var contador = 0;
            $('#detalle-table tfoot th').each( function () {
                var title = $(this).text();
                if(contador > 0){
                    $(this).html('<input type="text" id="filtro' + contador + '" class="form-control form-control-sm"' 
                        + 'style="width: 100%;" placeholder="Buscar ' + title + '" />');
                }
                contador++;
            } );

uncaught exception: Unable to automatically determine field from source.

$
0
0

Hopefully this will be a quick fix... hopefully

Full error I'm getting: "uncaught exception: Unable to automatically determine field from source. Please specify the field name"

I have a datatable with a field showing the concatenation of three fields, using the following:

   var table = $('#example').DataTable( {
      dom: "Bfrtip",
      ajax: "../server_side/scripts/ET_ASBresultsForBuilding.php?jobRef=P18-00053",
      iDisplayLength: 25,
      columns: [
         { data: null, render: function ( data, type, row ) {
                return data.tblASBassets.roomLocation;
            } },
         { data: null, render: function ( data, type, row ) {
                return data.tblASBassets.area + ', ' +data.tblASBassets.item + ', ' + data.tblASBassets.material;
            }, editField: null },

on the editor I've listed the three fields:

   editor = new $.fn.dataTable.Editor( {
      ajax: "../server_side/scripts/ET_ASBresultsForBuilding.php?jobRef=P18-00053",
      table: "#example",
      fields: [ { name: "tblASBassets.roomLocation", type: "display" },
                { name: "tblASBassets.area", type: "display" }, 
                { name: "tblASBassets.item", type: "display" }, 
                { name: "tblASBassets.material", type: "display" },

When I click on the datatable's field

I get the following

I know it's something to do with the editor trying to find the corresponding Editor Field - but because it's three fields in 1 I get the exception error.... all I want to do really is say - just show this at text - I don't want to edit it.

Anyone got any ideas? As ypou ca see I even tried setting the editfield parameter to null with no effect

Thank you in advance for any help given

How to control editor window width with jqueryui / editor template

$
0
0

Hi Allan,

I am using jqueryui, and have a complex form I want to use an editor template with. Following the instructions at https://editor.datatables.net/manual/templates I created a template, but quickly realized that since I'm not using lightbox the class configuration under Lightbox customisation section wouldn't work.

I reverse engineered what you are doing within editor.jqueryui.js, and it looks like the .dialog widget is initialized using Editor.display.jquery.modalOptions which is configured to have width of 600px.

It seems like I cannot override this in my javascript because the dialog is created on initialization. Is there a reason the width needs to be hard-configured? Or is there any way to override this that I'm missing?

BTW, seems to work a little better which changing the 600 to 'auto' using the debugger, but maybe there's something still not quite right with position.

Bug: Editor ignores WHERE-clause in LEFTJOIN Update

$
0
0

I am using this statement to SELECT and UPDATE contract approvals. While the statement selects data from multiple tables it only updates one table called contract_has_rfa. The two key tables are contract and contract_has_rfa. There can be multiple rfa's for one contract, but only one for a contract and one user (unique index on contract_has_rfa.contract_id and contract_has_rfa.approver_id). The link to the contract table is through contract.id as a foreign key (contract_has_rfa.contract_id.
Contract_has_rfa is also linked to the user table with user.id which is contract_has_rfa.approver_id in contract_has_rfa.

The statement selects all contracts that are assigned to the respective user ($_SESSION['id']) for approval. This works fine. Only the assigned contracts are selected not all of them. When making the update (setting contract_has_rfa.status to 'W', 'N' or 'A') there is a bug: The UPDATE statement does NOT contain the approver_id in its WHERE clause. It only has the respective contract.id in its WHERE clause. Hence all rfa's get updated for the respective contract - even those assigned to a different user!
The bug is that the UPDATE statement generated by Editor ignores this WHERE clause in my PHP statement below:

 ->where( 'contract_has_rfa.approver_id', $_SESSION['id'] )

while the SELECT statement uses it. I used the debug option to check the UPDATE statement generated by Editor to verify this.

Is there a fix for this bug? I would like to avoid a work around if possible.

<?php

Editor::inst( $db, 'contract' )
->field(
    Field::inst( 'gov.name' )->set( false ),
    Field::inst( 'govdept.name' )->set( false ),
    Field::inst( 'creditor.name' )->set( false ),
    Field::inst( 'contract.id' )->set( false ),
    Field::inst( 'contract.description' )->set( false ),
    Field::inst( 'contract_has_rfa.status' )
        ->setFormatter( function ( $val, $data, $opts ) {
            if ($val === 'W' &&  $data['contractStatusAlias'] === 'N') {
                $val = 'N';
            }
            return $val;
        } ),        
    Field::inst( 'contract_has_rfa.status AS contractStatusAlias' )->set( false ),
    Field::inst( 'contract_has_rfa.update_time' )->set(Field::SET_BOTH)
                                                 ->setValue( date("Y-m-d H:i:s") ),
    Field::inst( 'contract_has_rfa.updater_id' )->set(Field::SET_BOTH)
                                                ->setValue( $_SESSION['id'] )
)
// show approvals if any                   
->join(
Mjoin::inst( 'user' )
    ->link( 'contract.id', 'contract_has_rfa.contract_id')
    ->link( 'user.id', 'contract_has_rfa.approver_id' )
    ->order( 'contract_has_rfa.status DESC, user.lastname ASC' )
    ->fields(
        Field::inst( 'user.firstname AS userFirstName' )->set( false ),
        Field::inst( 'user.lastname AS userLastName' )->set( false ),
        Field::inst( 'contract_has_rfa.status AS approvalStatus' )->set( false ),
        Field::inst( 'contract_has_rfa.update_time AS updateTime' )->set( false )
            ->getFormatter( function ( $val, $data, $opts ) {
                return getFormatterDateTime($val);                 
            } )
    )
)
->join(
Mjoin::inst( 'file' )
    ->link( 'contract.id', 'contract_has_file.contract_id' )
    ->link( 'file.id', 'contract_has_file.file_id' )
    ->fields(
        Field::inst( 'web_path' )->set( false ),
        Field::inst( 'name' )->set( false )               
    )
)
->leftJoin( 'govdept', 'contract.govdept_id', '=', 'govdept.id')
->leftJoin( 'gov', 'govdept.gov_id', '=', 'gov.id')
->leftJoin( 'creditor', 'contract.creditor_id', '=', 'creditor.id')
->leftJoin( 'contract_has_rfa', 'contract.id', '=', 'contract_has_rfa.contract_id')
->leftJoin( 'user', 'contract_has_rfa.approver_id', '=', 'user.id')
->where( 'contract_has_rfa.approver_id', $_SESSION['id'] )
->debug(true)
->process($_POST)            
->json();

This is the SQL for the UPDATE generated by Editor:

bindings: [{name: ":status", value: "A", type: null},…]
0:{name: ":status", value: "A", type: null}
name:":status"
type:null
value:"A"
1:{name: ":update_time", value: "2017-05-07 16:16:59", type: null}
name:":update_time"
type:null
value:"2017-05-07 16:16:59"
2:{name: ":updater_id", value: "37", type: null}
name:":updater_id"
type:null
value:"37"
3:{name: ":where_0", value: "25", type: null}
name:":where_0"
type:null
value:"25"
query:"UPDATE  `contract_has_rfa` 
SET  `status` = :status, `update_time` = :update_time, `updater_id` = :updater_id 
WHERE `contract_id` = :where_0 "

And this is the result in the table contract_has_rfa:

CONTRACT_HAS_RFA after update:
-
id  contract_id approver_id who status  update_time          updater_id creator_id
1       25          37        G   A      07.05.2017 16:16      37               6
2       25          12        G   A      07.05.2017 16:16      37               6

As you can see both rows where updated while only the first row should have been updated.

File upload not working with two Editors on same page

$
0
0

One of the tables used in my application has a large number of fields, including two fields used to hold references to file uploads (one an image the other a pdf). Because the number of fields is large, I'm using multiple tabs to segregate the data into reasonable size chunks. Each tab has its own editor to handle the data within that tab. Works well, but I've run into an issue when uploading image and pdf files.

One of the editors ends up referencing the incorrect set of files when attempting to open the editor. I've created a fairly easily replication of the problem starting with the Editor sample upload.html/php. To reproduce, do the following:

Add another column to the users table as pdf int default NULL, and recreate the sample database.

Copy upload.html to uploadTest.html and modify contents as follows:

<snip><snip><snip>

var editor1; // use a global for the submit and return data rendering in the examples
var editor2; // use a global for the submit and return data rendering in the examples

$(document).ready(function() {
    editor1 = new $.fn.dataTable.Editor( {
        ajax: "../../controllers/uploadTestImage.php",
        table: "#editor1",
        fields: [ {
                label: "Last name:",
                name: "last_name"
            }, {
                label: "Image:",
                name: "image",
                type: "upload",
                display: function ( file_id ) {
                    return '<img src="'+editor1.file( 'files', file_id ).web_path+'"/>';
                },
                clearText: "Clear",
                noImageText: 'No image'
            }
        ]
    } );

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

    editor2 = new $.fn.dataTable.Editor( {
        ajax: "../../controllers/uploadTestPDF.php",
        table: "#editor2",
        fields: [ {
            label: "Last name:",
            name: "last_name"
        }, {
            label: "PDF:",
            name: "pdf",
            type: "upload",
            display: function ( file_id ) {
                return '<img src="'+editor2.file( 'files', file_id ).web_path+'"/>';
            },
            clearText: "Clear",
            noImageText: 'No image'
        }
        ]
    } );

    var table = $('#editor2').DataTable( {
        dom: "Bfrtip",
        ajax: "../../controllers/uploadTestPDF.php",
        columns: [
            { data: "last_name" },
            {
                data: "pdf",
                render: function ( file_id ) {
                    return file_id ?
                        '<img src="'+editor2.file( 'files', file_id ).web_path+'"/>' :
                        null;
                },
                defaultContent: "No PDF",
                title: "PDF"
            }
        ],
        select: true,
        buttons: [
            { extend: "create", editor: editor2 },
            { extend: "edit",   editor: editor2 },
            { extend: "remove", editor: editor2 }
        ]
    } );

} );



    </script>
</head>
<body class="dt-example php">
    <div class="container">
        <section>
            <h1>Editor example <span>File upload</span></h1>
            <div class="info">
                <p>This example shows Editor being used with the <a href="//editor.datatables.net/reference/field/upload"><code class="field" title=
                "Editor field type">upload</code></a> fields type to give end users the ability to upload a file in the form. The <a href=
                "//editor.datatables.net/reference/field/upload"><code class="field" title="Editor field type">upload</code></a> field type allows just a single file to be
                uploaded, while its companion input type <a href="//editor.datatables.net/reference/field/uploadMany"><code class="field" title=
                "Editor field type">uploadMany</code></a> provides the ability to have multiple files uploaded for a single field.</p>
                <p>The upload options of Editor are extensively documented in the manual (<a href="//editor.datatables.net/manual/upload">Javascript</a>, <a href=
                "//editor.datatables.net/manual/php/upload">PHP</a>, <a href="//editor.datatables.net/manual/net/upload">.NET</a> and <a href=
                "//editor.datatables.net/manual/node/upload">NodeJS</a>) and details the various options available.</p>
                <p>In this example an image file can be uploaded, limited to 500KB using server-side validation. To display the image a simple <code class="tag" title=
                "HTML tag">img</code> tag is used, with information about the file to be displayed retrieved using the <a href=
                "//editor.datatables.net/reference/api/file()"><code class="api" title="Editor API method">file()</code></a> method which Editor makes available and is
                automatically populated based on the server-side configuration.</p>
            </div>
            <div class="demo-html"></div>
            <table id="editor1" class="display" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Last name</th>
                        <th>Image</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>Last name</th>
                        <th>Image</th>
                    </tr>
                </tfoot>
            </table>
            <table id="editor2" class="display" cellspacing="0" width="100%">
                <thead>
                <tr>
                    <th>Last name</th>
                    <th>PDF</th>
                </tr>
                </thead>
                <tfoot>
                <tr>
                    <th>PDF</th>
                    <th>Image</th>
                </tr>
                </tfoot>
            </table>
            <ul class="tabs">
                <li class="active">Javascript</li>
                <li>HTML</li>
                <li>CSS</li>
                <li>Ajax</li>
                <li>Server-side script</li>
            </ul>
            <div class="tabs">

<snip><snip><snip>

Then, copy upload.php to uploadTestImage.php and change as follows:

<?php

/*
 * Example PHP implementation used for the index.html example
 */

// DataTables PHP library
include( "../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, 'users' )
    ->fields(
        Field::inst( 'last_name' ),
        Field::inst( 'image' )
            ->setFormatter( Format::ifEmpty( null ) )
            ->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' ), "Please upload an image" ) )
            )
    )
    ->process( $_POST )
    ->json();

Similarly, copy upload.php to uploadTestPDF.php and changes a follows:

<?php

/*
 * Example PHP implementation used for the index.html example
 */

// DataTables PHP library
include( "../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, 'users' )
    ->fields(
        Field::inst( 'last_name' ),
        Field::inst( 'pdf' )
            ->setFormatter( Format::ifEmpty( null ) )
            ->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( 'pdf' ), "Please upload a PDF file" ) )
            )
    )
    ->process( $_POST )
    ->json();

Now you're ready to test. Load the uploadTest.html and you should see two tables, each with two columns. First table has Last Name and Image columns, second table has Last Name and PDF columns. All good to this point.

Next, select first record in first table, then Edit first table, and upload any image. This is good.

Then, select second record in second table, then Edit second table, and upload any PDF. This works too.

Next, refresh the page. Image and PDF are there. That's good.

Now select the first record in first table, and then Edit first table. Doesn't work. Edit button just shows spinning cursor. I poked around down into DataTables.editor.min.js:105 -- and wrong array of files seems to be there (array from second editor, not first one).

If you refresh the page, select the second record in the second table, and then Edit, everything works okay.

Somewhere along the way, the list of files used for each editor is getting out of synch.

Note, I am using DataTables 1.10.18 and Editor 1.8.1 for both my own application, and for the example that I reproduced above.

Also, I did make the change you outlined in this fix from this issue to editor.php, but the problem still exists for me.

Viewing all 81384 articles
Browse latest View live


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