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

columnText renders text, not html, when using colReorder and colVis and bootstrap

$
0
0

Demo: https://jsfiddle.net/friek2k/fjwjfuxL/

In this demo, on first load, columnText appropriately renders the supplied html as html. However, if you try re-ordering the columns, then opening the columns dropdown again, the buttons are echoed as text - i.e. the html isn't rendered.

Any suggestions on how to remediate?

Thanks a lot


Creating Dynamic Nested Tables

$
0
0

Would it be possible to create something like this picture?

I am able to create the main table and the child row but I am at a loss how to create a dynamic number of tables with dynamic data.

Atm my thinking is, I need to create the HTML shell first and then add the data to the shells but I run into the problems of creating the shells and giving them a custom ID (which would be an object from the json file).

I was also thinking about instead of multiple tables, I would have 1 inner table in the child row, and use single td's with lists in them to show all the data.

I'm not sure how to go about this.

dynamic datasource asp.net mvc

$
0
0

I am trying to build a datatable based off a user defined function. I see a post where code is given on how to grab the column names dynamically: https://datatables.net/forums/discussion/comment/142403#Comment_142403

However, I am having trouble getting the data into the correct format. If you look at my commented out lines, there are several techniques I have tried (and you can probably tell by what I tried that I am very new to this :( )

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using DataTables;
using Billing.Models;
using Newtonsoft.Json;

namespace Billing.Controllers
{
    public class ToGenerateController : ApiController
    {
        [Route("api/ToGenerate")]
        [HttpGet]
        [HttpPost]
        public IHttpActionResult toGenerate()
        {
            var request = HttpContext.Current.Request;
            var settings = Properties.Settings.Default;
            var AsOfCookie = request.Cookies["AsOfDate"].Value;
            string query = "select * from udf_FundOrgFTE_AdjustedFTEPercentages ('" + AsOfCookie + "')";
            string connectionString = settings.DbConnection;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(query, conn);

                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                var dt = new System.Data.DataTable();
                dt.Load(reader);
                object[] result = new object[dt.Rows.Count + 1];

                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                {
                    result[i] = dt.Rows[i].ItemArray;
                }

                reader.Close();
                return Json( result);
                //string strArray = "{ 'draw':null,'data':[" + result.ToString() + "]}" ;
                //return Json( strArray );
                //var json = JsonConvert.SerializeObject(result);
                
                //return Json(json);
                //return Json("{ 'draw':null,'data':[" + result + "]}");
            }
        }

    }
}

add buttons to multiple tables

SearchPanes and search plugins

$
0
0

I'm working on a search plugin to filter duplicate data from the visible rows. If I use the search input I see that the plugin is executed once for each visible row when using draw(). However if I use SearchPanes to filter the table then the plugin is executed once for each row, visible or not, in the table when using draw().

Is this expected behavior with SearchPanes?

Is there a way in the search plugin to know if the row is visible so I know with to ignore it or use it when checking for duplicates?

Do you want a test case?

Kevin

Searchpane error

$
0
0

Good day,

I tried to put the "searchpane" option and appeared this error

Processing Load very slow takes more than 30 seconds

$
0
0

Hello, I have been trying to load the content of a single query for days, I have tried both from the server side and directly and both do not work take the same.

I have incorporated the "scroller" plugin but it takes the same, someone can help me, I leave the code here, use php and codeigniter 3.

JS

var table = $('#datatabletransaction').DataTable({
    "deferRender":    true,
    "scrollY":        500,
    "scroller":       true,
    "responsive": true,
    "processing": true,
    "fixedHeader": true,
    "serverSide":true,
        "lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "Todos"]],
        "ajax": {
            "url": mostrarcontenido,
            "type": "POST"
    },        
    language": {
          "url": "http://cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
    },
    "fixedColumns": true,
    "iDisplayLength": 5,
    "order": [[ 2, "desc" ]]
    });

Controller

public function mostrartablatransaccionestelefonos(){
      $this->load->model('tablas_model');
      $data = array();
      $list = $this->tablas_model->mostrar_registros_ventacompra($estado);
      foreach ($list as $person) {
          $row = array();
          $row[] = $person->num_factura;
          $row[] = $person->num_albaran;
          $row[] = $person->transacion;
          $row[] = $person->imei;
          $row[] = $person->nombre;
          $row[] = $person->fecha_registro;
          $row[] = $person->modelo;
          $row[] = $person->marca;
          $row[] = $person->color;
          $row[] = $person->memoria;
          $row[] = $person->precio_iva;
          $row[] = $person->precio_sin_iva;
    
          $output = array(
                  "data" => $data,
          );
          echo json_encode($output);

   }

using columnsToggle to hide columns but not remove them from the DOM

$
0
0

Is there a way to use the columnsToggle option, but have the toggle hide columns instead of removing them from the DOM? The reason I ask is I need to assign classes to certain cells, and right now I can only come up with 2 ways:

var table = $('#example').DataTable();
var row = table.row('#row_'+d.data[i].ID);
var node = row.node();

$(node).find('.cssCompTot').addClass('Warn');

or

$(node). find('td').eq(7).addClass('Warn');

The problem with either method is, if the table column is set to be hidden on load (I am using cookies to allow a user to hide columns on load) this will never find the cell that needs to have the class hidden because it is removed from the DOM.

The other problem with the 2nd example is, if different columns are hidden in front of column 7, the position will change as well and the class is applied to the wrong cell.

I have tried using:

 table.row.cell(this.index(),7).node().addClass('Warn')

as well as

 $( table.row.cell(this.index(),7).node() ).addClass('Warn')

Fetch extra columns & have a preset "where" (serverside)

$
0
0

Hey there! I have been struggling with getting the serverside DataTables ajax fetch to work like I want it to, and haven't found any documentation on this, so here goes;

I'm using the PHP SSP-class, and I'd like to get more than just the columns that are shown in the table. Fx., one of the (client-side) table columns is status, and the formatted data of this field depends on the value of 3 other columns from the (MySQL)table. the second argument passed to the formatter function in the server-side column setup is $rows, but this only returns the rows represented in dt values in the column-arrays. So, how would I go about getting more columns from the database, without showing them as a column in the HTML-table?

My second issue might just be me not understanding the complex function from the SSP-class, but (no matter what is searched, ordered by and so on), I need to have a standard WHERE statement. The statement is as follows;

printer_id IN (1,2,3,4,5) AND ((started != '0000-00-00 00:00:00' AND ended != '0000-00-00 00:00:00') OR printing = 1)

I have made a very poor attempt to modify the SSP-class, but I'm thinking this must be something that is achievable without modification (maybe?)

Thanks so much in advance!

Passing an async function to settings.ajax causes error when reload is called

$
0
0

Passing an async function to settings.ajax causes an "xhr.abort is not a function" error when reload is called:

Testcase:
http://live.datatables.net/kevuqoro/1/edit?html,js,console,output

Code

  var tableAsync = $('#async').DataTable({
    ajax: async (dtAjaxData, callback) => {
      callback({
        draw: dtAjaxData.draw,
        recordsTotal: 0,
        recordsFiltered: 0,
        data: [],
      });
    },
  });

  tableAsync.ajax.reload();

Error

jquery.dataTables.js:7582 Uncaught TypeError: xhr.abort is not a function
    at __reload (VM48 jquery.dataTables.js:7582)
    at _Api.<anonymous> (VM48 jquery.dataTables.js:7644)
    at _Api.iterator (VM48 jquery.dataTables.js:7029)
    at _Api.<anonymous> (VM48 jquery.dataTables.js:7643)
    at Object.reload (VM48 jquery.dataTables.js:7196)
    at HTMLDocument.<anonymous> (<anonymous>:26:19)
    at j (VM47 jquery-1.11.3.min.js:2)
    at Object.fireWith [as resolveWith] (VM47 jquery-1.11.3.min.js:2)
    at Function.ready (VM47 jquery-1.11.3.min.js:2)
    at HTMLDocument.J (VM47 jquery-1.11.3.min.js:2)

Searchpane issue with cascade and ajax reload

$
0
0

As mentioned in the Searchpane-feedback thread, there's a performance issue (pretty intense issue in fact), appearing when using cascading panes along with data.ajax.reload()

(see here for further details)

How to change position of buttons?

$
0
0

I have some custom buttons. Like Add New, PDF, CSV etc. I want these button in different positions. I have no problem to create button. But how can I give them position like the above image?

first step, config, can't connect to db, super common

$
0
0

Hello,
I see this Q googling

I see change localhost to 127.0.0.1
Gotta be php5.3 or higher, I'm using 7.2
Must be this type....I'm using Plesk

I see check the user and pw. I have dozens of scripts on the server with the user/pw setup

I don't recall having port as an option in any other script just the :3306. so I tried separate and together in the config php

directions list charset and I have tried ut8_general_ci and charset=utf8mb4 which is in the notes

"pdo" in directions
"pdoAttr" in the code to edit
I tried null, $database, and array because...I don't really know what the goal is with that variable

I pasted the sql text using phpmyadmin

Soooo I deleted everything, db, files, you name it and redid everything
Same errors.

This is on a local server suppose 1.2.3.4 For other scripts, I can use 1.2.3.4, 127.0.0.1, and localhost:3306 and each work fine

I still can't connect and I'm sorry to be that noob that asks a repeated question but, I've tried everything I googled and found

Uncaught TypeError: Cannot read property '_aData' of undefined

$
0
0

Hi,

I have a JQuery DataTables that shows parent/child detailed. User can click the expand/collapse icon on the parent row and another datatable will be shown up with the details info.

Everything works perfectly when the page first time loaded. I also have some custom filters i.e. status on the page to filter the table and it basically is calling the API to get the data and call the InitTable() to refresh the whole table from frontend. The issue is after the filters is selected, the expand/collapse stop working. The icon will still be toggled but the details table did not show up. I got the "Uncaught TypeError: Cannot read property '_aData' of undefined" error when running inspection in Chrome.

Here is the code:

<script type="text/javascript">
    $(function () {
        var selected1 = [];
        $('#permitStatues').multiselect({
            selectAllValue: 'multiselect-all',
            enableCaseInsensitiveFiltering: false,
            enableFiltering: false,
            onChange: function () {
                selected1 = $('#permitStatues').val();
                $('#selectedStatues').val(selected1);
                InitTable();
            }
        });

        $('#Requestor').change(function () {
            InitTable();
        });

        $("#Status").change(function () {
            InitTable();
        });

        InitTable();
    });

    //Return table with id generated from row's name field
    function format(rowData) {
        return '<table id="' + rowData.JobId + '" class="table table-striped table-hover table-condensed table-bordered"></table>';
    }

    function InitTable() {
        $('#permitrequests').DataTable().destroy();
        var permitStatues = $('#permitStatues').val();
        var requestor = $('#Requestor').val();

        var tblpermitrequests = $('#permitrequests').DataTable({
            "destroy": true,
            "lengthMenu": [[10, 20, 25, 50, -1], [10, 20, 25, 50, "All"]],
            "search": {
                "caseInsensitive": true
            },
            "order": [[ 1, "asc" ]], //default sorting by site name
            "stateSave": true,
            "iDisplayLength": 20,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "@Url.HttpRouteUrl("ActionApi", new { controller = "Job", action = "GetPermitJobs", area = "" })",
                "data": { permitStatues: permitStatues, requestor: requestor },
                "type": "POST"
            },
            "columns": [
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": '',
                    "render": function () {
                        return '<i class="fa fa-plus-square" aria-hidden="true"></i>';
                    },
                    width: "15px"
                },
                { "data": "JobNumber" },
                { "data": "JobName" },
                { "data": "LocationName" },
                { "data": "CustomerName" },
                { "data": "ProjectManager" },
                { "data": "Foreman" },
                { "data": "Engineer" },
                { "data": "ScheduleStartDate" },
                { "data": "RequestCount" }
            ]
        });

        // Add event listener for opening and closing first level childdetails
        $('#permitrequests tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var tdi = tr.find("i.fa");
            var row = tblpermitrequests.row(tr);
            var rowData = row.data();

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.remove();
                tr.removeClass('shown');
                tdi.first().removeClass('fa-minus-square');
                tdi.first().addClass('fa-plus-square');
                // Destroy the Child Datatable
                $('#' + rowData.JobId).DataTable().destroy();
            }
            else {
                // Open this row
                row.child(format(rowData)).show();
                var id = rowData.JobId;

                var permitrequesttable = $('#' + id).DataTable({
                    "destroy": true,
                    "order": [[1, "asc"]],
                    dom: "t",
                    "processing": true,
                    "serverSide": true,
                    "ajax": {
                        "url": "@Url.HttpRouteUrl("ActionApi", new { controller = "PermitRequest", action = "GetPermitRequests", area = "" })",
                        "data": { JobId: rowData.JobId },
                        "type": "POST"
                    },
                    columns: [
                        {
                            title: 'Action',
                            "render":
                                function (data, type, row) {
                                    if (type === 'display') {
                                        if (isAdministrator) {
                                            var actions = "<a class='view-permitrequest' href='/PermitRequest/Detail/" + row.Id + "'>"
                                                + "<span class='glyphicon glyphicon-search' title='View/Edit permit request'></span></a>"
                                                + "<span class='glyphicon glyphicon-trash delete-permitrequest' title='Delete Permit Request'></span>";
                                            return actions;
                                        }
                                        else if (isPM) {
                                            var actions = "<a class='view-permitrequest' href='/PermitRequest/Detail/" + row.Id + "'>"
                                                + "<span class='glyphicon glyphicon-search' title='View/Edit permit request'></span></a>";
                                            return actions;
                                        }
                                        else {
                                            var actions = "<a class='view-permitrequest' href='/PermitRequest/Detail/" + row.Id + "'>"
                                                + "<span class='glyphicon glyphicon-search' title='View/Edit permit request'></span></a>";
                                            return actions;
                                        }
                                    }
                                },
                            "sortable": false,
                            "class": "grid-actions"
                        },
                        { data: "Name", title: 'Permit Name' },
                        { data: "Requestor", title: 'Requestor' },
                        { data: "FSR", title: 'FSR' },
                        { data: "StatusName", title: 'Status' },
                        { data: "LocationName", title: 'Location' },
                        { data: "RequiredDate", title: 'Required Date', render: formatDate },
                        { data: "ExpiryOn", title: 'Expiry On', render: formatDate },
                        { data: "InspectionCount", title: 'Inspections' },
                        { data: "DocumentCount", title: 'Documents' }
                    ],
                    scrollY: '100px',
                    select: true,
                });

                tr.addClass('shown');
                tdi.first().removeClass('fa-plus-square');
                tdi.first().addClass('fa-minus-square');
            }
        });
    }
</script>

Here is the error screenshot and looks like the error is on this line: var rowData = row.data();

How do I print on separate pages rows grouped by a value or attribute?

$
0
0

I've got a table that shows data for multiple suppliers and it has a "Supplier" column with the name of the supplier. My intention is that when I hit print, I would get all rows related to one supplier in one page, all rows related to another supplier on another page and so on ending up with a big print with lots of pages and each suppliers on a separate page.

I'm thinking of either filtering/grouping those results by the column value which is the supplier name or by some attribute that I could add to those rows depending on their value.

However, my issue is that I don't know how to use the exportoptions and rows to make this filtering/grouping happen and also I don't know how to split them into different pages.

Here is my print button:

{
   extend: 'print',
   className: 'btn btn-smallest btn-primary btn-mini',
   text: 'Print Report',
   title: 'Report' + selectedAgent,
   orientation: 'landscape',
   footer: true,
   customize: function ( win ) {
      $(win.document.body).css( 'font-size', '10pt' ),
      $(win.document.body).find('h1').css('font-size', '12pt'),
      $(win.document.body).find( 'table' ).addClass( 'compact' ).css( 'font-size', 'inherit' );
   },
   exportOptions: {
      rows:{
         ...?
         }
      }
   },

Here is a sample of the table:

Please point me in the right direction, I've been looking at the documentation and can't figure out a way to combine those API options to get what I'm looking for


Datatables not work

$
0
0

hi
I have started to try my first datatable plugin, but it is not working.
I have included the datatable js and css files in master.php like this

<head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
</head>
<body>
> 
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
    $(document).ready( function () {
        $('#table_id').DataTable();
    });
</script>
</body>

I have given id to a table and call the script given in datatables website.

@extends('admin.layouts.master')
@section('title')
    Danh mục sản phẩm
@endsection
@push('css')
@endpush
@section('content')
    <!--main content start-->
    <section id="main-content">
        <section class="wrapper">
            <div class="table-agile-info">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        Responsive Table
                    </div>
                    <div class="table-responsive">
                        <table id="table_id" class="table table-striped b-t b-light">
                            <thead>
                            <tr>
                                <th></th>
                                <th>tên danh mục</th>
                                <th>Mô tả </th>
                                <th>Hiển thị</th>
                                <th>Ngày thêm</th>
                                <th></th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach($category_products as $key=>$cate_product)
                                <tr>
                                    <td>{{$key+1}}</td>
                                    <td>{{$cate_product->category_name}}</td>
                                    <td>{{$cate_product->category_description}}</td>
                                    <td>
                                        @if($cate_product->category_status == 0)
                                            Ẩn
                                        @else
                                            Hiển thị
                                        @endif
                                    </td>

                                    <td>{{$cate_product->updated_at}}</td>
                                    <td>
                                        <a href="{{route('admin.category.edit',$cate_product->id)}}"
                                           class="btn btn-info waves-effect">
                                            <i class="label label-info pull-right">sua</i>
                                        </a>
                                        <button class="btn btn-danger waves-effect" type="button"
                                                onclick="deleteCategory({{$cate_product->id}})">
                                            <i class="label label-danger pull-right">xoa</i>
                                        </button>
                                        <form id="delete-from-{{$cate_product->id}}"
                                              action="{{route('admin.category.destroy',$cate_product->id)}}"
                                              method="POST" style="display: none;">
                                            @csrf
                                            @method('DELETE')
                                        </form>
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                    <footer class="panel-footer">
                        <div class="row">

                            <div class="col-sm-5 text-center">
                                @if(count($category_products) <= 5)
                                    <small class="text-muted inline m-t-sm m-b-sm">hiển thị
                                        <?php  echo count($category_products)  ?>/<?php  echo count($category_products)  ?> danh mục sản phẩm
                                    </small>
                                @else
                                    <small class="text-muted inline m-t-sm m-b-sm">hiển thị
                                        5/<?php  echo count($category_products)  ?> danh mục sản phẩm
                                    </small>
                                @endif
                            </div>
                            <div class="col-sm-7 text-right text-center-xs">
                                <ul class="pagination pagination-sm m-t-none m-b-none">
                                    {{$category_products->links()}}
                                </ul>
                            </div>
                        </div>
                    </footer>
                </div>
            </div>
        </section>
    </section>

    <!--main content end-->
@endsection
@push('js')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <script type="text/javascript">
        function deleteCategory(id) {
            const swalWithBootstrapButtons = Swal.mixin({
                customClass: {
                    confirmButton: 'btn btn-success',
                    cancelButton: 'btn btn-danger'
                },
                buttonsStyling: false
            })

            swalWithBootstrapButtons.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!',
                reverseButtons: true
            }).then((result) => {
                if (result.value) {
                    event.preventDefault();
                    document.getElementById('delete-from-' + id).submit();
                } else if (
                    /* Read more about handling dismissals below */
                    result.dismiss === Swal.DismissReason.cancel
                ) {
                    swalWithBootstrapButtons.fire(
                        'Cancelled',
                        'Your imaginary file is safe :)',
                        'error'
                    )
                }
            })
        }
    </script>
@endpush

I draw data from a table called tbl_category.. The data is loading alright but the datatables plugin is not. No error showing though. Thank you in advance.

Datatables Working on Local Host but when published to Web app get error 404

$
0
0

Hi,
I have an issue when using aspnet.core 2.1, I have datatables controller for my database which connects to the azure hosted sql server database.
This works fine when using IIS Express Localhost however when I publish the project to a web application I get an the following error,
DataTables warning: table id=example - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
The connection string I am trying to use has windows login and I believe this error may be due to the api request (http post and get) as it says the api url cannot be found error 404 or possibly due to the antiforgery token in the ajax request?

Select2 dropdown list does not open after second editor openning

$
0
0

Hi

Have a series of select2 field in my editor form.
Everything works find when i open the editor for the first time. But after closing the editor form, and reoppenning it in create or edit mode, the dropdown field is clickable but nothing appear when clicking on it.
I will need to reload the page to get it working again.

{label: "Select type: ",name: "metadata_field_2",type: "select2",opts: {placeholder: "Select a content type",minimumResultsForSearch: 5,multiple: false,closeOnSelect: false,include_hidden: false}, options: generateTypeList(find_type('content[].type'))},

I upgraded from Select2 4.0.6 to 4.0.13 but not better.
I am using Editor 1.9.2

Any suggestions ?
Thanks in advance

how takes multiple object in datatable

$
0
0

I return this in the controller.
return Json(new { listOfPath = test, data = listUser, draws = draw, recordsFiltered = recordsTotal, recordsTotals = recordsTotal }, JsonRequestBehavior.AllowGet);

in the column:
"columns": [
I can display object data
]
How takes object listOfPath in this column ??

Unique Validator

$
0
0

I wanted to use the built-in "unique" validator for Editor but I didn't know how to use it conditionally: The field may have the values "0", "1" and "2". Only the "2" must be unique in the database. The "0"s and "1"s are occuring may times.

I ended up using the code below. Is there a way to use the built-in validator here?

if ($lang === 'de') {     
    $msg[0] = 'Feld darf nicht leer sein.'; 
    $msg[1] = 'Es kann nur einen Marktplatz Betreiber geben.';
} else {
    $msg[0] = 'Field may not be empty.';
    $msg[1] = 'There can only be one marketplace operator.';
}
.............
Field::inst( 'creditor.type' )
    ->validator( function ( $val, $data, $opts ) use ($msg, $db) {
        if ( $val == '2' ) { //marketplace operator: there is only one!
            $row = $db->raw()
                ->exec('SELECT COUNT(*) FROM creditor WHERE type = 2')
                ->fetch(PDO::FETCH_ASSOC);
            if ( (bool)$row["COUNT(*)"] ) {
                return $msg[1];
            }
        }
        return true;
    } ), 
Viewing all 81693 articles
Browse latest View live


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