Quantcast
Channel: Recent Discussions — DataTables forums

Horizontal scrolling and the Fixedheader briefly losing alignment

$
0
0

I’ve been trying to get a way of using fixedheaders on a wide table for a couple of days. I finally managed to get it working the same on desktop and mobile (I don’t want this to be responsive), but there is one slight problem. If the screen is scrolled when anywhere except the absolute left of the table, once the fixedheader is attached, it starts at the left, so it appears out of line. However, what causes it to realign straight away, is to just scroll horizontally either left of right and it suddenly jumps back into position. When you scroll back up and the fixedheader detaches once again, the problem above is repeated.

I’ve tried loads of suggestions with no luck including table.columns.adjust() and table.fixedHeader.adjust();.

I use the table inside a div to contain it, and this nearly works as I wanted.

<div style="overflow: auto; max-width: 100%;">
    <table class="datatable table table-striped table-bordered" id="datatable" style="width: auto; margin: 0;">

I’ve read about scrollX and fixedheaders not being being 100% compatible, but I seem to be so close to this working after trying so many combinations.

I use Bootstrap 5 and have all the latest versions from the downloads page. I have fixedHeader: true, scrollX: true,.

Is there a way something can be triggered to fix this like just a quick horizontal scroll does? I’ve attached a couple of demo screenshots and I’m hoping there might be something I can try without the need for a test case. I hope I’ve given enough detail.




way to batch importing to stay under the max_input_vars

$
0
0

I used https://editor.datatables.net/examples/extensions/import as a reference to create an import process, however I am getting, "Too many rows edited at the same time (tech info: max_input_vars exceeded)."

I may not have the ability to expand max_input_vars because of where the server is hosted.
I am trying to find a workaround without retooling a bunch of stuff.

Is there a way to auto-batch through the data being uploaded so it only uploads X number of records at a time?

Ability for the Responsive extension toggle arrow to be on a different column than the first one

$
0
0

As far as I know, currently the Responsive extension places the arrow toggle on the first column. You can modify that via these settings (in this case to appear on the 2nd column):

responsive: {
    details: {
        type: "column",
        target: 1
    }
}

However, the toggle arrow still remains on the first one. The 2nd column is now used to toggle between opened and closed state, but the CSS doesn't reflect that.
You can manually set the arrow like so, where dtr-control-custom is a class added to each column:

table.dataTable.dtr-column.collapsed > tbody > tr {
    > td.dtr-control-custom,
    > th.dtr-control-custom {
        cursor: pointer;
        
        &:before {
            display: inline-block;
            box-sizing: border-box;
            content: "";
            border-top: 5px solid transparent;
            border-left: 10px solid rgba(0, 0, 0, 0.5);
            border-bottom: 5px solid transparent;
            border-right: 0;
            margin-right: 1rem;
        }

        .dtr-expanded &:before {
            border-top: 10px solid rgba(0, 0, 0, 0.5);
            border-left: 5px solid transparent;
            border-bottom: 0;
            border-right: 5px solid transparent;
        }
    }
}

A common use case for this might be if you have a selector column as the first, using DataTable.render.select() as a render function.

Is it some setting I'm missing, or does DataTables add the dtr-control class to the 1st column unnecessarily, when another should have it?

Feature Request: Visual Indicator for Active Column Filters (ColumnControl)

$
0
0

Note: This is primarily a design/CSS question.

I often use DataTables as an alternative to Excel for filtering and exploring data. However, when applying filters to multiple columns, it’s easy to forget that filters are active - there’s currently no clear visual indicator on the column controls themselves.

While the default column control icons look great, they don’t clearly reflect the filtered state. In my own python package for converting dataframes to DataTables - df2tables (which I previously shared here), I tried making the default (unfiltered) icons slightly more transparent, but that subtle change doesn’t provide enough visual feedback.

I’ve attached a few rough sketches to illustrate the concept, but they’re purely placeholders.

Ideally, this would evolve into icons/CSS styles created by someone with UI/UX or design experience.
Something that visually communicate “filtered” vs. “unfiltered” states without breaking the existing clean look of DataTables.

Thanks for considering this!

selectize on editor form

$
0
0

I just started to work with selectize in my editor form to allow searching on various fields to find an address. The field in the editor form doesn't appear to be doing anything and I am not seeing any errors. I am wondering if it's a config issue.

I downloaded the plugins from https://editor.datatables.net/plug-ins/field-type/editor.selectize. Below is how I am initializing in my header:

<head>
         <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
    <title>Residents</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />

        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
     
        <link href="css/datatables.min.css" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="css/generator-base.css">
    
                <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">


        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.9.0/css/selectize.css">  
                <link rel="stylesheet" type="text/css" href="css/editor.selectize.css">

            <script src="js/datatables.min.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/dataTables.editor.min.js"></script>
                <script src="https:////cdnjs.cloudflare.com/ajax/libs/selectize.js/0.9.0/js/standalone/selectize.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/editor.selectize.js"></script>

            <script type="text/javascript" charset="utf-8" src="js/Residents_tbl_test.js" defer></script>
        <script type="text/javascript" charset="utf-8" src="js/ellipsis.js"></script>   
          <link rel="stylesheet" href="./css/navbar.css">
      
</head>

Below is the configuration under the editor:

 {
            label: 'Find Address:',
            name: 'Residents.addressaid',
            type: 'selectize',
            opts: {
                valueField: 'addressaid',
                labelField: 'Full_Address',
                searchField: 'Full_Address',
                create: false, // Allow creating new options
                load: function(query, callback) {
                    if (!query.length) return callback(); // Don't load if no query
                    $.ajax({
                        url: './php/Addresses_Ajax_test.php', // Your API endpoint for lookup.
                        
            
                        data: { q: query },
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.data); // Assuming your API returns an array of objects
                        }
                    });
                }
            }
        },

I believe Addresses_ajax_test.php is working as it returns the following:
{"data":[{"AddressAID":17712,"Full_Address":"BALSAM ST 4251 APT 1","StreetName":"BALSAM ST","AddressNumber":4251,"Ward":12,"District":3,"IsProd":0},{"AddressAID":17713,"Full_Address":"BALSAM ST 423 (17713)","StreetName":"BALSAM ST","AddressNumber":423,"Ward":12,"District":3,"IsProd":0},{"AddressAID":17714,"Full_Address":"BALSAM ST 419 (17714)","StreetName":"BALSAM ST","AddressNumber":419,"Ward":12,"District":3,"IsProd":0},{"AddressAID":17715,"Full_Address":"BALSAM ST 413 (17715)","StreetName":"BALSAM ST","AddressNumber":413,"Ward":12,"District":3,"IsProd":0},{"AddressAID":17716,"Full_Address":"BALSAM ST 409 (17716)","StreetName":"BALSAM

Unable to find an exact date using FixedColumns component and calendar with data in DateTime format

$
0
0

Link to test case: https://live.datatables.net/nilaciqu/1/edit
Debugger code (debug.datatables.net): NA
Error messages shown: NA
Description of problem: Hello,

Hello,

I'm having a small problem using the FixedColumns component with dates in ISO 8601 format.

In a test case, searching for a specific date doesn't work.

However, sorting is functional, and I can search for dates before or after. Only the exact date doesn't work.

Just to clarify, my regional settings are in French.

Ex. Sorting on date: OK

Ex. Filtering on a later date: OK

Ex. Filtering on a exact date: KO

However, the date 2025-11-09 does exist in the table.

Just to clarify, I don't use Moment.js or Luxon.

Thanks in advance for your help and have a nice day.

Lolo

Formating a rendered number of a column

$
0
0

Hello,
I have a number column that I am rendering that way:

{data: "reporting_header.balance_CLBD_amount_amount", render: DataTable.render.number(null, null, 2), className: 'dt-body-right' }

But I must add a condition statement which calculate the value of the column:

{data: null, render: function ( data, type, row ) {
     if (data.reporting_header.balance_CLBD_credit_debit_indicator === 'DBIT') {
          return -1 * data.reporting_header.balance_CLBD_amount_amount;
     } else {
          return data.reporting_header.balance_CLBD_amount_amount;
     }
}}

How can I add to the second code the formating of the first?

DateTime display() as an option

$
0
0

For the DateTime plugin, display() is available through the api, but an option would be helpful as well.

{
    label: 'Some date field',
    name: 'some_date',
    type: 'datetime',
    opts: {
        display: {
            year: 1982,
            month: 10
        }
    }
},   

or maybe...

{
    label: 'Some date field',
    name: 'some_date',
    type: 'datetime',
    opts: {
        display: [1982, 10]
    }
},   

The display option would probably only take affect if there is no current value or default value set.


Datatables defaults on datatable fields in Editor

$
0
0

Hi,
Does datatable fields in Editor adhere to any of the settings in DataTable.defaults if the code extends those properties?

Follow up to "Datatables defaults on datatable fields in Editor"

$
0
0

As I marked the question as answered, I will follow up here...

Following this up, seems like layout is where I have my issues..
My default settings are

                top: [
                    'buttons',
                    'paging',
                    { search: { placeholder: 'Sökord' } }
                ],
                topStart: null,
                topEnd: null,
                bottomStart: 'info',
                bottomEnd: 'pageLength'

This gets overridden by

                top: hasButtons
                    ? ['search', 'buttons', 'info']
                    : ['search', 'info'],
                bottom: ['paging'],
                bottomStart: null,
                bottomEnd: null,
                topStart: null,
                topEnd: null

It does not seem to be possible to override this in the datatable field type options.
I tried with

                            top: [
                                'buttons'
                            ]

but to no avail.
KR,
Björn H

Loading and Saving Sates to / from a Mariadb SQL database Take 2

$
0
0

Here is another example of saving / loading state data to / from a SQL MariaDb database based on https://datatables.net/extensions/staterestore/examples/initialisation/ajax.html

This example does integrate with Editor as it uses the PHP controller file that the Editor Generator produces to retrieve data. It also works with a Select field getting its data from another table. I have also tried it with "Column Control", colReorder and colvis and all seem to work fine. You can change the user_id variable in user_data.php so that different users can just see their own states.

To get this to work, I have added another method to the php/lib/Editor.php file. (in my case I added it after the json() method).

To start, log into the DataTables website and generate a basic site from the Editor page (https://editor.datatables.net/ ) as the files below rely on the libraries / structure of what the generator produces. You will then need to save the files detailed below in the relevant directories. Make sure you use stateRestore version 1.4.3 or later.

Initially download the package from the generator and get it working and then use / copy the files below.

SQL Scripts
data_table_script.sql. This script creates the main "data" table
state_table_script.sql. Creates the table to store the state information.
10data.sql: Optional file to load 10 example rows of data into the "data" table.

Editor.add.php
Method to be included in the php/lib/Editor.php file.

Save the following in the root directory
* user_data.php
* state_info.php

Save the following in the js directory
* table.user_data.js
* table.state_info.js

Save the following in the PHP directory
* table.state_info.php
* table.user_data.php
* table.user_and_state_data
* stateSave.php
* stateLoad.php

Edit php/lib/Editor.php and add Editor.add.php

Edit table.user_and_state_data and check that the path for the $stateLoad variable is correct.

Note that I opted for separate controller files for datatables and editor in table.user_data.js so that the statesave info is not sent back to the server after editing.


-- Data Table (filename: data_table_script.sql )
DROP TABLE IF EXISTS data;
CREATE TABLE `data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(25) DEFAULT NULL,
  `last_name` varchar(25) DEFAULT NULL,
  `zip_post_code` varchar(25) DEFAULT NULL,
  `country` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE `data`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;

  -- State Table (filename: state_table_script.sql )

DROP TABLE IF EXISTS states;
CREATE TABLE `states` (
  `id` int(10) NOT NULL,
  `state_name` varchar(10) NOT NULL,
  `state_info` text DEFAULT NULL,
  `user_id` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE `states` ADD PRIMARY KEY (`id`);
ALTER TABLE `states` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;
ALTER TABLE `states` ADD UNIQUE `unique_index`(`state_name`, `user_id`);

-- Data for load (filename: 10data.sql)
INSERT INTO data (first_name, last_name,zip_post_code,Country)
VALUES
("Armand","Warren","56045","Taiwan"),
("Xenos","Salas","71090","Liberia"),
("Virginia","Whitaker","62723","Nicaragua"),
("Kato","Patrick","97662","Palau"),
("Penelope","Hensley","76634","Greenland"),
("Georgia","Erickson","81358","Bolivia"),
("Tanisha","Humphrey","93371","Kenya"),
("Claire","Espinoza","I8S 2S8","Panama"),
("Raya","Tucker","O8D 8W7","Botswana"),
("Otto","Briggs","57590","Anguilla")

    /** File: Editor.add to be added to php/lib/Editor.php
     * jsonAddState, echo out json and state information.
     */
        public function jsonAddState($statescript = null)
    {
        include($statescript);
        $json = $this->_out;
        if ($statedata_array === []) {
            $json = json_encode($json);
            echo $json;
        } else {

            $json["stateRestore"] =  $statedata_array;
            $json = json_encode($json);
            echo $json;
        }
        return $this;
    }

<?php
    // filename user_data.php
    session_start();
    $_SESSION['user_id'] = 2;
    ?>

<!doctype html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1">

    <title>User Data</title>

        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.7.0/moment-2.29.4/dt-2.3.4/b-3.2.5/b-colvis-3.2.5/cr-2.1.2/cc-1.1.1/date-1.6.1/sl-3.1.3/sr-1.4.3/datatables.min.css">
        <link rel="stylesheet" type="text/css" href="css/generator-base.css">
        <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">

        <script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jq-3.7.0/moment-2.29.4/dt-2.3.4/b-3.2.5/b-colvis-3.2.5/cr-2.1.2/cc-1.1.1/date-1.6.1/sl-3.1.3/sr-1.4.3/datatables.min.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/dataTables.editor.min.js"></script>

    <script type="text/javascript" charset="utf-8" src="js/table.user_data.js"></script>

    <style>
        div.desktopContainer {
            width: auto;
            margin-left: 200px;
            margin-right: 200px;
        }
    </style>
</head>

<body class="dataTables">
    <div class="desktopContainer">
        <h2>User Data</h2>
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="user_data" width="100%">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>ZIP / Post code</th>
                    <th>Country</th>
                </tr>
            </thead>
        </table>
    </div>
</body>

</html>

<?php
    // Filename state_info.php
    ?>
<!doctype html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>State Information</title>

        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.7.0/moment-2.29.4/dt-2.3.4/b-3.2.5/b-colvis-3.2.5/cr-2.1.2/cc-1.1.1/date-1.6.1/sl-3.1.3/sr-1.4.3/datatables.min.css">
        <link rel="stylesheet" type="text/css" href="css/generator-base.css">
        <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">

        <script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jq-3.7.0/moment-2.29.4/dt-2.3.4/b-3.2.5/b-colvis-3.2.5/cr-2.1.2/cc-1.1.1/date-1.6.1/sl-3.1.3/sr-1.4.3/datatables.min.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/dataTables.editor.min.js"></script>

    <script type="text/javascript" charset="utf-8" src="js/table.state_info.js"></script>

    <style>
        div.desktopContainer {
            width: auto;
            margin-left: 90px;
            margin-right: 90px;
        }
    </style>

</head>

<body class="dataTables">
    <div class="desktopContainer">
        <h2>State Information</h2>
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="state_info" width="100%">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>User Id</th>
                    <th>State Name</th>
                    <th>State Information</th>
                </tr>
            </thead>
        </table>
    </div>
</body>

</html>

Pagination start post variable always 0

$
0
0

Hello,

I'm working on a project upgrading our website- jquery/datatables/codeigniter. With the previous versions, I had no problem with this datatable. But now, for some reason the pagination isn't working. The datatable loads successfully the first time, but neither the drop-down to choose the number of results shown, nor the clickable page numbers work. Each time the function getRecordsInfo returns the same thing (results from 0 to 10).

Unfortunately the page is behind a login, but I can provide code as necessary. This is the header HTML, we are using dataTables 2.0.8

<script src="https://dev.vmc.w3.uvm.edu/xana/CI4/js/jquery-3.7.1.min.js" type="text/javascript"></script>
<script src="https://dev.vmc.w3.uvm.edu/xana/CI4/js/jquery-ui-1.13.2.js" type="text/javascript"></script>
<script src="https://dev.vmc.w3.uvm.edu/xana/CI4/js/bootstrap-4.1.3/bootstrap.min.js" type="text/javascript"></script>
<script src="https://dev.vmc.w3.uvm.edu/xana/CI4/js/vendor/mustache/0.5.0-dev/mustache.js" type="text/javascript"></script>
<script type="text/javascript" src="https://dev.vmc.w3.uvm.edu/xana/CI4/js/dataTables-2.0.8/datatables.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://dev.vmc.w3.uvm.edu/xana/CI4/css/bootstrap-4.1.3/bootstrap.min.css"/>
<link href="https://dev.vmc.w3.uvm.edu/xana/CI4/js/jquery-ui-1.11.2.custom/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="https://dev.vmc.w3.uvm.edu/xana/CI4/js/dataTables-2.0.8/datatables.min.css"/>

The javascript initializing the table:

                      datat = $('#data-table').DataTable({
                           "processing": true,
                           "serverSide": true,
                            "ajax": {
                                "url": "<?php echo site_url('manage/versions/getRecordsInfo');?>",
                                "type": "POST",
                                "data": data
                            }, 
                            "drawCallback": function (settings) { 
                                    // Here the response
                                    var response = settings.json;
                                    console.log(response);
                                },                                    
                            "searching": false,
                            "ordering": false,
                            "columns": JSON.parse(result.cols), //result.cols,
                            "stateSave": true,
                            "scrollY": '50vh',
                            "scrollCollapse": true,
                            "scrollX": true
                        });

The beginning of getRecordsInfo looks like this. When I echo 'start' it is always 0, even if I am clicking on the 2nd or 3rd page. Any idea why that would be the case?

            $postData = $this->request->getPost();             
            $draw = (int)$postData['draw'];
            $start = $postData['start'];
            $length = $postData['length'];
            $datasetid = $postData['datasetid'];
            $versionid = $postData['versionid'];
            echo $start 

Link to test case: unavailable
Debugger code (debug.datatables.net): uploaded as debug code ejodaw
Error messages shown: no error messages shown
Description of problem: Pagination not working, start is always 0 (length is always 10 also)

Editor datetime input is malformed

$
0
0

The date input for the editor with bootstrap5 styling and floating labels is malformed. It has two overlapping input boxes.
You can see it at the example itself

Pagination jump scrolling and accessibility

$
0
0

I’ve been working with DT2 & BS5.3 and have an issue with pagination jump scrolling when used at the bottom of a layout, which I didn’t previously have in older versions. Clicking on new pages used to keep the pagination block at the bottom regardless of the page length, but now longer pages jump up and then scroll down to where it needs to be. So, the end result is the same, apart from some jumping around.

That led me to wonder what the correct method should be for accessibility but I can’t find a consensus. I successfully forced the next page to start to the top which to me makes more sense to me but not sure that is the correct way. I think the focus should be targeted in the top left th but I suppose some checking is then needed to make sure there aren’t any hidden columns. There are so many combinations I can think of so wondered if there are any examples of best practice?

Not seeing the 'childRow.dt' event triggered.

$
0
0

Link to test case: https://live.datatables.net/dehonimi
Description of problem: Following the example provided on "https://datatables.net/reference/event/childRow" for handling the 'childRow.dt' event doesn't show any output.

The event doesn't trigger the handler regardless if it's applied before or after table initialization. Listening on either 'childRow' or 'childRow.dt' makes no difference and neither does using a static data set or AJAX for table data. I've also tried adding and removing a row manually afterwards with DtTable.row.add() and DtTable.row().remove().

Am I doing something wrong or is this event deprecated or perhaps just not working in the latest version of DataTables?


DataTable shows incorrect or duplicated data after updating rows in responsive mode

Column Control and fixed Header bug?

$
0
0

https://live.datatables.net/besoqowu/1/edit?html,js,output

No error messages:

Hi! Loving datatables and the new ColumnControl extension! Whilst working on a table in a ASP.Net solution, I have however ran into a bit of an issue between ColumnControl and Fixed header that is present within the JS Bin, when filtering on the FreeForm Search on columns , those being on Position, Whenever it filters and changes size, it loses focus on the input boxes , is this intended or is there anyway to go around that? Thank you in advance!

Example of how to use fetch() with DataTables React component

$
0
0

The DataTables React component is very nice.

I like how changing the data prop triggers a re-render. I utilized this behavior to implement a simple server-side fetch() that asynchronously populates the initial DataTable.

The following React component, called FetchDataTable, fetches the table data from a server using the browser API fetch. It is much easier to use than ajax for smaller tables.

FetchDataTable.jsx:

//
// FetchDataTable.jsx -- Wrapper for DataTables React component with fetch()
//

import { useState, useEffect, createContext } from 'react';

function useFetch(fetchUrl, fetchOptions) {
    const [tableData, setTableData] = useState([]/*empty table*/);
    const [isLoading, setIsLoading] = useState(true);
    const [errorMsg, setErrorMsg] = useState(null);

    useEffect(() => {

        const fetchData = async () => {

        try {
            setIsLoading(true);

            // fetch() default options
            const opts = Object.assign({
                method: 'GET', // or 'POST'
                cache: 'no-store',
                //credentials: 'same-origin', // default
                headers: { // if POST
                    'Content-Type': 'application/json; charset=utf-8',
                    //'Content-Type': 'application/x-www-form-url-encoded; charset=utf-8',
                },
                //body: JSON.stringify(data), // if POST
                redirect: 'error',
            }, fetchOptions);

            const response = await fetch(fetchUrl, opts);

            if (!response.ok) { // Got non-200 range response (404, etc)
                throw new Error(`Server request failed: Error ${response.status}`);
            }

            let text = await response.text();

            const json = JSON.parse(text); // Throws SyntaxError if bad JSON

            if (json.error) {
                throw new Error(json.error);
            }

            const data = json.data;

            if (Array.isArray(data)) {
                setTableData(data);
            } else {
                throw new Error('Server did not return data[]');
            }
        } catch(err) {
          setErrorMsg(err.message);
        } finally {
          setIsLoading(false);
        }
      };

      fetchData(); // Start the async data fetch

      return () => {
           // Do useEffect cleanup here
      };

    }, []/*once*/); // end useEffect()

    const props = {
        tableData,
        setTableData,
        errorMsg,
        isLoading
    };

    return props;
}

/*
Expected JSON response:
{
  data: [
        { "UserId": 123, "FirstName":"Bob", "LastName":"Smith", "Role": "Manager" },
        { "UserId": 456, "FirstName":"Roger", "LastName":"Kline", "Role": "Tech Support" },
        { "UserId": 789, "FirstName":"Julie", "LastName":"Adams", "Role": "Sales" }
  ]
}

If an error occurs, the expected JSON response is

{ error: "Error message" }
*/

////////////////////////////////////////////////////////////////////////////
//
// Wrapper for <DataTable data={tableData}>
//
//

// Context to pass the fetched data down to the DataTable component
export const FetchDataTableContext = createContext({});

export function FetchDataTable({fetchUrl, fetchOptions, children}) {

    // Note the use of braces {}, not []
    const {tableData, setTableData, errorMsg, isLoading} = useFetch(fetchUrl, fetchOptions);

    if (isLoading) {
        return (
            <h1>Loading data...</h1>
        );
    }

    if (errorMsg) {
        return (
            <p style={{ color: "red" }}>Error: {errorMsg}</p>
        );
    }

    const contextData = { tableData, setTableData };

    return(
        <FetchDataTableContext value={contextData}>
          {children}
        </FetchDataTableContext>
    );
}

The following is a simple React app that uses the FetchDataTable component to populate a DataTable.

The example uses Bootstrap 5.

App.jsx:

// Example App

import { createRoot } from 'react-dom/client';
import { useRef, useState, useEffect, useContext } from 'react';

import * as bootstrap from 'bootstrap';
import DataTable from 'datatables.net-react';
import DT from 'datatables.net-bs5';

import 'bootstrap/dist/css/bootstrap.css';

import { FetchDataTable, FetchDataTableContext } from './FetchDataTable';

DT.use(bootstrap);
DataTable.use(DT);

function MyDataTable()
{
    const dtTable = useRef(); // Create a DT ref (Normally only plain DOM elements are allowed here, but DataTable is a special case)

    //Provides context.tableData, context.setTableTable()
    const context = useContext(FetchDataTableContext);

    const options = {

        lengthMenu: [2, 10, 25, 50, 100],

        // Put other options here

        columns: [
            { data: 'UserId' },
            { data: 'FirstName' },
            { data: 'LastName' },
            { data: 'Role' },
        ],
    };

    return (
        <DataTable id="users" ref={dtTable}
              data={context.tableData}
              options={options}
              className="display table table-striped table-bordered">
            <thead>
                <th>UserId</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Role</th>
            </thead>
            <tbody>
            </tbody>
        </DataTable>
    );
}

/////////////////////////////////////////////////////////////////////////////
//
function App() {

    const fetchUrl = 'https://my-site-name/my-api'
    const fetchOptions = { 'method': 'GET' };

    return (
      <div className="container">
        <FetchDataTable fetchUrl={fetchUrl} fetchOptions={fetchOptions}>
          <MyDataTable />
        </FetchDataTable>
      </div>
    );
}

/////////////////////////////////////////////////////////////////////////////

export const root = createRoot(document.getElementById("root"));

root.render(
    <App />
);

DataTable shows duplicated data when responsive

$
0
0

Link to test case: https://stackblitz.com/~/github.com/mizterdy07/vue3-test-datatable?file=src/App.vue&view=editor

Description of problem:
First, I opened the web page and resized the screen to 550px. At this width, four columns were hidden. Then, I clicked the Expand button to view the hidden columns (see the picture below).

After that, I clicked the Change Data button, which updates the values in the Description column to “11112222”. When I resized the screen back to the normal width of 1070px, the four previously hidden columns reappeared — but their data was duplicated (see the picture below).

Date search on ColumnControl

$
0
0

Hi everyone. My name is Filippo and I'm writing from Italy, this is my first post.

I've noticed that if I search for a date using the date picker in the "Start Date" column of this page, it doesn't find it. However, if I edit the text field, the search works. Does anyone has encountered the same problem?

Reference to buttons.name in config

$
0
0

Is it possibe to use the buttons.name setting to activate a set of buttons in a layout definition? (like 'buttons:main' or similar)
I would like to define multiple sets of buttons in the default settings and be able to refer to them in the config locally, but maybe this needs to be done through API calls after config?
KR, Bjørn H

grid layout - show custom div behind a feature element

$
0
0

How can I insert a custom div directly after the layout element paging?
Currently, it is displayed as a separate cell in the grid.

https://live.datatables.net/mijifezi/1/edit?html,css,output

<div class="dt-layout-row">
  <div class="dt-layout-cell dt-layout-full"></div>
  <div class="dt-length"></div>
  <div class="custom-div">hallo</div>
  <div class="dt-search"></div>
</div>

current

what i want


djangorestframework-datatables and searchPanes

rowReorder has started adding extra rows

$
0
0

Link to test case: https://www.wd4g.com/WCGateway/rowReorder_Debug.wc
Debugger code (debug.datatables.net): n\a
Error messages shown: no error message
Description of problem:
rowReordering was working fine until recently, now each time we do a rowReorder (or just drag the row to the top of the dt) we get a new rows inserted above the actually data rows (but below the column headers), this new row contains the datatables_length elements, and the datatable_filter elements. Also, we get a new rows below the data rows, (but above the table footer), this row contains the datatable_info and datatable_pagnation elements. This happen for each rowReOrder, so it duplicates each time.

I have tried removing all recent global changes to do with datatables, but the issue remains.

So, I'm struggling to find the cause of this issue.
If someone could please take a look and offer any advice that would be really appreciated.

Thanks, Chris

I'm trying to join the first name and surname from two different column and display it as full name.

$
0
0

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

Plugins columncontrol-bs5 and colreorder-bs5 not available through Composer

$
0
0

Hello,

As the title says, these packages are not available in the Packagist repository.
When doing the following commands:

composer require datatables.net/datatables.net-colreorder-bs5
composer require datatables.net/datatables.net-columncontrol-bs5

I receive the following messages:

Could not find package datatables.net/datatables.net-colreorder-bs5.
Could not find a matching version of package datatables.net/datatables.net-columncontrol-bs5. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (stable).  

These commands are given by Datatables download page when selecting the Composer installation.

I have installed other plugins through the same means (responsive-bs5, fixedheader-bs5, buttons-bs5 etc.) and there were no issues.

Is it possible to upload the missing plugins on packagist, please?

Thank you !

datatable download builder: jquery-ui missing textures?

$
0
0

I use jQuery UI with a theme that uses textures. There are two methods to include a jQuery UI style.

1) Method: jQuery UI ThemeRoller example
dataTables.jqueryui.css is loaded separately

2) Method: datatable download builder
Step 1. Choose styling => jQuery UI
datatables.css contains jQuery UI CSS styles

using Methode 1 ui-state-default

table.dataTable thead th.ui-state-default,
table.dataTable tfoot th.ui-state-default {
  border-left-width: 0;
}
table.dataTable thead th.ui-state-default:first-child,
table.dataTable tfoot th.ui-state-default:first-child {
  border-left-width: 1px;
}

using Methode 2 ui-state-default
table.dataTable thead > tr > *.ui-state-default { background: #f6f6f6; }

I have noticed that textures used with method 2 are lost.

The configured texture influences various elements, such as table headings.

How do you get a DataTables table Search input field to autofill with a parameter passed in a URL?

$
0
0

I have a page which builds a page with a column like this:

<td><a href='/bin/users?phone={{ $customerPhone }}' target='_new'>{{ $customerLabel }}</a></td>

It correctly passes the phone argument to the users page as seen in the URL:

https://devel.mysite.com/bin/users?phone=303-000-0000

How do we make this autofill the DateTables Editor table Search input field so that it limits the results to the user with that phone number, 303-000-0000?

Searching a table which contain tinyint values?

$
0
0

Can I search table data rows which have tinyint values?
Scenario: A table contains people. A table column is for marital status. 0=not married, 1=married. Please note that the information is not in text format.
How can I search using datatable and fetch the married people or the opposite?
Any example?
Thank you


How do you incase the table, and bottom row, in a div? but leave out the top?

$
0
0

This might be a dumb question but i want to incase the table itself and the bottom row in a div, but leave out the top row?

is there an easy why to do that with layout?

something like this:

<div class="dt-search"> search</div>
<div class="card">
   <div class="dt-table"></div>
   <div class="dt-bottom-row"></div>
</div>

again sorry if its a stupid question



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