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

Query where cause 2 field ID

$
0
0
        Editor::inst($db, **tablename**)
        ->pkey('ID')
        ->fields(
            Field::inst('ID'),
            Field::inst('ORGANIZATION_ID'),
            Field::inst('BARCODE'),
            Field::inst('ITEM_NO'),
            Field::inst('DESCRIPTION'),
            Field::inst('ONHAND_QTY'),
            Field::inst('ONHAND_UOM'),
            Field::inst('ACTUAL_QTY'),
            Field::inst('ACTUAL_UOM'),
            Field::inst('REMARK')
        )
        ->where('ACTUAL_QTY',null,'<>')
        ->where(**Field::inst('ACTUAL_QTY')**, **Field::inst('ONHAND_QTY')**,'<')
        ->debug(true)
        ->process($_POST)
        ->json();

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 many 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;
    } ), 

Cannot edit row when the primary key is a string contains space

$
0
0

Hi,
I have a table that contains 2 columns:

+-------------+-----------+
| category    |  level   |
+-------------+-----------+
| Cat         |     1     |
| Cat A       |     2     |
| Cat B       |     1     |
| ....        | ...       |
+-------------+-----------+

on Client Side I create a simple editor:

editor = new $.fn.dataTable.Editor({
        ajax: url + "json",
        table: "#detail",
        fields: [
            {
                label: "Category",
                name: "category",
                type: "display"
            },
            {
                label: "level",
                name: "level"
            },
        ]
    });

on Server Side (PHP):

$DB  = $this->editorlib->getDatabase();
$ed = new Editor($DB, "category_table","category");
$ed->debug(true);
$ed->fields(
    Field::inst('category')->set(false),
    Field::inst('level')
);
$ed->process($_POST);
$ed->json();

When I tried to update Cat A level value to another value (3), the row is not updated but a new row with category value '0', and level value 3 inserted instead.

+-------------+-----------+
| category    |  level    |
+-------------+-----------+
| Cat         |     1     |
| Cat A       |     2     |
| Cat B       |     1     |
| 0           |     3     |
+-------------+-----------+

Debug log:

{
   "data":[
      {
         "DT_RowId":"row_0",
         "category":"0",
         "level":3
      }
   ],
   "debug":[
      {
         "query":"SELECT  category as \"category\" FROM  category_table WHERE category = :where_0 ",
         "bindings":[
            {
               "name":":where_0",
               "value":"0",
               "type":null
            }
         ]
      },
      {
         "query":"UPDATE  category_table SET  level = :level WHERE category = :where_0 ",
         "bindings":[
            {
               "name":":level",
               "value":"3",
               "type":null
            },
            {
               "name":":where_0",
               "value":"0",
               "type":null
            }
         ]
      },
      {
         "query":"SELECT  category as \"category\", level as \"level\" FROM  category_table WHERE category = :where_0 ",
         "bindings":[
            {
               "name":":where_0",
               "value":"0",
               "type":null
            }
         ]
      }
   ]
}

From the log above we can see that the binding for ':where_0' is incorrect. It should be "Cat A".

However if I edit the 'Cat' Category, it works fine.

If it's possible, I would like to avoid changing the database structure and add a new primary key.

Thank you.
Danny.

Inline editor sometimes not working

$
0
0

I have working code that only fully works when I do a hard refresh on the page. In this case, the inline "td" editor input receives focus, the cursor appears inside the input, the user can edit the text directly in the table.

However, when I merely reinitialize the DataTable (and associated global editor variable) without a full page reload, the DataTable successfully loads the data, but afterwards, the only way to edit a row is to manually select the cell which contains the primary key (ID), then click the Edit button, which brings up the "Edit entry" dialog, then the user has to click the Update button on the dialog.

I am proactively calling this before i reinitialize. But it does not appear to be enough.
$("#tblJudges").DataTable().destroy();

How can I get the inline editors to appear every time i initialize (or merely reinitialize) the DataTable?

cannot read property 'length'

$
0
0

I have looked at other posts on the forum but I don't see the resolution to my issue.

            var ToGenerateTable = $('#ToGenerate').DataTable({
                dom: 'frtip',
                ajax: 'api/ToGenerate',
                dataSrc: 'Table',
                idSrc: 'ImportID',
                columns: [
                    { data: "ImportID" },
                    { data: "DeptName" },
                    { data: "FTE" },
                    { data: "EmployeeCount" }
                ]
            })

json:

{"Table":[{"ImportID":121,"DeptName":"Ag Commissioner","FTE":48.15,"EmployeeCount":50},...

Print button orientation = landscape

$
0
0

Hi,
always portrait print? landascape not working in print button?

buttons: [
    {
        extend: 'print',
        text: '<img src="images/printer24x24.png" alt="">',
        titleAttr: 'Imprimir',
        columns: ':not(.select-checkbox)',
        orientation: 'landscape'
    }
]

Changing bottom button color

$
0
0

I have two rows of buttons, I was able to change the className for the top row but the bottom initialization shows up with only the font color changed even though I used the same className as in the top row. How do I override the normal button appearance for the bottom row?

Also, how does one go about putting spaces between the top row buttons? The CSS for margin-right or anything isn't working at all.

        new $.fn.dataTable.Buttons( dt, {
        buttons: [
            {
                
                text: "Button 2",
                action: function ( e, dt, node, conf ) {
                    alert( "Button 2 clicked on" );
                },
                

            },

        ]
        
    } );

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.


dynamic columns

$
0
0

I found other posts that deal with grammatically creating columns. My data seems exactly the same but I am getting an error. So I am guessing it is because my json is formatted differently.

Here is the link where someone else got it working: https://datatables.net/forums/discussion/comment/162006/#Comment_162006

Here is my code:

            var columns = []; 
            $.ajax({
                url: "api/ToGenerate",
                success: function (data) {
                    //tableData = JSON.parse(data);  //Unexpected token o in JSON at position 1
                    tableData = JSON.parse(JSON.stringify(data));    // Cannot read property '0' of undefined
                    
                    columnNames = Object.keys(tableData.data[0]);
                    for (var i in columnNames) {
                        columns.push({
                            data: columnNames[i],
                            title: columnNames[i]
                        });
                    }
                    
                    $('#ToGenerate').DataTable({
                        dom: 'frtip',
                        ajax: {
                            url: 'api/ToGenerate',
                            dataSrc: 'Table'
                        },
                        rowId: 'ImportID',
                        columns: columns
                    })
                }

            });

here is the format of my JSON

{"Table":[{"ImportID":121,"DeptName":"Ag Commissioner","FTE":48.15,"EmployeeCount":50}...

the first line of code JSON.parse(data) results in 'unexpected token...
the second line of code (from the post that I have the link to above) results in Cannot read property '0' of undefined and is talking about the line: columnNames = Object.keys(tableData.data[0]);

So I assume something is wrong with the structure of the object tableData but I can't figure it out.

R user

$
0
0

hi dear
I am R user , I need how to convert code in DataTables to DT package in R
thx for your valuable help

Customizing the page numbers to show in pagination using jquery datatables

Modal to display 2 rows

$
0
0

Hello, I have been using DataTables for a while now and is fantastic but have a query which I am unable to resolve. My data is in pairs (odd + even) in a repeating pattern. Using a responsive table, the modal shows whatever column you click (eg, row 1) but I would like to show the pair (1+2 or 3+4, 5+6 etc). If the odd row is clicked it shows the even number following also and if the even row is clicked it shows the previous odd row in the modal.

Is this possible to achieve?

Thanks in advance.

Automatic selection of an added row

$
0
0

I am a satisfied Editor user in serverside mode and bootstrap4 with pagination.
I use tabs for parent / child editing and pagination (see image).

I would like a new row added in "Anagrafica" to be automatically selected in order to enable the "Riferimenti" and "Diario" tabs for inserting new data without looking for the row in the pages in alphabetical order.
The selected page should become the one where the row is located and it should be highlighted.
Is it possible to do such a thing?
Thank you,
Giuseppe

Invalid JSON Data with Newtonsoft JSON Serializer

$
0
0

Hi, I'm making a web app using ASP.NET Core and Entity Framework Core.
And I have a table called Items. I pass the list of items to DataTables using Newtonsoft JSON Serializer.
I don't know why I got this error every time I have a lot of Item data, but this doesn't happen in other lists / DataTables (yet).

DataTables warning: table id=ItemTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

Currently, I have 21 rows of Item data. And this actually happened several times.
1. I use this code and my data is at 15 rows, got that error.
public string GetAll()
{
var model = _itemRepository.GetAll();

            var settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            var serialized = JsonConvert.SerializeObject(model, Formatting.Indented, settings);

            return serialized;
        }

2. I've changed the code to this, I can store up to 17-21 rows and after row 21 I get that error again.
public string GetAll()
{
var model = _itemRepository.GetAll();

                var settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };
                var serialized = JsonConvert.SerializeObject(model, settings);

                return serialized;
            }

This is my DataTable inside my Item List view

var table = $("#ItemTable").DataTable({
                "processing": true,
                "ajax": {
                    "url": "Item/GetAll",
                    "dataSrc": ""
                },
                "columnDefs": [
                    {
                        "targets": 0,
                        "title": "Id",
                        "data": "Id",
                        "visible": false
                    },
                    {
                        "targets": 1,
                        "title": "Brand",
                        "data": "Brand.Name"
                    },
                    {
                        "targets": 2,
                        "title": "Name",
                        "data": "Name"
                    },
                    {
                        "targets": 3,
                        "title": "Price",
                        "data": "Price",
                        "render": $.fn.dataTable.render.number( ',', '.', 2, 'Rp ' ),
                        "searchable": false
                    },
                    {
                        "targets": 4,
                        "title": "UoM",
                        "data": "UoM.Name"
                    },
                    {
                        "targets": 5,
                        "title": "Category",
                        "data": "Category.Name"
                    },
                    {
                        "targets": 6,
                        "title": "Stock On Hand",
                        "data": "StockOnHand",
                        "render": $.fn.dataTable.render.number( ',' ),
                        "searchable": false
                    },
                    {
                        "targets": 7,
                        "title": "On Reserved",
                        "data": "OnReserved",
                        "render": $.fn.dataTable.render.number( ',' ),
                        "searchable": false
                    },
                    {
                        "targets": 8,
                        "title": "Actions",
                        "data": null,
                        "searchable": false,
                        "orderable": false,
                        "render": function (data, type, row) {
                            if (data.ActiveStatus == "Active") {
                                return "<div class=\"btn-group\">" +
                                    "<button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">" +
                                    "Actions" +
                                    "</button>" +
                                    "<div class=\"dropdown-menu\">" +
                                    "<a id=\"Detail\" class=\"dropdown-item\" href=\"#\"><i class=\"fas fa-stream\"></i>&nbsp;&nbsp;Details</a>" +
                                    "<a id=\"Edit\" class=\"dropdown-item\" href=\"#\"><i class=\"fas fa-pen\"></i>&nbsp;&nbsp;Edit</a>" +
                                    "<div class=\"dropdown-divider\"></div>" +
                                    "<a id=\"SetInactive\" class=\"dropdown-item\" href=\"#\"><i class=\"far fa-square\"></i>&nbsp;&nbsp;Inactive</a>" +
                                    "<div class=\"dropdown-divider\"></div>" +
                                    "<a id=\"Delete\" class=\"dropdown-item\" href=\"#\"><i class=\"fas fa-trash\"></i>&nbsp;&nbsp;Delete</a>" +
                                    "</div>" +
                                    "</div>";
                            }
                            else if (data.ActiveStatus == "Inactive") {
                                return "<div class=\"btn-group\">" +
                                    "<button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">" +
                                    "Actions" +
                                    "</button>" +
                                    "<div class=\"dropdown-menu\">" +
                                    "<a id=\"Detail\" class=\"dropdown-item\" href=\"#\"><i class=\"fas fa-stream\"></i>&nbsp;&nbsp;Details</a>" +
                                    "<a id=\"Edit\" class=\"dropdown-item\" href=\"#\"><i class=\"fas fa-pen\"></i>&nbsp;&nbsp;Edit</a>" +
                                    "<div class=\"dropdown-divider\"></div>" +
                                    "<a id=\"SetActive\" class=\"dropdown-item\" href=\"#\"><i class=\"far fa-check-square\"></i>&nbsp;&nbsp;Active</a>" +
                                    "<div class=\"dropdown-divider\"></div>" +
                                    "<a id=\"Delete\" class=\"dropdown-item\" href=\"#\"><i class=\"fas fa-trash\"></i>&nbsp;&nbsp;Delete</a>" +
                                    "</div>" +
                                    "</div>";
                            }
                        }
                    }
                ],
                "order": [[2, "asc"]],
                "createdRow": function (row, data, dataIndex) {
                    if (data.ActiveStatus == "Inactive") {
                        $(row).addClass("table-warning");
                    }
                }
            });

This happens only on Item. Loading data takes a little bit too long. When I check the output of the GetAll method, it returns JSON like string, and it is a very long and I think it never ends, just keep scrolling.

Please help. If you need my code, I could send them.

Thank you, kind regards
Michael Reno

datatable load issue


FixedColumns not working !

$
0
0

My table is RowSpan type.

My code.

Adding data attributes depending on ajax data

$
0
0

Hello.
I want to pass a data to my Datatable with structure like this

[{mainValue: 1, additionalValue: 'one'}, {mainValue: 2, additionalValue: 'two'}... and so on] 

and then in resulting table get a cells in format like this (adding main value as text inside a cell and second value as data-attribute):

<td data-value="one">1</td>
<td data-value="two">2</td>

I know. that I can export 'mainValue' by columns.data option but how can I adding data-attribute with additional value?

FixedHeaders (v3.1.6): Any reference to original table?

$
0
0

I have some custom header-level elements that have behavior that I would like to maintain on the fixed header. Does anyone know if the created fixed position table has any reference to the dataTable it originated from? I haven't noticed anything that consistently ties it to the table that created it, so far. Just want to make sure there isn't anything out-of-box that I'm missing before I create my own solution. Thanks in advance!
DataTable version: 1.10.20

Editor autocomplete return values

$
0
0

Good afternoon (o;

As my project already uses autocomplete from jqueryui I give it a go as well with the editor..
But I am stuck what to exactly return from the ajax call.

Got this framework I've found here:

            label: "Artikelnummer",
            name: "Artikelnummer",
            type : "autoComplete",
            minLength: 2,
            opts: {
            source: function (query, result) {
                        $.ajax( {
                            url: '/inc/get.products.php',
                            dataType: 'json',
                            success: function ( data ) {
                                result ( $.map( data,    function (item) {
                                    console.log(data.data);
                                    return {
                                        label: data.data.number, << no clue yet (o;
                                        value: data.data.number << no clue yet (o;
                                    };
                                }
                            )
                            )
                        }
                    });
            }
            }

The PHP code just returns an array with all products availabe, and the editor autocomplete should fill then two fields automatically when selected...

So my simple question..what exactly do I have to return in the ajax call to autocomplete so it displays the product list matching they typed input?

I'm not that JS guru (o;

thanks in advace
richard

i used the destroy function to reload the table and data but the table is not loading please help

$
0
0
function get_all()
        {
            $('#tbl-category').dataTable().fnDestroy();
            $.ajax({
                url : "../php/all_category.php",
                type : "GET",
                dataType : "JSON",

                success:function (data) {

                    $('#tbl-category').dataTable({
                        "aaData": data,
                        "scrollX": true,
                        "aoColumns": [
                            {"sTitle": "Category", "mData": "catname"},
                            {
                                "sTitle": "Status", "mData": "status", "render": function (mData, type, row, meta) {
                                    if (mData == 1) {
                                        return '<span class="label label-info">Active</span>';
                                    }
                                    else if (mData == 2) {
                                        return '<span class="label label-warning">Deactive</span>';
                                    }
                                }
                            },

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

Viewing all 81696 articles
Browse latest View live


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