Quantcast
Channel: Free community support — DataTables forums
Viewing all 35371 articles
Browse latest View live

how to edit in column visibility button

$
0
0

datatable have multiple column and those are handel visible or not by column visibility button but i want to some selected column view in column button


observable arrays in KnockoutJS and table updates

$
0
0

Following this pattern:

https://datatables.net/dev/knockout/

Instead of the deprecated array subscription model used in the example, I am using the following:

myResults = ko.mapping.fromJS([]); // an observable array
myResults.subscribe(function (changes) {
        //console.log(changes);
        for (var i = 0; i < changes.length; i++) {
            var item = changes[i];
            switch (item.status) {
                case "deleted":
                    var rowIdx = dt.column(1).data().indexOf(item.value.Id);
                    dt.row(rowIdx).remove();
                    break;
                case "added":
                    dt.row.add(item.value);
                    break;
            }
        }
        dt.draw(); // moved draw function here after all changes are processed...
    }, null, "arrayChange");

I found moving draw out of the for loop improves performance significantly but i still have to call draw again after changes, the row isn't removed from the data table view for some reason - if i had 120 records, i'll see 119 in the paging control but the deleted item is still showing up on the table.

I also had the code below as in the example: but i notice it gets called multiple times and doesnt' quite invalidate the row, it still shows the older data unless I explicitly edit the dt.row(rowIdx).data() object ...

$.each(['VerifiedBy', 'VerifiedOn', 'OtherField'], function (i, prop) {
        that[prop].subscribe(function (val) {
            // Find the row in the DataTable and invalidate it, which will cause DataTables to re-read the data
            var rowIdx = dt.column(1).data().indexOf(that.Id);
            dt.row(rowIdx).invalidate();
        });

I'm trying to figure out how to call draw effectively and how to make changes render, and having quite a difficult time with it - i'll post a live example when I get a chance, for now any feedback on this would be great.

How to sort the child rows hidden in responsive

$
0
0

I need to sort the hidden elements in the child row whrn the datatable is responsive using dt-responsive

DT spelling error

$
0
0

On your front page : Semanic_UI should be Semantic_UI.

multiple issues with sorting column

$
0
0

Hi, when I load page ..datatables fetches database from MYSQL and display as usual.. BUT....

Problem 1: When I click on "Name" header to sort it , it goes blank and doesn't show any data in any column without any error displaying "No data available in table".. i.e empty datatables ....

response :-
{"draw":2,"recordsTotal":0,"recordsFiltered":3,"data":[]}

Problem 2: Though when click on other column headers database is fetched correctly but they are not sorting correctly in ASC and DESC when clicked on headers ..data changes but not in correct order.. NONE OF COLUMN SORTING working Correctly...
response for SORTING EMAIL IDs:-

DESC Email Column:-

{draw: 2, recordsTotal: 3, recordsFiltered: 3,…}
data
:
0
:
["Aman Sharma", "8950376887", "praa@gmail.com", "Hongkong", "Insurance",…]
1
:
["Amar", "5454545477", "amar@gmail.com", "Delhi", "Insurance",…]
2
:
["Sandeep", "8950388989", "sandy@gmail.com", " Paris", "Investment",…]
draw
:
2
recordsFiltered
:
3
recordsTotal
:
3

ASC EMAIL Column :

{draw: 3, recordsTotal: 3, recordsFiltered: 3,…}
data

0
:
["Sandeep", "8950388989", "sandy@gmail.com", " Paris", "Investment",…]
1
:
["Amar", "5454545477", "amar@gmail.com", "Delhi", "Insurance",…]
2
:
["Aman Sharma", "8950376887", "praa@gmail.com", "Hongkong", "Insurance",…]
draw
:
3
recordsFiltered
:
3
recordsTotal
:
3

My code to fetch data fetch.php:-

<?php include('db.php'); include('function.php'); $query = ''; $output = array(); $query .= "SELECT * FROM client "; if(isset($_POST["search"]["value"])) { $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" '; $query .= 'OR address LIKE "%'.$_POST["search"]["value"].'%" '; $query .= 'OR phone LIKE "%'.$_POST["search"]["value"].'%" '; $query .= 'OR email LIKE "%'.$_POST["search"]["value"].'%" '; $query .= 'OR query LIKE "%'.$_POST["search"]["value"].'%" '; } if(isset($_POST["order"])) { $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' '; } else { $query .= 'ORDER BY id DESC '; } if($_POST["length"] != -1) { $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length']; } $statement = $connection->prepare($query); $statement->execute(); $result = $statement->fetchAll(); $data = array(); $filtered_rows = $statement->rowCount(); foreach($result as $row) { $sub_array = array(); $sub_array[] = $row["name"]; $sub_array[] = $row["phone"]; $sub_array[] = $row["email"]; $sub_array[] = $row["address"]; $sub_array[] = $row["query"]; $sub_array[] = 'Update Delete';; $data[] = $sub_array; } $output = array( "draw" => intval($_POST["draw"]), "recordsTotal" => $filtered_rows, "recordsFiltered" => get_total_all_records(), "data" => $data ); echo json_encode($output); ?>

function.php :-

<?php function get_total_all_records() { include('db.php'); $statement = $connection->prepare("SELECT * FROM client"); $statement->execute(); $result = $statement->fetchAll(); return $statement->rowCount(); } ?>

Field Names with Space.

$
0
0

This:

Results in this:

But This:

Results in no sql error.....

but but result set field name has the brackets "[]":

and therefore:

Also If I add brackets around a field name that does have a space [Name]:

Results in double brackets "[[Name]]" and therefore:

How do I work with field names with Spaces. I notice there are none in the example. Is this because it's not supported?

Requested unknown parameter

$
0
0

I have been battling with this for days and I can't figure it out. Please help

Error:
DataTables warning: table id=table_id - Requested unknown parameter 'password' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Json:
[
  {
    "password": "MD5HASH"
  },
  {
    "password": "MD5HASH"
  },
  {
    "password": "MD5HASH"
  },
  {
    "password": "MD5HASH"
  },
  {
    "password": "MD5HASH"
  },
  {
    "password": "MD5HASH"
  }
]
Html:
<table id="table_id" class="display">
    <thead>
        <tr>
            <th>password</th>
        </tr>
    </thead>
</table>
JS:
$(document).ready(function () {
    $('#table_id').DataTable({
        "info": true,
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": '@Url.Action("LoadResults", "Search")',
            "dataSrc": ''
        },
        "columnDefs": [{
            "defaultContent": "BOB"
        }],
        "columns": [{
            "data": "password"
        }]
    });
});

Editor using Mjoin for three tables

$
0
0

Hi everybody,

I'm a little bit confused about the usage of the Editor's Mjoin-Feature and if it is possible to use it to join three tables together - or what will be the best practice to implement it?!

I have the three tables

+-----------------+     +-----------------+     +-----------------+
| projects        |     | target          |     | status          |
+-----------------+     +-----------------+     +-----------------+
| id              |     | id              |     | id              |
| name            |     | name            |     | name            |
+-----------------+     +-----------------+     +-----------------+

This will be joined in a table

+-------------------------+
| projects_targets_status |
+-------------------------+
| project_id              |
| target_id               |
| status_id               |
+-------------------------+

When I tried to join the three tables to the bottom one (using the link function) I'll get the error, that link can only be used twice.

So I'm wondering if there's a way to get an editor in which it is possible to create/edit/delete entries for the latter table.

Here's the code I tried to use:

$editor = Editor::inst($db, 'projects')
    ->debug(true)
    ->field(
        Field::inst('projects.title')
    )
    ->join(
        Mjoin::inst('portals')
            ->link('projects.id', 'projects_portals_states.project_id')
            ->link('portals.id', 'projects_portals_states.portal_id')
            ->link('states.id', 'projects_portals_states.state_id')
            ->order('name')
            ->fields(
                Field::inst('id')
                    ->validator('Validate::required')
                    ->options(Options::inst()
                        ->table('portals')
                        ->value('id')
                        ->label('name')
                    ),
                Field::inst('name')
            )
    )
    ->join(
        Mjoin::inst('states')
        ->link('projects.id', 'projects_portals_states.project_id')
        ->link('portals.id', 'projects_portals_states.portal_id')
        ->link('states.id', 'projects_portals_states.state_id')
        ->order('name')
        ->fields(
            Field::inst('id')
                ->validator('Validate::required')
                ->options(Options::inst()
                    ->table('states')
                    ->value('id')
                    ->label('name')
                )
        )
    )
    ->process($_POST)
    ->json();

Any help is appreciated.

Regards,
Dennis


Permanent Inline Checkboxes -- click/change only registered "outside" of containter

$
0
0

I'm following the blog article Permanent Inline Checkboxes and Always Shown Checkbox. This is pretty awesome, and I've had success implementing it. Side note: I'm using Bootstrap. I had to use text-center for columns.className.

As I click the checkboxes, "checks" and "unchecks" ARE registered, and sent to the database. Information coming back from the database is displayed appropriately.

If I stay inside of the <td>checkbox</td> field, it will not register new clicks (checks or unchecks). Also, you've got to be pretty precise when clicking the checkbox; If you click just outside, no new clicks are registered. Lastly, there's a weird blue box around the input, presumably from the OS.

ANYWAY, If I go from row, to row, to row, and click the boxes, things work as expected. Problems occur if you stay inside of the <td>Publish</td>, and try to re-click the box.

What should I be looking at? Can you recommend an approach to fix this? Should I render the html differently?

editor = new $.fn.dataTable.Editor({
    table: "#example",
    fields: [
        {
            label: "Publish:",
            name: "Publish",
            type: "checkbox",
            /**
             * use the separator option to have Editor submit the data as a string, 
             * rather than as an array
             */
            separator: "|",
            options: [
                { label: "", value: 1 }
            ],
            //unselectedValue: 0
        },
    ],
table = $('#example').DataTable({
    dom: "Bfrtip",
    data: aoo,
    columns: [
        {
            data: 'Publish',
            title: 'Publish',
            visible: true,
            render: function (data, type, row) {
                if (type === 'display') {
                    return '<input type="checkbox" class="editor-publish">';
                }
                //return data;
                return (data == 0) ? '0' : '1';
            },
            className: "text-center"
        }
    ],
    /**
     * select the row if any part of the row is clicked, except for the last column
     */
    select: {
        style: 'os',
        selector: 'td:not(:last-child)' // no row selection on last column
    },
    buttons: [
        { extend: "create", editor: editor },
        { extend: "edit", editor: editor },
        { extend: "remove", editor: editor }
    ],
    rowCallback: function (row, data) {
        /**
         * Set the checked state of the checkbox in the table.
         * rowCallback function is run for every row that is displayed by DataTables
         */
        $('input.editor-publish', row).prop('checked', data.Publish == 1);
    }
});

// Activate an inline edit on click of a table cell
$('#example').on('click', 'tbody td', function (e) {
    editor.inline(this);
});

$('#example').on('change', 'input.editor-publish', function () {

    /**
     * https://datatables.net/blog/2014-09-09
     */
    editor
        //call the edit() method to start an edit for the row; do not display form (as it would by default)
        .edit($(this).closest('tr'), false)
        //the set() method is used to set the value of the field based on the checkbox that was toggled
        .set('Publish', $(this).prop('checked') ? 1 : 0)
        .submit();
});

First Time Configuration & Specific Table Queries

$
0
0

Searching for the best way to sort my tables, I came across DataTables and was instantly sold by the table shown on their landing page, in which you can click to show additional details per name.

This is of high interest as one of the reasons I wish to use this system is that each row I would have as a summary and within the details defined to that person.

Questions

  1. What is the recommended package download for someone who uses jQuery.3.3.1 without Bootstrap?
  2. Where can I find the DataTable on the landing page within the demos to see minimal code required?
  3. Is there a "Go To Page" function available, eg; used within a ranking system, go to users rank?
  4. Is it possible to have, within one table:
  • Main Table (entire scope) scrollable.
  • Click to show details on a user basis, inner table also scrollable

Thank you for any help in getting started prior!

Best Regards,
Tim

Automatic change of one field after changing another

$
0
0

Hello. Can I make it so that when the value in one of the cells changes, the function of updating the value in another cell automatically works? For example, there are fields "Number 1", "Number 2" and "Sum". After changing the fields "Digit 1" or "Digit 2" the function of the amount recalculation should work and further the received value should be updated in the "Amount" cell. All this should be preserved in the database, and then return the value to the cell.

Additional last row to display accumulated data.

$
0
0

Hi, I would like to add a row to accumulate the records and display the total amount as the last row. I have been searching for similar examples but I have not found one yet, does anyone knows how to solve this?

I have included an example table that I would like to create, to accumulate all records above in an additional row at the bottom to display the total.

Is it possible to achieve a series of nested tables like this with Datatables?

$
0
0

See attached image. I'm trying to achieve a technique where the rows example and reveal higher level data. Could this be done with rowspans or the grouping functions in datatables? Any pointers are appreciated.

Bootstrap 4 and datatables dont work seem to work together

$
0
0

Hello everyone,

I was wondering if people could check out why my datatables isn't working when I'm using bootstrap 4.

Before I never used bootstrap , now I started to use it and combine it with datatables my datatables doesn't work anymore.

Maybe I have the wrong CDN's , or something else

Could you please check it ou my code here? https://paste.ofcode.org/x7vNXtKwdyySEAR9sTD6WX

Regards

sjaakie

How to add "date" from column to title

$
0
0

I have a column dates in table and when i search for a certain date it should be able to print only that date with the title of that date. Table for that date is printed automatically and works beautiful, but i cannot put that date into the title. Any help?


How to solve the problem that the child form and parent form are not aligned

$
0
0

The inner and outer tables have the same structure, and the inner layer has no header. After embedding, the sub-table is shifted to the right as a whole.

Asp.net Core Editor example

$
0
0

First of all, a bit of background - recently started my first asp.net core project, or it would more precise to say first dev project in like 10 years, so yeah, currently rate myself a newb in development.

So when I got the multi-tenancy, authentication, authorization done, I started to look for UI elements for my project, came across datatables, and was pretty sure that I would love to include this UI element in my project. Editing data grids is a must for me, so it was disappointing to find out that there is no libraries for asp.net core for Editor server-side. Although I haven't yet bought it, I decided to try to implement the server side myself. Long story short, 2 days later I have editable table, and I am willing to share my solution, as it could help someone else or me (by someone improving upon it). So here we go.

  1. Models
    public class ProjectType

    {
        [Required]
        public int Id { get; set; }
        [Required]
        public string ProjType { get; set; }


    }
 public class ProjectTypeDTable : ProjectType
    {
        public string DT_RowId { get; set; }
    }
  1. Editor and datatable initialization
    <script type="text/javascript">
        

        $(document).ready(function () {

            var editor = new $.fn.dataTable.Editor({
                ajax: {
                    url: '/api/dtprojecttype',
                    data: function (d) {
                        return JSON.stringify(d);
                    },
                    contentType: "application/json"
                },
                table: '.projecttypes-table',
                idSrc: 'id',

                fields: [
                    {
                        name: "projType",
                        label: "Project Type: "
                    }
                ],
            });

          var generateProjectTypesTable = 
                $('.projecttypes-table').DataTable({
                    columns: [
                        {
                            data: "id",
                            searchable: false,
                        },
                        
                        { data : "projType" }

                    ],
                    ordering: true,
                    paging : true,
                    pagingType : 'full_numbers',
                    pageLength : "25",
                    select : true,
                    dom: '<"html5buttons"B>lTfgitp',
                    buttons : [
                        { extend: 'create', editor: editor },
                        { extend: 'edit', editor: editor },
                        { extend: 'remove', editor: editor },
                        { extend: 'copy' }
                    ]

                });         

            //$('.projecttypes-table').on('click', 'tbody td', function () {
            //    editor.inline(this);
            //});

        });

    </script>

  1. Server side api action
 public async Task<IActionResult> Post([FromBody]JObject request)
        {
            //split incomming JSON object into action and data JTokens
            var action = request.GetValue("action").ToString();
            var data = request.GetValue("data");

            IList<ProjectTypeDTable> testchangedobjects = new List<ProjectTypeDTable> { };
            test

            //define new list for changed objects
            IList<ProjectTypeDTable> changedobjects = new List<ProjectTypeDTable> { };

            //parse json to class objects
            changedobjects = changedobjects.DTableEditParser(request, "Id", "Int");

            //create empty List for response objects
            IList<ProjectTypeDTable> responseobjects = new List<ProjectTypeDTable> { };


            if (action == "create")
            {
                foreach (var x in changedobjects)
                {
                    var changed = new ProjectType
                    {
                        ProjType = x.ProjType
                    };

                    changed = await _tenantdbrepo.AddProjectTypeAsync(changed);

                    responseobjects.Add(new ProjectTypeDTable { Id = changed.Id, ProjType = changed.ProjType, DT_RowId = "row_" + changed.Id.ToString() });
                };
            }
            else if (action == "edit")
            {
                foreach (var x in changedobjects)
                {
                    var changed = new ProjectType
                    {
                        Id = x.Id,
                        ProjType = x.ProjType
                    };
                        
                      changed =  await _tenantdbrepo.UpdateProjectTypeAsync(changed);
                    responseobjects.Add(new ProjectTypeDTable { Id = changed.Id, ProjType = changed.ProjType, DT_RowId = x.DT_RowId ?? "row_"+changed.Id });
                };
            }
            else if (action == "remove")
            {
                foreach (var x in changedobjects)
                {
                    var changed = new ProjectType
                    {
                        Id = x.Id,
                        ProjType = x.ProjType
                    };
                    await _tenantdbrepo.RemoveProjectTypeAsync(changed);
                };
            };

            
            if (responseobjects.Any())
            {
                dynamic response = new
                {
                    data = responseobjects
                };
                return Json(response);
            }
            else
            {
                dynamic response = new { };
                return Json(response);
            };

        }
  1. My extension that parses the json to objects
public static class DatatablesEdit
    {

   
    public static IList<T> DTableEditParser<T>(this IList<T> source,  JObject json, string id, string idtype)
        {
            //split incomming JSON object into action and data JTokens
            var action = json.GetValue("action").ToString();
            var data = json.GetValue("data");

            IList<T> changedobjects = new List<T> { };

            foreach (JProperty x in data)
            {
                //initialize empty object of class
                T changedobject = (T)Activator.CreateInstance(typeof(T));
                

                //set object's ID property to JSON objects Name
                if (idtype =="int")
                {
                    changedobject.GetType().GetProperty(id).SetValue(changedobject, Int32.Parse(x.Name.ToString()));
                } else if (idtype == "string")
                {
                    changedobject.GetType().GetProperty(id).SetValue(changedobject, x.Name.ToString());
                }
                
                

                //loop through each of JSON object sub properties, change the property name from camel case to pascal case and map to object's properties
                foreach (JProperty y in x.Value)
                {
                    string propertyname = char.ToUpper(y.Name[0]) + y.Name.Substring(1);

                    if (changedobject.GetType().GetProperty(propertyname).PropertyType.Name == "String")
                    {
                        changedobject.GetType().GetProperty(propertyname).SetValue(changedobject, y.Value.ToString());
                    }
                    else if (changedobject.GetType().GetProperty(propertyname).PropertyType.Name == "Integer")
                    {
                        changedobject.GetType().GetProperty(propertyname).SetValue(changedobject, Int32.Parse(y.Value.ToString()));
                    }
                }
                //add object to changed objects List
                changedobjects.Add(changedobject);
            }


            return changedobjects;
        }
       
    }

I am sure that the code is far from optimal, but I am pretty proud of myself to get this working. Any improvements appreciated.

Editor Custom Form - Input below legend

$
0
0

Hi there!
I'm using the example Custo Form, with bootsrap-4, but I need input fields below Caption, i.e. in col-12 not col-8.
Inspecting Element says editor creates come "DTE" elements:
..div data-dte-e="input" class="col-lg-8"..
How do I control this to generate col-lg-12 in Caption and in Input field?
Thanks for any help
Fracnsico

why is there a misalignment of datatable headers and body when side menu is collapsed on the webpage

$
0
0


> >
>
> > > > > > > > > > > > > > > > > > >
IDMobile NumberService ProviderSIM NumberRemarksRemarksRemarksRemarksRemarksModeAction
>
>
> >

Get data via AJAX when leaving the field

$
0
0

Hello all,

sorry i am new and inexperienced!

As an example, I would like to add articles in an invoice.

I have the fields item number, article name, quantity and price.
If I enter the article number and leave the field, I would like to retrieve the article name and the price from the database via AJAX and write it into the grid.
Is there an example for this?

I looked at all the examples and found no solution.

regards,
Kostas

Viewing all 35371 articles
Browse latest View live