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

How to Export Checked Row (I m using checkbox to select rows)?

$
0
0

1.Server side code

   while( $row=mysqli_fetch_array($queryRecords) ) 
        {  
                     $nestedData=array();
                      $nestedData[] = "<input type='checkbox' onclick='checkboxfn($(this));' id='singleBox'  value='". $index."'  />" ;
                      $nestedData[]  = "<i class='mdi mdi-format-list-bulleted'></i>";
                      $nestedData[]  = $index;
                      $nestedData[] = $row["Designation"];
                      $nestedData[] = $row["CompanyName"];
                      $nestedData[] = $row["PersonalEmail"];
                      $nestedData[] = $row["PersonalPhone"];
                      $nestedData[] = $row["PersonalMobile"];
                     $data[] = $nestedData;
                  $index++;
         }  

$json_data = array(
                          "draw"                => 1,   
                          "recordsTotal"    => intval( $totalRecords ),  
                            "recordsFiltered" => intval($totalRecords),
                           "data"            => $data   // total data array
                        );
   echo json_encode($json_data);  // send data as json format
  1. My Button Code

    dom: 'lBfrtip',
    buttons: [
    {
    extend: 'copyHtml5',

            exportOptions: {
                columns: [6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 ]
            }
        },
        {
            extend: 'excelHtml5',
            text: 'XLS',
            exportOptions: {
                columns: [6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
            }
        },
        {
        extend:  'csvHtml5',
        exportOptions: 
        {
            columns: [6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
        }
        },
        {
            extend: 'pdfHtml5',
            orientation: 'landscape',//landscape give you more space
        pageSize: 'A0',//A0 is the largest A5 smallest(A0,A1,A2,A3,legal,A4,A5,letter))
            exportOptions: {
                columns: [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
            }
        },
    

    ],
    columnDefs: [{
    "targets": 5,
    "orderable": true
    }]


Issue with uploads after validation fails

$
0
0

I am having an issue with file uploads. When a user tries to create a new record in the table and one if the required fields is not filled out properly I get the "field is required" message and everything looks fine. However when I correct the required field error and try to create the record, it goes through without an error, but the file upload is not inserted into the database and the new record is not added to the table. Any thoughts?

```

    //travel table
    var traveleditor = new $.fn.dataTable.Editor({


        ajax: '/api/DataTable/TravelTable',
        table: '#TravelTable',
        fields: [
         {
             "label": "FormInstanceId:",
             "name": "FormInstanceId",
             "className": "formidnew"                

         },                
        {
            "label": "Date:",               
            "name": "date",
            "type": "datetime",
            "format": "MM/DD/YY"
        },
        {
            "label": "Category:",
            "name": "expensecategory",
            "def": "Travel",
            "className": "category"

        },
        {
            "label": "Type of Expense:",
            "name": "expense_type",
            "type": "select",
            "options": [
                "Air Fare",
                " Milege",
                " Gas",
                "Taxi",
                "Other"
            ]
        },

        {
            "label": "Description:",
            "name": "description",
            "type": "textarea"
        },
        {
            "label": "Cost Center:",
            "name": "cost_center",
            "type": "select",
            "placeholder": "Select a Cost Center"   
        },
        {
            "label": "Account Number:",
            "name": "account_number",
            "type": "select",
            "placeholder": "Select an Account Number"

        },
        {
            "label": "W\/O:",
            "name": "wo_number"
        },
        {
            "label": "Project:",
            "name": "project_number",
            "type": "select",
            "placeholder": "Select a Project Number"
        },
        {
            "label": "Amount:",
            "name": "amount",

        },
        {
            "label": "Attachment:",
            "name": "attachments",
            "type": "upload",
            "display": function (Id) {

                var ext = traveleditor.file('expenseAttachment', Id).webPath.toLowerCase();
                var ext1 = ext.split(".").pop();

              if (Id !== null) {

                    var ext = traveleditor.file('expenseAttachment', Id).webPath.toLowerCase();
                    var ext1 = ext.split(".").pop();

                    if (ext1 == "pdf") {

                        return '<a href ="' + traveleditor.file('expenseAttachment', Id).webPath + '" target=_blank><i class =" glyphicon glyphicon-file" style="font-size: 1em; "</i>' + traveleditor.file('expenseAttachment', Id).filename + '</center></a>';

                    }

                    if ((ext1 == "png") || (ext1 == "jpg") || (ext1 == "gif")) {

                        return '<a href ="' + traveleditor.file('expenseAttachment', Id).webPath + '" target=_blank><img width="100px" src="' + traveleditor.file('expenseAttachment', Id).webPath + '"/></a>';
                                                }
                }
                else {

                    return "No File";
                }

            },

            clearText: "Remove file",
            fieldInfo: "Upload file, then create."
        }
        ] 
    });
    $('label', traveleditor.field('date').node()).addClass('aster');
    $('label', traveleditor.field('description').node()).addClass('aster');
    $('label', traveleditor.field('account_number').node()).addClass('aster');
    $('label', traveleditor.field('amount').node()).addClass('aster');
    $('label', traveleditor.field('cost_center').node()).addClass('aster');

    traveleditor.on('open', function () {

        var id1 = $("#thisid").val();
        var id2 = $("#thisid2").val();
        var cc = $("#CostC").val();
        if (id1 != "") {
            var id = id1;

        }
        else {
            var id = id2;

        }

        $("#DTE_Field_FormInstanceId").val(id);
        $("#DTE_Field_cost_center").val(cc);
        $(".formidnew").hide();
        $(".category").hide();        


    });

    traveleditor.on('close', function () {
        traveltable.ajax.reload();

    });

//API Controller

public IHttpActionResult TravelTable()
{
var request = HttpContext.Current.Request;

        using (var db = new Database("sqlserver", dbCon))

        {

            var response = new Editor(db, "ExpenseTable", "id")
                .Where(q => q.Where("FormInstanceId", request.Form["Value"], "=").Where("expensecategory", "Travel", "="))


                .Model<ExpenseTableModel>()


                        .Field(new Field("date")
                        .Validator(Validation
                                    .DateFormat("MM/dd/yy"))
                                    .GetFormatter(Format.DateSqlToFormat("MM/dd/yy"))
                                    .SetFormatter(Format.DateFormatToSql("MM/dd/yy"))
                        .Validator(Validation.NotEmpty(
                               new ValidationOpts
                               {
                                   Message = "The field is required"
                               }
                     )))

                   .Field(new Field("description")
                  .Validator(Validation.NotEmpty(
                  new ValidationOpts
                  {
                      Message = "The field is required"
                  }
                  ))

                  )
                  .Field(new Field("account_number")
                          .Options(new Options()
                              .Table("ExpenseAccountNumber")
                              .Value("AccountNumber")
                              .Label("AccountNumber"))
                              .Validator(Validation.NotEmpty(
                               new ValidationOpts
                               {
                                   Message = "The field is required"
                               }
                     )
                     ))
                    .Field(new Field("amount")
                  .Validator(Validation.NotEmpty(
                  new ValidationOpts
                  {
                      Message = "The field is required"
                  }
                  )))

                      .Field(new Field("cost_center")
                          .Options(new Options()
                              .Table("CostCenters")
                              .Value("CostCenterNumber")
                              .Label("CostCenterNumber"))
                              .Validator(Validation.NotEmpty(
                               new ValidationOpts
                               {
                                   Message = "The field is required"
                               }
                     )))

                     .Field(new Field("project_number")
                          .Options(new Options()
                              .Table("ExpenseProjectNumber")
                              .Value("ProjectNumber")
                              .Label("ProjectNumber"))

                     )

                        .Field(new Field("attachments")


                        .Upload(new Upload(request.PhysicalApplicationPath + @"ExpenseAttachments\Travel\2018\__NAME____ID____EXTN__")
                          .Validator(file => {
                            if (file.ContentLength >= 5000000)
                            {
                                return "Files must be smaller than 500K";
                            }
                            return null;
                        })
                        .Validator(
                           Validation.FileExtensions(
                                       new[] { "png", "jpg", "gif", "pdf"},
                                      "Only image or pdf files can be uploaded (png, jpg, gif and pdf)"
                                      )
                                      )


                    .Db("expenseAttachment", "Id", new Dictionary<string, object>
                    {
                        { "filename", Upload.DbType.FileName },
                        {"url", Upload.DbType.SystemPath },
                         {"webPath", Upload.DbType.WebPath}

                })

               .DbClean(data =>
               {

                   File.Delete("Id");

                   return true;


               }
               ))

                .SetFormatter(Format.NullEmpty()))

                .Process(request)

                .Data();
            return Json(response);
        }

How to properly setup a responsive table?

$
0
0

I enabled responsive:

{ responsive: true; }

This technically works, as the columns will start to auto hide on page resize. However this triggers two issues:

  1. The table width is given a fixed size, which breaks the layout.
  2. The hiding of the columns only seem to happen on resize, and not when the page loads. So when I reload the page, all columns are there.

I read several times the docs, but can't seem to understand what's the proper behavior. I know I can setup breakpoints, but that still sets a fixed width to the table. I would like to keep the table size at 100%. I tried forcing the size via css !important, but that just breaks the hiding of the columns.

The docs show, severals responsive options, but fail to show these options showing together.

Thank you.

how to bind datatable columns dymanicall from ajax post in jquery

$
0
0

$.ajax({
type: 'POST',
url: someurl
success: function (resp) {
if (resp.length > 0) {
var headers = [];
// VAR obj = $.parseJSON(resp);
// var response = JSON.parse("'resp+"'");
debugger
$.each(resp, function (index, value) {
debugger
var keys = [];
$.each(Object.keys(value), function (index1, value1) {

                      var locdatatype = "";
                      if (index == 0) {
                          //headers[index] = value1;
                          keys.push(value1);
                          debugger
                          //if (columns.length > 0)
                          //    $.each(columns, function (i, item) {

                          //        if (item.AliasName == "[" + value1 + "]") {

                          //            locdatatype = item.DataType;

                          //            colname = item.ColName;
                          //        }

                          //    });
                      }
                  });

var table = $('#viewtbl').DataTable({
// responsive: true,
//ServerSide: true,
//autoWidth: false,
// dom: 'Bfrtip',
columns: keys,
data:resp,
scrollX: false,
orientation: 'landscape',
pageSize: 'LEGAL',
Paginate: true,
dataType: "json"});

i got the error like this
Cannot use 'in' operator to search for '8' in Active1

Is there a way to use Data Live DOM Ordering together with "deferRender" + "paging" enabled

$
0
0

Dear all,

I'm using Datatables client-side with AJAX but not in server side processing mode.
I have defined custom live DOM ordering functions that are doing their job very well ; the following is an exemple of such functions.

    jQuery.fn.dataTable.ext.order['dom-data-timestamp'] = function(settings, col) {
        return this.api().column(col, { order: 'index' }).nodes().map(function(td, i) {
            return parseInt($(td).find('span').attr('data-timestamp'));
        });
    };

The datatable code is as follows.

var table = $('#my-table').DataTable({
    ajax: {
        url: '/my-table-populate-ajax-url.php',
        type: 'POST',
        global: false,
    },
    deferRender: true,
    pageLength: 10,
    paging: true,

    ordering: true,
    searching: true,

    dom: 'rt',

    order: [1, 'asc'],

    columnDefs: [
        {
            targets: [1],
            render: $.fn.dataTable.render.dataAttribute('data-date'),
            orderDataType: 'dom-data-timestamp',
            type: 'numeric',
        },
    ],
    buttons: [],
 
    initComplete: function(settings, json) {
        // Do Stuffs...
    },
});

When the number of row does not exceed the page length everything just work fine.
But as soon as there is multiple pages, ordering fail on my column 1 with a console error (either a or b is undefined), because of the deferRender enabling.

What is the correct way to use data live DOM ordering with deferRender ?

Many thanks,

I get the following error: TypeError: data is null

how to custom define the search field name

$
0
0

Hi, I got a problem, I defined a field 'good_id' like this

{
data: 'good_id',
searchable: false,
render: function(data, type, row, meta){
if(row.good){
return row.good.name;
}
return '';
}
},

but when I search , I want to search the field 'good.name' not 'good_id', so how should I do ?

fixed column above select row highlite use is it possible?

$
0
0

hi dear..
fixed column above select row highlite use is it possible?


Preserve sorting after updating cell

$
0
0

I have a table which has editable fields in row.
now when i sort data based upon perticular value and then update editable cell value, I update datatable object values using below code

table.row("rowid").data("newData").draw(false);

The problem is that it changes row position anonymously only if we have sorted data manualy(ie not default sorting).
I want a result like even if i sort data manualy and then i update column, sorting settings should not change and row
position should be preserved.
How can i get this result?

autoClose don't work for collection Button

$
0
0

Hello @allan

The option autoClose don't work for collection if option background is false .

The code problem is here.. I think... =P

PS: if I click inside the datatable, the collection is closed normally!

Hide columns - ASP MVC

$
0
0

Hi

Our current software provider has datatables present within an ASP MVC built remote acces portal (hosted locally).
Datatables is used to render Sites/Jobs/Invoice lists from our on site SQL server.
Since all the coding for the table columns etc is within the compiled code i have no way to edit this.

I have a problem that this portal is designed for customer use, they login etc etc. The problem is that there are certain columns such as 'Prospect' within quotes that i don't want them to see.

Our software provider just doesn't want to iron out the bugs but i need to roll this out rapidly.

Is it possible to reload the table with columns hidden when its set up this way? Any more information then please ask, im not experienced with DataTables/ASP/MVC but i can find my way around if needed.

Any help would be most appreciated.

Many thanks

How to customize width of select dropdown list in datatables

$
0
0

bootstrap 4.0 Datatables, the default width of the dropdown editor does use the width of the column according to datasize in it, which makes it hard to select the correct value. What's the best way to customize the width of search dropdown list?

Excel Export with complete datas

$
0
0

I'm using a table with over 30 columns. Some of the columns contains huge datas. For readable reason - and not making the table to wide - i'm cutting the datas in some columns like this:

{ "render": function (data, type, row) {
     if (data.length > 25)
      {
              var anzklass = '<span title="'+data+'">';
              anzklass += data.substring(0, 23) + '...';
              anzklass += '</span>';
              return anzklass;
      }
     return data;
      }, "targets": 30 }

This works fine. All big datas will be cutted and the complete content will be seen in a mouse-over.

But:
I also need a Excel Export. I manage this with the normal "Buttons:[Excel]" function. This also works fine, but in the Excel-file i only see the cutted datas, not the complete data.

How can i solve this, that i can see in the screen the "cutted" datas and in the Excel-file the complete datas?

Thanks a lot in advice.

need snippet for my data table with inline edit feature enabled and without ajax

$
0
0

Hello Admin,

I would like to create a data table with the inline edit with submit button, also one column should be the inline drop-down (example: state column) and one column should be in non-editable mode.

Please help me to fix this.

Thanks in advance.

Problem with data load...

$
0
0

Hi to all...
My problem is below;
I was sending a one param to filter data, after click event. And I get correct data inside datatables, but my in alert I get all data, before I was sending param.
When I read data from first row I get old data, but I need new filtered data.
In datatable I get correct data but rows count in the same event click I get bad data...
Here is part of my code...

http://prntscr.com/io2qve

http://prntscr.com/io2rom

http://prntscr.com/io2n2m

I hope someone understand what is my problem!

Solutions!?


Multiple checkbox columns

$
0
0

Hi,
I would likt to know if it's possible to make a table that is showing a checkbox beside cells content.
What I have is a 10 columns table, which 5 of them should have checkboxes, along with text content. Only one checkbox should be ticked for a same row.

Is that doable?
Thanks!

Render image instead of data

$
0
0

I want to render an image (a country flag) for a country column but keep the underlying data intact so that the column is still sortable. For example if the data is GB I want to display <img src="GB.gif">
I feel that I should be able to do this but I can't get it to work as I want.

Is it possible to check and validate file type on presubmit ?

$
0
0

Currently in my form I'm checking whether or not the field has a value and also length but I'm wondering if there's a way to check the file type on uploads as well?

This is my code for the presubmit >

editor.on( 'preSubmit', function ( e, o, action ) {
     if ( action !== 'remove' ) {
         var numOfFields = $('[data-editor-template]').length;
         var fieldNames = Object.keys(this.s.fields);
         var skip = ['home_sections.status_id','home_sections.section_image_id','home_sections.link'];
         for(var i=0;i<numOfFields;i++){

          if(fieldNames[i] == "home_sections.section_image_id"){
              console.log(this.field(fieldNames[i]));
              this.field(fieldNames[i]).error('This field can not be over 200 characters');
             }

            if(fieldNames[i] == "home_sections.link" && this.field(fieldNames[i]).val().length >= 200 ){
              this.field(fieldNames[i]).error('This field can not be over 200 characters');
             }

             else {
                if (skip.includes(fieldNames[i])) {
                 continue;
               }
             }

             if(fieldNames[i] == "home_sections.title" && this.field(fieldNames[i]).val().length >= 75 ){
              this.field(fieldNames[i]).error('This field can not be over 75 characters');
             }


             if( !this.field(fieldNames[i]).val() ) {
                  this.field(fieldNames[i]).error('This field can not be empty');
             }
         }

         if ( this.inError() ) {
             return false;
         }
     }
 } );

Uncaught TypeError: Cannot read property 'Editor' of undefined

$
0
0

Hello all,

I am getting this error on the trial version (just got it yesterday) of editor ver 1.7.2. I saw previous posts on the issue, so I made sure jquery is only loaded once (checked markup and in Network in Chrome). I then commented out all other javascript and library references, except for ones needed by Editor. Lastly, I double-checked that I have all the proper js and css added. So, at this point, I cannot do the following line without an error. Thoughts?

<script type="text/javascript">
    var editor;

    $(document).ready(function () {

        editor = new $.fn.datatable.Editor({});

    });
</script>

Editor set "computed" column

$
0
0

Hey folks. I have a "computed" column in my table which is computed from the values of two actual boolean columns in the DB, which is defined something like the following. Is there some way to use the editor to edit this computed column, by selecting a value from a drop down, and then set the source columns (Hidden and Approved) appropriately? I realize this is kind of a strange case. Thanks. If it helps, I'm using the C# DataTables editor on the back end to handle requests.

                {
                    data: null,
                    render: function (data, type, row, meta) {
                        if (data["Hidden"] == true) {
                            return "Hidden";
                        }
                        else if (data["Approved"] == true) {
                            return "Active";
                        }
                        else {
                            return "Pending";
                        }
                    } 
                }
Viewing all 82252 articles
Browse latest View live


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