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

Problems applying noVis to columns with rowspan colspan

$
0
0

Link to test case: https://live.datatables.net/kojunuce/10/edit
Debugger code (debug.datatables.net): No Error.
Error messages shown: No Error
Description of problem: I'm having problems getting noVis to work when the columns involved have rowspan and colspan enabled. I'm attaching two test cases, one in which it works perfectly and hides the column if it's an employee and prevents it from showing in "Column Visibility". If it's false, it should display correctly.
In the test case: https://live.datatables.net/kojunuce/10/edit is the described situation, and below I show a case where I don't have colspan and rowspan and it works perfectly: https://live.datatables.net/kojunuce/4/edit
If you have a chance to take a look and provide me with suggestions, I would really appreciate it. Thank you in advance.

I don't know if I explained myself well, in the case described: https://live.datatables.net/kojunuce/10/edit The Salary column should not appear when I click on Column Visibility


Search Builder orthogonal not work?

$
0
0

Link to test case: https://live.datatables.net/nefehaxu/7/edit?html,js,output
Description of problem:
In the column Office, it is rendered as html flag, and I want to filter this column in Search Builder with the country name.
(This is different than the one from this example, where I don't have country name next to the flag), and I use the option columns.searchBuilder.orthogonal, setting both search and display keys' value to 'filter'.

In the test case, however, the Office column in the Search Builder is blank because the Search Builder does not take the orthogonal settings into account. I checked the source code, the orthogonal configuration was indeed passed to the SearchBuilder, Criteria and Group at the very beginning. But somehow it uses the default configurations defined before generating Value select dom.

Related lines in the source code I guess are: https://github.com/DataTables/SearchBuilder/blob/d3ec11bd3823b28529547ba4c7f91d12db80cfb0/src/criteria.ts#L2173
https://github.com/DataTables/SearchBuilder/blob/d3ec11bd3823b28529547ba4c7f91d12db80cfb0/src/criteria.ts#L2241
https://github.com/DataTables/SearchBuilder/blob/d3ec11bd3823b28529547ba4c7f91d12db80cfb0/src/criteria.ts#L2438

I was able to fix this issue by changing this line:
https://github.com/DataTables/SearchBuilder/blob/d3ec11bd3823b28529547ba4c7f91d12db80cfb0/src/criteria.ts#L2441-L2446

private _getOptions(): {[keys: string]: any} {
    let table = this.s.dt;

    return $.extend(
        true,
        {},
        Criteria.defaults,
        table.settings()[0].aoColumns[this.s.dataIdx].searchBuilder
    );
}

into

private _getOptions(): {[keys: string]: any} {
    let table = this.s.dt;

    return this.c;
}

It seems that there is no searchBuilder inside aoColumns[this.s.dataIdx] before calling the function _getOptions(), which returns undefined, but I've made too many changes to the source code (to be able to use React) so I'm not quite sure.

Html encoding before Process httpRequest

$
0
0

In my database I store the data with html encoding Test&Test. The actual value is Test&Test.

While I search the Test& then it is return the value on Process but when I add Test&Tthen Process not return any value.

The query is Select [Name] FROM [V_Test] WHERE ([Name] like '%Test&T%' WHERE (1=1) ORDER BY [ID] desc OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY

Is that any way we can manipulate the search value and pass the '%Test&T%' ?
Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:

Data Shuffling Issue in Table Columns

$
0
0

I am currently working on a component where I'm encountering an issue with data shuffling in one of the table columns.

When I log the row data in the slots for index 8, the console output is unexpected and doesn't appear to be correct. However, the data displayed on the UI seems fine.

LMSDataTable.tsx Componet

import DataTable, { DataTableSlots } from 'datatables.net-react';
import DT, { Config } from 'datatables.net-dt';
import 'datatables.net-fixedcolumns';
import 'datatables.net-fixedcolumns-dt';
import 'datatables.net-responsive-dt';

import './dataTables.dataTables.css';
import './fixedColumns.datatables.css';
import './responsive.datatables.css';
import React, { ReactNode } from 'react';

DataTable.use(DT);

interface LMSDataTableProps {
    children: ReactNode;
    columns: { data: string }[];
    options?: Config;
    slots?: DataTableSlots;
  }

const LMSDataTable : React.FC<LMSDataTableProps> = ({children, columns, options, slots}) => {
    return (
        <>
                    {/* <DataTable data={brandData} columns={columns} className="w-full table-auto"> */}
                    <DataTable columns={columns} className="w-full table-auto"
                    options={options}
                    slots ={slots}
                    >
                        {children}
                    </DataTable>
        </>
    );
};

export default LMSDataTable;

Author.tsx Component

    Other Import......
    import LMSDataTable from '../../components/Tables/LMSDataTable'


    const authorsData: AUTHOR[] = [
        {
            authorId: 78454,
            firstName: "Author Name",
            lastName: "lastName",
            dateOfBirth: new Date(),
            nationality: "nationality",
            photo: "photo",
            bio: "BIO of the author",
            isActive: true
        },
        {
            authorId: 78455,
            firstName: "Author Name 2",
            lastName: "lastName",
            dateOfBirth: new Date(),
            nationality: "nationality",
            photo: "photo",
            bio: "BIO of the author",
            isActive: true
        },
        {
            authorId: 78456,
            firstName: "Author Name 3",
            lastName: "lastName",
            dateOfBirth: new Date(),
            nationality: "nationality",
            photo: "photo",
            bio: "BIO of the author",
            isActive: false
        },
    ];

    const fieldNames = Object.keys(authorsData[0]);
    const columns = fieldNames.map((field) => ({ data: field }));

    columns.push({ data: "Action" });
    console.log(columns);

    const Authors = () => {

        Other Code.........

        const slots = {
            8: (data: string, row: any)=>{
                console.log(row);
                //console.log(row.authorId);
                return  <div className='flex'>
                <button type="button" className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg px-3 py-1.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
                    <FiEdit />
                </button>
                <button type="button" onClick={()=>handleOpen(row)} className="text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg px-3 py-1.5 me-2 mb-2 dark:bg-red-600 dark:hover:bg-red-700 focus:outline-none dark:focus:ring-red-900">
                    <MdDelete />
                </button>
            </div>
            }
        }

        return (
            <>
                {isOpen && (
                    <Modal onClose={handleClose} onConfirm={handleConfirm}>
                        <p>Are you sure you want to delete {selectedAuthor?.firstName} {selectedAuthor?.lastName}?</p>
                    </Modal>
                )}

                <Breadcrumb pageName="Authors" />

                <div className="bg-white border-b border-stroke px-7 py-4 dark:border-strokedark dark:bg-boxdark">
                    <Link
                        to="/authors/add"
                        className="inline-flex items-center justify-center rounded-md bg-primary py-3 px-10 text-center font-medium text-white hover:bg-opacity-90 lg:px-8 xl:px-10"
                    >
                        Add Author
                    </Link>
                </div>


                <div className="bg-white px-5 pt-6 pb-2.5 shadow-default dark:border-strokedark dark:bg-boxdark xl:pb-1">

                    <div className="max-w-full overflow-x-auto">

                        <LMSDataTable columns={columns} options={options} slots={slots}>
                            <thead>
                                <tr className="bg-gray-2 text-left dark:bg-meta-4">
                                    <th className="min-w-[120px] py-4 px-4 font-medium text-black dark:text-white xl:pl-11">Id</th>
                                    <th className="py-4 px-4 font-medium text-black dark:text-white">Photo</th>
                                    <th className="min-w-[120px] py-4 px-4 font-medium text-black dark:text-white">First Name</th>
                                    <th className="min-w-[120px] py-4 px-4 font-medium text-black dark:text-white">Last Name</th>
                                    <th className="py-4 px-4 font-medium text-black dark:text-white">DOB</th>
                                    <th className="py-4 px-4 font-medium text-black dark:text-white">Nationality</th>
                                    <th className="py-4 px-4 font-medium text-black dark:text-white ">BIO</th>
                                    <th className="py-4 px-4 font-medium text-black dark:text-white ">Is Active</th>
                                    <th className="min-w-[120px] py-4 px-4 font-medium text-black dark:text-white ">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {authorsData.map((item) =>
                                    <tr key={item.authorId}>
                                        <td className="border-b border-[#eee] py-5 px-4 pl-9 dark:border-strokedark xl:pl-11">
                                            {item.authorId.toString()}
                                        </td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark flex">
                                            <span className="h-10 w-10 rounded-full">
                                                <img src="http://localhost:5173/images/user/user-01.png" alt="User" />
                                            </span>
                                        </td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">{item.firstName}</td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">{item.lastName}</td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">{item.dateOfBirth.toLocaleDateString()}</td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">{item.nationality}</td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark ">{item.bio}</td>
                                        <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark ">
                                            {!item.isActive && <span className="inline-block rounded  py-0.5 px-2.5 text-sm font-medium bg-red/[0.08] text-red ">InActive</span>}

                                            {item.isActive && <span className="inline-block rounded  py-0.5 px-2.5 text-sm font-medium bg-meta-3/[0.08] text-meta-3 ">Active</span>}
                                        </td>
                                        {/* <td className="min-w-[120px] border-b border-[#eee] py-5 px-4 dark:border-strokedark ">
                                        </td> */}
                                    </tr>
                                )}

                            </tbody>
                        </LMSDataTable>
                    </div>
                </div>
            </>
        );
    };

    export default Authors;

This is showing in the console of the browser

but Data looks ok in the UI

To implement a dynamic table where you can toggle the visibility of columns and save those preferenc

$
0
0

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

datatable column visibility select column save to refesh select column in display bootstrap php

$
0
0

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

To implement a dynamic table where you can toggle the visibility of columns and save those preferenc

$
0
0

To implement a dynamic table where you can toggle the visibility of columns and save those preferences so that the selected columns remain visible or hidden even after a page refresh, we can use the following tools:

Row reorder not update oldPosition and newPosition at drop event

$
0
0

Hi i don't understand how to update new "position" after a rowreorder event was dropped to new position.

I try to tell what i need (using my example at the end):

I have a table with a time start, duration, and time end.
Every row start at the same time the row before ends.

Now if I want to change position for ROW-4 into position ROW#2, I want that the START value of ROW#4 (at new position 2) become the END of ROW#1, and the END of ROW#4 (at the position 2) must be recalculated by its ORIGINAL DURATION.

So:

Phase W with original start at 20, after positioned into position 2, start must became 16 (the end of row 1) and END must became (16 + 4 (original duration of phaseW)) = 20.
Then next rows are calculated with same logic (start became the END of previous row, and END is calculated by the new START + ORIGINAL duration).

So the last ROW END must be ALWAYS 24 of course!

My example above works only 1 times! (try to position PHASE W before PHASE Y).

But now, If I try to do another ordering after new configuration, (example PHASE Z before PHASE W) you can see all STARTS breaks (and of course ENDS)!

The logic is that LAST ROW has always 24 as END because changing order of rows the duration is always the same!

It seems that datatable after dropped row doesn't update the new oldPosition and newPosition attributes?

Here my example:

https://live.datatables.net/garizoxa/368/edit

Table not updating after edit

$
0
0

Hello, I am working with Datatables and Editor. I have the edit working from the edit button (i plan to get inline working next) but after the edit the grid isn't reflecting the change. If I refresh the page the change is there. The service returns 200 and I return the same JSON object that was sent. Should I be doing something else? Do I need to call something to manually refresh the grid?

html5 export buttons doesn't work when loading with importmap

$
0
0

Hi guys,

Im facing a issue when i want to load HTML5 export buttons.

I get this error:
Uncaught Cannot extend unknown button type: copyHtml5

When i try all the packages load in with a cdn then the html5 buttons works, but when i use it with importmap it doesn't. It cannot find the extension copyHtml5, but this extension is in the datatables.net-buttons package.

This is the content of my app.js

import $ from 'jquery';
window.$ = window.jQuery = $;

import './bootstrap.js';
import '@fortawesome/fontawesome-free/css/fontawesome.min.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import './styles/sb-admin-2.css';
import './styles/app.css';
import './styles/select2-bootstrap-5-theme.min.css';
import 'select2/dist/css/select2.min.css';

// Datatables
import DataTable from 'datatables.net-bs5';
import 'datatables.net-bs5/css/dataTables.bootstrap5.min.css';
import 'datatables.net-buttons-bs5/css/buttons.bootstrap5.min.css';
import 'datatables.net-fixedheader';

import pdfMake from 'pdfmake';
import jszip from 'jszip';
pdfMake.fonts = {
    Roboto: {
        normal: 'https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/fonts/Roboto/Roboto-Regular.ttf',
        bold: 'https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/fonts/Roboto/Roboto-Medium.ttf',
        italics: 'https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/fonts/Roboto/Roboto-Italic.ttf',
        bolditalics: 'https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/fonts/Roboto/Roboto-MediumItalic.ttf'
    },
};

import 'datatables.net-buttons';
import 'datatables.net-buttons-bs5';
window.DataTable = DataTable;

import '@popperjs/core';

And the content of my datatable template:

<script type="module">
        $('<div class="loading">Loading</div>').appendTo('body');
        DataTable.ext.buttons.alert = {
            className: 'buttons-alert',

            action: function (e, dt, node, config) {
                alert(this.text());
            }
        };
        let table = new DataTable('#stockListTable', {
            layout: {
                topStart: {
                    buttons: [
                        {
                            extend: 'copyHtml5',
                            text: 'copy'
                        },
                        {
                            extend: 'excel',
                            text: 'Excel'
                        },
                        {
                            extend: 'pdf',
                            text: 'Save current page',
                        },
                        {
                            extend: 'alert',
                            text: 'My button 3'
                        },
                    ],
                }
            },
            fixedHeader: true,
            pageLength: 100,
            ajax: '/api/stock/list',
            columns: [
                { data: 'sku' },
                { data: 'name' },
                { data: 'packing' },
                { data: 'brandName' },
                { data: 'locationName' },
                { data: 'count' },
                { data: 'reservedCount' },
            ],
            initComplete: function (settings, json) {
                $('div.loading').remove();
            }
        });
    </script>

<table id="stockListTable" class="table table-striped table-bordered table-sm">
        <thead>
        <tr>
            <th>Artikelnummer</th>
            <th>Naam</th>
            <th>Verpakking</th>
            <th>Merk</th>
            <th>Locatie</th>
            <th>Voorraad</th>
            <th>Gereserveerd</th>
        </tr>
        </thead>
    </table>

Can you help me tackle this issue?

Thanks!

Wrong option name (detectType)

$
0
0

Hi @allan

I'm looking for the documentation about disable Type Detection detectType and documented here

But the correct option name (working in last version) is typeDetect, as using detectType: false had no effect.
I just realize that because I see the correct name in the settings object.

Hello, im looking for someone that use laravel inertia vuejs3 and datatable.net to ask him?

$
0
0

my question is i need to implement datatable.net to component for use it but i already try it muti times and show me like bugs like:

i have index of users for example has like users and props users come from inertia render

and i have model for create and update and when i update and in datatable show new value but when i search not show but when i search with old name it show but show with new name it like datatable cache old name and show new value HAHAHA
case 2 is when i have one row in datatable and i deleted it show error of nextsiblings on null and row stuck unil i reload page
so please with tips

Datatables send and load data not working in unfiltered datatable

$
0
0

Link to test case: I cannot seem to figure out how to show a test case for my experience (ajax endpoints)
Description of problem:
I'm going to try to lay this out in the best way possible to understand.. I can't even figure out how to title this question right.

  1. I have a datatable that loads a list of projects
ajax : {
            url: "/Projects/GetProjects",
            type: "GET",
            dataType: "JSON"
        },

This table has a drawCallback that forces a reload on a summary table

        drawCallback: function(settings){
            if(DataTable.isDataTable("#SummaryDatatable")){
                console.log("Data Table drawCallback (data visible in API)");
                console.log(datatable.column(1, { filter: 'applied' }).data().flatten().toArray())
                summaryDatatable.ajax.reload();
            }
            
        }
  1. The summary table then POST data back to an API via AJAX with the current data from the Data table
ajax : {
            url: "/Projects/GetSummary",
            type: "POST",
            dataType: "JSON",
            data: function (d) {
                console.log("Summary Table Data Function (data to POST)");
                console.log(datatable.column(1, { filter: 'applied' }).data().flatten().toArray());
                d.projectIds =  datatable.column(1, { filter: 'applied' }).data().flatten().toArray();
            } 
        },

This currently WORKS in all scenarios EXCEPT the full unfiltered list. This includes the first load. The moment I apply any filter/search to Data table, this works flawlessly. If I clear all filters so that it shows nothing filtered in the info, the C# endpoint shows null for the data passed in.

The endpoint:

public IActionResult GetSummary(List<int> projectIds)

Relative screenshots:

Console log

C# Endpoint debugging with filtered results

C# Endpoint debugging with no filters

It might be a C# binding issue, but I've gone through every filter so each id would show (in case there was an id that wasn't an int) and I've parsed the objects from the console, all are the same and valid.

Is there something I'm missing in the documentation to handle unfiltered data? Even though I see it in the console just before asking for a reload... it fires, the end point is hit, but the data is missing.

How could I use Jspreadsheet and DataTable for an application?

$
0
0

How can I combine Jspreadsheet and DataTable in a web application to create a seamless data entry and visualization experience? What would be the steps to allow users to edit data in a spreadsheet-like interface using Jspreadsheet, process that information in the backend, and then display the results in an organized and paginated format with DataTable?

SearchBuilder date format

$
0
0

Hi,

feeling a bit dumb again since I guess this should be easy to solve, but I cannot seem to find the correct solution.

I'm displaying dates in my Datatable using a custom render function.

When I search for date columns using SearchBuilder, it uses the YYYY-MM-DD format. Which is not what my Datatable is using, so it doesn't work.

In the docs, I found:

https://datatables.net/extensions/searchbuilder/examples/initialisation/date-fmt.html

There is says, I'm supposed to use:

DataTable.datetime('HH:mm MMM D, YY');
DataTable.datetime('ddd, MMMM Do, YYYY');

(or whatever date format I need). How does that relate to my render function? Am I supposed to remove the render function? Also, I don't use DataTable.datetime() in my render function since it has time zone issues. Instead, I did something like this:

    DataTable.render.mydatetime = function (fmt) {
      return function (data, type, row) {
        if (type === 'type' || type === 'sort') {
          if (data == null) {
            return null;
          }
          return data.startsWith('0000-00-00') ? null : data;
        }
        return data == null ? null : moment(data).format(fmt);
      };
    };

and in my render function I'm calling DataTable.render.mydatetime('DD.MM.YYYY'); or DataTable.render.mydatetime('DD.MM.YYYY HH:mm:ss') depending on my needs.

So, what I basically need is an option for the SearchBuilder to use the date format from the render function.

Thanks a bunch in advance.


hi, i have a problem with datatables.net-vue3

$
0
0
"datatables.net-dt": "^2.1.8",
"datatables.net-vue3": "^3.0.2",
<DataTable :columns="contractColumns"  :data="contracts">
                        <template #contractRef="{ rowData }">
                            <SimpleLink class="" v-tooltip="`Voir le contrat en PDF`" :href="`/p/contract/${rowData.id}`">
                                {{ rowData.ref }}
                            </SimpleLink>                                
                        </template>
                        <template #endDate="{ rowData }">
                            <Text class="m-0">{{ formatDateTime(rowData.end_date) }}</Text>
                            <SpanField :class="getStatusClass(rowData.start_date, rowData.end_date)">
                                {{ getStatus(rowData.start_date, rowData.end_date) }}
                            </SpanField>
                            <Text class="m-0 badge bg-brown-400" v-if="rowData.extended_duration">Prolonger: {{ rowData.extended_duration }} {{ rowData.is_monthly ? 'Mois' : `Jour${rowData.extended_duration !== 1 ? 's' : ''}` }}</Text>
                        </template>
                        <template #actions="{ rowData }">
                            <Division class="dropdown position-relative">
                                <Button class="btn btn-sm btn-outline-primary rounded dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
                                    Actions
                                </Button>
                                <ul class="dropdown-menu dropdown-menu-end text-sm" aria-labelledby="dropdownMenuButton">
                                    <template v-if="$hasPermission('edit_contract')">
                                        <li><Button class="dropdown-item text-success" @click="closeContract(rowData)">Fermer contrat</Button></li>
                                        <li><hr class="m-1" /></li>
                                        <li><NavLink class="dropdown-item" :href="`/contracts/${rowData.id}/edit`">Modifier</NavLink></li>
                                        <li><Button class="dropdown-item" @click="extendedDuration(rowData)">Prolonger</Button></li>
                                    </template>
                                    <template v-if="$hasPermission('delete_contract')">
                                        <li><hr class="m-1" /></li>
                                        <li><Button class="dropdown-item text-danger" @click="deleteItem(rowData.id)">Supprimer le contrat</Button></li>
                                    </template>
                                </ul>
                            </Division>
                        </template>
                    </DataTable>

            <ExtendedDurationModal ref="ExtendedDurationRef" url="contract-extend-duration" />

import DataTable from 'datatables.net-vue3';
import DataTablesCore from 'datatables.net-dt';
import $ from 'jquery';

DataTable.use(DataTablesCore);
import "datatables.net-dt/css/dataTables.dataTables.min.css";
const contractColumns = [
    { title: 'Contrat', data: null, render: '#contractRef' },
    // { title: 'Nature', data: null, render: '#company' },
    // { title: 'Client', data: null, render: '#client' },
    // { title: 'Véhicule', data: null, render: '#vehicle' },
    // { title: 'Avances', data: null, render: '#total' },
    // { title: 'Prix de location', data: null, render: '#rentPrice' },
    // { title: 'Sortie le', data: null, render: '#startDate' },
    { title: 'Retour le', data: null, render: '#endDate' },
    // { title: 'Agence', data: null, render: '#agency' },
    { title: 'Actions', data: null, render: '#actions' },
];

import ExtendedDurationModal from '@/Components/Contract/ExtendedDurationModal.vue';



const ExtendedDurationRef = ref(null);


const props = defineProps({
    contracts: Object
});

const extendedDuration = (contractObject) => {   
    ExtendedDurationRef.value.openModalExtended(contractObject)
}

here all is work good but just one thing for example i go to page dashboard and return i return to list contract and i click for actions for extended duration it show me
Uncaught TypeError: Cannot read properties of null (reading 'openModalExtended')

DataTables Pagination Issue: Header hides with scrollX Option

$
0
0

I'm using DataTables, and everything works well, but I've encountered an issue when clicking on pagination: the table header hides, leaving only the table body visible. After some debugging, I discovered that the scrollX: true option is causing this problem. I attempted to remove the scrollX: true option and instead wrapped the parent element in a div with overflow enabled. However, this change resulted in scrollbar appearing below the pagination numbers, separate from the table itself. I am unable to reproduce this on datatables.live.net, but I am hoping this is a common problem you may have encountered.

<script>
$(document).ready(function() {
    // Initialize DataTables for all elements with the class 'example-table'
    var table = $('.example-table').DataTable({
         paging: true,
        
          fixedHeader: true,
          "scrollX": true, 
        searching: true,
        info: true,
        ordering: true,
        order: [],
        "scrollCollapse": true,
        dom: 'ifrtBp', // Add the buttons control element
        buttons: [
            {
                extend: 'excelHtml5',
                text: 'Export to Excel',
                titleAttr: 'Export as Excel'
             }
        ]
    });



    // Add event listener for print
    window.onbeforeprint = function() {
        // Disable horizontal scrolling and paging temporarily before printing
        table
            .columns.adjust()
            .draw(false); // Redraw table without changing page
        table.page.len(-1).draw(); // Show all entries

        // Disable overflow and scrolling for both header and body
        $('.dataTables_scrollBody').css('overflow', 'visible'); 
        $('.dataTables_scrollHead').css('overflow', 'visible');
    };

    window.onafterprint = function() {
        // Re-enable horizontal scrolling and restore paging after printing
        table.page.len(10).draw();

        // Restore overflow and scrolling for both header and body
        $('.dataTables_scrollBody').css('overflow', 'auto'); 
        $('.dataTables_scrollHead').css('overflow', 'auto');
    };
});
</script>

Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

SearchBuilder with SSP, how to have the dropdown menu?

$
0
0

Hello, I've seen a lot of cases like mine but none that really answer the question or I just don't understand :smile:

Is it possible with the latest versions to have a dropdown menu instead of a text input for the value?

This sub (https://datatables.net/forums/discussion/71962/searchbuilder-ssp-dropdown-value) seems to answer the question, but there no news if they have well implemented the possibility to have the dropdown menu. And I have read a lot of the docs here, I have found nothing that work for me.

Thank you in advance

React slot render can cause misalignment when horizontally scrollable

$
0
0

Link to test case: https://stackblitz.com/edit/datatables-net-react-simple-miyesp?file=src%2FApp.tsx
Description of problem: Recently I noticed that as long as the table is horizontally scrollable (regardless of whether the scrollX is enabled or not) or when you do enable it (regardless of whether table is horizontally scrollable or not), the slot rendering function leads to misalignment as the rendering continues after the init event. (See console log) And this leads to problems when calculating the column width!

In the demo case, I enabled the option scrollX and the misalignment happens, once I comment it out, the misalignment issue is gone.

I know that we can use the columns.adjust() to adjust the column inside the initEvent, but the problem is that the render still proceed after the initEvent which may lead to wrong column width calculations.

See this demo case with columns.adjust() inside initEvent:
https://stackblitz.com/edit/datatables-net-react-simple-aplnwi?file=src%2FApp.tsx

NOTE: const api = table.current!.dt(); will always to false within initEvent at runtime!! I have to wait until the rendering is completed. As in the demo case, I wait 1 second, which is really unreliable!

My second, slightly better temporary solution is to use setInterval, which clears the interval when the reference is available.
See this demo case with setInterval:
https://stackblitz.com/edit/datatables-net-react-simple-ylsfes?file=src%2FApp.tsx

Again, if the time is set too low, e.g. to 10 ms, there is still the chance that the result will be misaligned after multiple times of page reload.

I wonder is there any better solution for this issue?

datatables.net-react 1.0.0 slots function does not consider all columns

$
0
0

Description of problem: The use of columnDefs with the string _all - all columns (i.e. assign a default) doesn't work for datatables.net-react slots, in the source code, the check for string _all is missing.

It seems that the datatables.net-react repo: https://github.com/DataTables/React is not visible, so I'll post my fix in here.

in the source code:

function applySlots(cache: SlotCache, options: DTConfig, slots: DataTableSlots) {
    if (!options.columnDefs) {
        options.columnDefs = [];
    }

    Object.keys(slots).forEach((name) => {
        let slot = slots[name];

        if (!slot) {
            return;
        }

        // Simple column index
        if (name.match(/^\d+$/)) {
            // Note that unshift is used to make sure that this property is
            // applied in DataTables _after_ the end user's own options, if
            // they've provided any.
            options.columnDefs!.unshift({
                target: parseInt(name),
                render: slotRenderer(cache, slot)
            });
        }
        else {
            // Column name
            options.columnDefs!.unshift({
                target: name + ':name',
                render: slotRenderer(cache, slot)
            });
        }
    });
}

the fix:

function applySlots(cache: SlotCache, options: DTConfig, slots: DataTableSlots) {
    if (!options.columnDefs) {
        options.columnDefs = [];
    }

    Object.keys(slots).forEach((name) => {
        let slot = slots[name];

        if (!slot) {
            return;
        }

        // Apply to all columns
        if (name === '_all') {
            options.columnDefs!.unshift({
                targets: '_all',
                render: slotRenderer(cache, slot)
            });
        }
        // Simple column index
        else if (name.match(/^\d+$/)) {
            // Note that unshift is used to make sure that this property is
            // applied in DataTables _after_ the end user's own options, if
            // they've provided any.
            options.columnDefs!.unshift({
                target: parseInt(name),
                render: slotRenderer(cache, slot)
            });
        }
        else {
            // Column name
            options.columnDefs!.unshift({
                target: name + ':name',
                render: slotRenderer(cache, slot)
            });
        }
    });
}

with this fix, slots like below can work.

            slots={{
                _all: (data, type, row) => {
                    return "<div class='whitespace-normal max-w-60'>" + data || "-" + "</div>";
                }
            }}

which now applies to all columns

Hope it helps!

Edit: Oh! This is not perfect and the _all will overwrite other columns!

Viewing all 82679 articles
Browse latest View live


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