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

Columns custom width resetted after scroll down and up (with fixedHeader plugin)

$
0
0

Hi,
I have a problem with custom width on <th>, using fixedHeader plugin.
If I set for example a th like this:

<th style="width:400px">Large column</th>

and I scroll down (until the fixed header appears) and up again, the width of the column will fit the content instead of being 400px.
This is the config:

{
    autoWidth: false,
    fixedHeader: true,
    responsive: true,
}

This is the fiddle:
http://live.datatables.net/dubefetu/1/edit?html,css,js,console,output

Thanks in advance


Keep Child Rows open on Draw

$
0
0

Hello,

I know this question have been up hundreds of times.
I have read almost every topic on the Internet, but I can't still get it to work.

I have enabled Responsive and as such some columns are hidden when the screen size is to small to fit them all.
When I select to show these columns with the plus sign, a child row is beeing open.
When the table reloads (a draw is done every 15 seconds), all open child rows closes.

I have found this:
https://datatables.net/forums/discussion/29199/how-can-i-keep-child-rows-opened-after-the-ajax-reload

The problem is that I don't think that is applicable to Responsive as that solution seems to need a static content (and not depending on the columns actually hidden).

I have also found this:
https://datatables.net/forums/discussion/43577/rows-close-when-ajax-updates

Stating (I think) that Responsive should actually take care of it by it-self.
That is not the case for me (running the latest version of DataTables and Responsive as of today).

I have the following enabled:

"responsive": true,
"stateSave": true,

I have run the debugging tool and it reports no failures or warnings.

What am I missing?

Regards,
Lucas

SearchPanes and option stateSave: true, refresh data issue

$
0
0

A datatable reloads the data in a period of x seconds.
In order to refresh the view, i call $('#mytable-id').DataTable().clear().rows.add(<new data>).draw();
After that i call $('#mytable-id').DataTable().searchPanes.rebuildPane();
If i do so, searchPanes is rebuild with the initial state of the DataTable. But the initial state is not the latest state. That means the restored selections in searchPanes is not what the user had before data refresh is started.
I think, the reason is in function SearchPane.prototype._buildPane().
In the line 'var loadedFilter = table.state.loaded();' the initial state is reloaded. For me, it would be better to load the current state: 'var loadedFilter = table.state();'
So i changed the line in SearchPane.prototype._buildPane(). But the result was not what i expected.
After further debugging i see in function 'SearchPanes.prototype.rebuild' the call of 'this.clearSelections()' causes a reset of the 'current state'. The selections of searchPanes are cleared in the 'current state' of DataTable. Thus my change in ' SearchPane.prototype._buildPane()' forces a reset to 'empty selections'.
My temporarily solution for this problem is saving the 'current state' in function 'SearchPanes.prototype.rebuild':
var stateBeforeClear = this.s.dt.state(); I do this before clearSelections() is called. I use the saved state in 'SearchPane.prototype._buildPane()' and get the expected behaviour in case of rebuild the searchPanes after data refresh.

Can i change rowGroup with rowReorder ?

$
0
0

Hello, i have made rowGroup and rowReorder working together.

For now when i change my row order and place it between 2 rows in other group,
it will add new header, and i will have more than one header with the same name.

Is it possible somehow to change the group of the row i've moved?

Reset filters not wroking on dates filters

$
0
0

Hi all!

This is my first topic in this forum, I hope you can help me.

I have 3 tables in 3 different tabs (pending, published and archived) in one page. When I filter the a table then I clique on reset filters on other tabs, all tables containt the result of the filter applied on the first table. I have this issue only with dates range filter and not with other filters.

This is my code

HTML

<label for="pending-fromDate">publication Date from</label>
<input type="text" class="datepicker" id="pending-fromDate"> 

<label for="pending-toDate">publication Date from</label>
<input type="text" class="datepicker" id="pending-toDate">

<button type="button" id="resetButton-pending">Reset</button>

<table id="pending-data-table" style="width: 100%;"
    class="table table-condensed table-hover table-striped js-dashboard-table">
    <thead>
        <tr id="pending-data-table-col">
            <th data-column-id="id-pending">Id</th>
            <th data-column-id="name-pending">name</th>
            <th data-column-id="publication-pending">publication Date</th>
            <th data-column-id="closing-pending">closing Date</th>
        </tr>
    </thead>
</table>

JS

var tabName = $('#pending-data-table'); 

tabName.dataTable({
    initComplete : function() {
        var table = tabName.DataTable();
            $('#pending-rows-number').text('(' + this.api().data().count() + ')');
            searchDatesField(table, 2, 'pending-fromDate', 'pending-toDate', 'pending');
// other filters ...
    }
});

function searchDatesField(table, columnIndex, fieldNameFrom, fieldNameTo, tabName) {
    $.fn.dataTable.ext.search.push(function(settings, datax, dataIndex) {
        var max, min;
        var fromDate = $('#'+ fieldNameFrom).val();
        var toDate = $('#'+ fieldNameTo).val();

        if (fromDate.length > 0){
            min = getFilterDateValue(fromDate);
        } else {
            min = null;
        }

        if (toDate.length > 0){
            max = getFilterDateValue(toDate);;
        } else {
            max = null;
        }

        var filterDate = new Date(datax[columnIndex].substring(0,4) + '-' 
                + datax[columnIndex].substring(4,6) + '-' 
                + datax[columnIndex].substring(6,8));

        if (min == null && max == null){
            return true;
        } else if (min == null && max != null ){
            if (filterDate <= max){
                return true;
            }
        } else if(min != null && max == null ){
            if(filterDate >= min){
                return true;
            }
        } else if (min != null && max != null) { 
            if(filterDate >= min && filterDate <= max){
                return true;
            }
        }

        return false;
    });

    initDatePickerActions(fieldNameFrom, table, tabName);
    initDatePickerActions(fieldNameTo, table, tabName);
}   

function initDatePickerActions(dateField, table, tabName){
    $('#'+ dateField).Zebra_DatePicker({
        format: 'd/m/Y',
        onSelect: function(view, elements){
            table.draw();
            if(tabName != ''){
                updateTableRowsNumber(table, $('#'+ tabName +'-rows-number'));
            }
        },
        onClear: function(view, elements){
            table.draw();
            if(tabName != ''){
                updateTableRowsNumber(table, $('#'+ tabName +'-rows-number'));
            }
        }
    });
}

function resetSearchFields(tabName) {
    var fieldSelector = '#search-filters';

    if(tabName != ''){
        fieldSelector = '#'+ tabName +'-tab';
    }

    $(fieldSelector +' .datepicker').each(function() {
        $(this).data('Zebra_DatePicker').clear_date();
    });

    $(fieldSelector +' select').each(function() {
        $(this).val('All').change();
    });

    $(fieldSelector +' input:not(.datepicker)').each(function(){
        $(this).val('').keyup();
    });
}

How do i remove small box below sorting arrow from my dataTable ?

DataTables Editor & React 16

$
0
0

Hi,
I was just wondering what the state of play was regarding getting Editor to fire up inside a React component?

I don't need any data handling - the data can be supplied locally from an array of objects say, but I want to make sure that I can make use of some of the plugins.

Kind regards,
R

FixedHeader + Bootstrap 4 column width incorrect

$
0
0

Hello,

I have the problem that the column width is not correct when using FixedHeader (with Bootstrap 4).
I have not yet found a solution to this problem.

Example: https://jsfiddle.net/mzqusLc1/4/

Greetings


standalone registration form

$
0
0

SInce my project is using datatables I figure it would be nice to use standalone editor to create the registration form. But all the examples I find here are all about editing an existing record.

Is it possible to have a blank editor form come up and on click of Submit it gets saved. I'm guessing it would leave the data on the page, disable/remove the submit button and add some kind of 'submit successful' message. But, the question is, can you start with a blank form with a submit? If so, can someone post a sample of what they have done?

Client Side Sorting , but table values are picking from Server Side

$
0
0

Is it possible to do client side sorting values, whereas values are picking from server side...??

Responsive + Editor with opt-in for inline editable fields

$
0
0

I'm using a setup similar to this, but instead of using this

$('#example').on( 'click', 'tbody td:not(.child)', function (e) {
    editor.inline( this );
} );

I'm doing this

$('#example').on( 'click', 'tbody td.editable', function (e) {
    editor.inline( this );
} );

which makes it a more "opt-in" method than just assuming the user can edit all the fields. This has worked great until I realized that same method isn't carrying over to the "DTR" child elements (the elements that get pushed off the page when the viewport isn't large enough to show them - see screenshot below). I'm hoping to find a way to carry my className: 'editable' classes set in the columns option over to the child elements as well. Any help would be much appreciated!

DTP child elements

Access td element from within columnDefs render

$
0
0

I am populating a cell with a json which contains the infos to color a cell (something like {"color":"#000","text":"demo cell content"}). In the columnDefs I am targeting this column so that I can perform a custom rendering like this:

columnDefs.push({
    targets: [column index],
    render: function (data, type, row) {
        return [custom rendered content];
    }
});

How can i access the td that is being rendered to assign the background-color style to the whole cell and not only to its content?

classes not replicated when columns are folded

$
0
0

I have a column which has a label

<label id="label_RIO1393_approved" class="btn active act_test"><i class="fa fa-thumbs-o-up fa-lg fa-fw fileaction" aria-hidden="true" id="icon_RIO1393_approved_approval"></i></label>

The "active" and "act_test" are dynamically set when the label is clicked.

when this column is folded as a responsive action then the label in the created child is missing the dynamically set classes. Is there a way to carry them across?

Thanks

KeyTable input withing header is not tabbable

$
0
0

Hi, when KeyTable extension is used then it is impossible to tab with the keyboard into an input within a heading column.

Just try following:
1. go to http://live.datatables.net/sadupisu/1/
2. click on search
3. use tab key to enter input withing first column heading

Instead focusing the input the first cell within the body receives focus.

Change Buttons exportsOptions dynamically

$
0
0

Hello,
I'd like to change the displayed columns of an export dynamically.
I have 20 columns in my table and can select differents layout.
I can export exactly what is displayed by using exportOptions column : ':visible' and that works perfectly.

But I need to do some changes to the export according to the currently displayed layout.
For instance it's required that while displaying column 1 / 2 / 5 /12 I'll export 1 / 2 / 6/7/ 8 / 12. (so to substitute the column 5 by columns 6/7/8).

I can calculate the index needed and want to update the button export option property. I've tried

table.button(0)[0].inst.c.buttons[0].exportOptions = {columns: [4,5,6]}

But this doesn't reflect in the exported data.

Any Idea or method I missed ?
Thanks.
Mathieu


Editor - validation clears form

$
0
0

In my asp.net project, when form data does not meet all validation rules, the messages show under the fields in red correctly, however, all the fields are blanked out and the user needs to retype all entries, even those without errors.

        var RegistrationEditor = new $.fn.dataTable.Editor({
            ajax: 'api/Users',
            table: '#login',
            fields: [
                { label: "Email Address:", name: "Users.WindowsLogin", def: userNameCookie, type:"readonly"},
                { label: "First Name", name: "Users.UserFirstName" },
                { label: "Last Name", name: "Users.UserLastName" },
                { label: "Email Address:", name: "Users.UserEmail" },
                {
                    label: "Department:",
                    name: "Users.UserDepartmentID",
                    type: "select",
                    placeholder: "<Select a Department>",
                    placeholderValue: null,
                    placeholderDisabled: false

                },
                { label: "IsAdmin", name: "Users.IsAdmin", def: 0, type: "hidden" },
                { label: "IsApproved", name: "Users.IsApproved", def: 0, type: "hidden" },
                {
                    label: "RecordAdded",
                    name: "Users.RecordAdded",
                    def: function () {
                        var d = new Date();
                        return d;
                    },
                    type: "hidden"
                }
            ]
        });
    public class UsersController : ApiController
    {

        [Route("api/Users")]
        [HttpGet]
        [HttpPost]
        public IHttpActionResult Users()
        {
            var request = HttpContext.Current.Request;
            var settings = Properties.Settings.Default;

            using (var db = new Database(settings.DbType, settings.DbConnection))
            {

                var response = new Editor(db, "Users", "WindowsLogin")
                    .Model<UsersModel>("Users")
                    .Field(new Field("Users.RecordAdded")
                        .Set(false)
                    )
                    .Field(new Field("Users.UserDepartmentID")
                        .Validator(Validation.Numeric())
                        .Validator(Validation.NotEmpty(new ValidationOpts
                        {
                            Empty = false,
                            Message = "You must select your Department"
                        }))
                        .Options(new Options()
                                    .Table("Departments")
                                    .Value("DepartmentID")
                                    .Label("DepartmentName")
                        )
                    )
                    .Field(new Field("Users.UserEmail")
                        .Validator(Validation.Numeric())
                        .Validator(Validation.Email(new ValidationOpts
                        {
                            Empty = false,
                            Message = "A valid e-mail address is required"
                        }))
                    )
                    .Field(new Field("Departments.DepartmentName")
                        .Validator(Validation.NotEmpty())
                    )
                    .Field(new Field("Users.IsApproved")
                        .Validator(Validation.NotEmpty())
                        .Validator(Validation.Numeric())
                        .Options(() => new List<Dictionary<string, object>>{
                            new Dictionary<string, object>{ {"value", "0"}, {"label", "No"} },
                            new Dictionary<string, object>{ {"value", "1"}, {"label", "Yes"} },
                        })
                    )
                    .Field(new Field("Users.IsAdmin")
                        .Validator(Validation.NotEmpty())
                        .Validator(Validation.Numeric())
                        .Options(() => new List<Dictionary<string, object>>{
                            new Dictionary<string, object>{ {"value", "0"}, {"label", "No"} },
                            new Dictionary<string, object>{ {"value", "1"}, {"label", "Yes"} },
                        })
                    )
                    .LeftJoin("Departments", "Departments.DepartmentID", "=", "Users.UserDepartmentID")
                    .Process(request)
                    .Data();
                return Json(response);
            }
        }
    }

Detail Row not showing...

$
0
0

Took my first crack at setting up the responsive datatables on a wordpress site, and when I expand the second row, it appears that it's hidden...or at least styled in the incorrectly somehow. A quick attempt to "just style" it to the same color as the primary row didn't seem to work. I don't believe I'm doing anything wrong, but maybe trained eyes will help. Tried both the traditional and bootstrap example with the same result. One can see it in action here: https://nerd-brigade.com/individual-services/

Thanks for the help!

datatables export buttons not working

$
0
0

Hello,
I'm trying to use datatables on my Symfony project with webpack encore.

This is my import section in my js file

_require( 'jszip' );
var dt = require( 'datatables.net' )( window, $ );

require( 'datatables.net-buttons');
require( 'datatables.net-buttons/js/buttons.html5.js' )();
require ("datatables.net-buttons/js/buttons.print.js")();_

Already have jquery

this is my package.json file

        _"bootstrap": "3.3.7",
        "bootstrap-datetimepicker.js": "^1.0.0",
        "datatables": "^1.10.18",
        "datatables.net": "1.10.20",
        "datatables.net-bs": "1.10.20",
        "datatables.net-buttons": "1.5.6",
        "dcjqaccordion": "2.7",
        "fullcalendar": "3.9.0",
        "gritter": "1.7.4",
        "jquery": "3.3.1",
        "jquery-scrollTo": "^0.2.2",
        "jquery-sparkline": "^2.4.0",
        "jquery.cookie": "^1.4.1",
        "js-cookie": "^2.2.1",
        "jszip": "^3.3.0",
        "moment": "2.18.1",
        "popper.js": "^1.16.1",
        "select2": "^4.0.13"_

and here how I configure my datatables

_$(".paginated-table").DataTable({
            responsive: true,
            "lengthMenu": [[5, 10, 20, 50, -1], [5, 10, 20, 50, "Tous"]],
            "language": {
                processing: "Traitement en cours...",
                search: "Rechercher&nbsp;:",
                lengthMenu: "Afficher _MENU_ &eacute;l&eacute;ments",
                info: "Affichage de l'&eacute;lement _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
                infoEmpty: "Affichage de l'&eacute;lement 0 &agrave; 0 sur 0 &eacute;l&eacute;ments",
                infoFiltered: "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
                infoPostFix: "",
                loadingRecords: "Chargement en cours...",
                zeroRecords: "Aucun &eacute;l&eacute;ment &agrave; afficher",
                emptyTable: "Aucune donnée disponible dans le tableau",
                paginate: {
                    first: "Premier",
                    previous: "Pr&eacute;c&eacute;dent",
                    next: "Suivant",
                    last: "Dernier"
                },
                aria: {
                    sortAscending: ": activer pour trier la colonne par ordre croissant",
                    sortDescending: ": activer pour trier la colonne par ordre décroissant"
                }
            },
            dom: 'Bfrtlip',
            buttons: [
                {
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Exporter au format Excel',
                },
                {
                    extend: 'print',
                    text: '<i class="fa fa-print"></i>',
                    titleAttr: 'Imprimer',
                }
            ]
        });_

the datatable is apply on my table but I dont get Excel and print buttons.

did I miss something.

Thanks in advance.

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

Inline Editor - Select2 sending empty values

$
0
0

I am using the select2 intergration with inline editing. I am using Patch requests to preform partial updates to my data.
I notice the specific select2 field is always sent with this request regardless of whether this field has been modified or not.

Is there a way of emitting this field from being sent unless a change has been made, or if that is not possible setting the select2 selected object to that of the data pulled back by the datatables.

below is my datatables code

    var interface_mapper_datatable = $('#interface_mapper_table').DataTable({
        dom: '<"top">rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7 dataTables_pager"<"pull-right"lp>>><"clear">',
        //dom: 'Bfrtip',
        // columns definition
        columnDefs: [
            {className: "text-center", targets: "_all"},
            {className: "text-left", targets: 0},


            {targets: 0, visible: false,},
            {targets: 1, visible: false,},
            {
                targets: 4,
                "createdCell": function (td, cellData, rowData, row, col) {
                    if (cellData < 1) {
                        $(td).css('color', 'red')
                    }
                }


            }
        ],
        columns: [
            {data: "uuid"},
            {data: "switch"},
            {data: "existing_switch_name"},
            {data: "interface"},
            {data: "speed"},
            {data: "mode"},
            {data: "description"},
            {data: "destination_interface_name", editField: "destination_interface"}
        ],
        pageLength: 10,
        responsive: true,
        rowId: 'uuid',
        order: [[1, "desc"]],
        "lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]],
        language: {
            lengthMenu: " _MENU_"
        },
        select: true,
        buttons: [
            {extend: 'edit', editor: editor},
            {extend: 'remove', editor: editor}
        ]
    });

    var editor = new $.fn.dataTable.Editor({
        // ajax:  '/api/v1/migration-tool/switch-mapper/editor/?format=datatables',
        ajax: {
            create: {
                type: 'POST',
                url: '/api/v1/migration-tool/interfaces'
            },
            edit: {
                type: 'PATCH',
                url: '/api/v1/migration-tool/interfaces/_id_'
            },
            remove: {
                type: 'DELETE',
                url: '/api/v1/migration-tool/interfaces/_id_',
                deleteBody: false
            }
        },
        table: '#interface_mapper_table',
        idSrc: 'uuid',
        fields: [
            // {label: 'uuid', name: 'uuid',},
            // {label: 'switch', name: 'switch'},
            // {label: 'existing_switch_name', name: 'existing_switch_name'},
            // {label: 'interface', name: 'interface'},
            // {label: 'speed', name: 'speed',},
            // {label: 'mode', name: 'mode'},
            {label: 'description', name: 'description'},
        ]
    });

    editor.add({
        "label": "destination_interface_name:",
        "name": "destination_interface",
        "type": "select2",
        "initialValue": true,
        "opts": {
            allowClear: true,
            CloseOnSelect: false,
            cache: true,
            placeholder: "Select Interface",
            ajax: {
                url: (function () {
                    var data = $('#endpoint').select2('data')[0]['id'].split('_').pop();
                    var url = "/api/v1/aci/fabric-node-interfaces?interface=&switch__site_id__uuid=" + data;
                    console.log(url);
                    return url
                }),
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    // console.log(params.term);
                    return {
                        switch__node_name: params.term, // search term

                    };
                },
                processResults: function (data, params) {
                    // parse the results into the format expected by Select2
                    // since we are using custom formatting functions we do not need to
                    // alter the remote JSON data, except to indicate that infinite
                    // scrolling can be used
                    params.page = params.page || 1;
                    var formatted_data = [];
                    for (i = 0; i < data.results.length; i++) {
                        formatted_data.push(
                            {
                                'id': data.results[i].uuid,
                                'text': data.results[i].interface_name,
                            }
                        )
                    }
                    return {
                        results: formatted_data,
                    };
                },


            },
            escapeMarkup: function (markup) {
                return markup;
            },
        }
    });

i have tried to setting it as per the select2 documentation [here](https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 "here") without any luck.

    // Update select2 selection based on row.
    interface_mapper_datatable.on('select', function (e) {
        var data = interface_mapper_datatable.row({selected: true}).data();
        var destination_interface = data.destination_interface;
        // Fetch the preselected item, and add to the control
        var editor_select2 = $('#DTE_Field_destination_interface');
        $.ajax({
            type: 'GET',
            url: '/api/v1/aci/fabric-node-interfaces/' + destination_interface
        }).then(function (data) {
            // create the option and append to Select2
            var option = new Option(data.interface_name, data.uuid, true, true);
            var formatted_data =
                {
                    'id': data.uuid,
                    'text': data.interface_name,
                };
            editor_select2.append(option).trigger('change');


            // manually trigger the `select2:select` event
            editor_select2.trigger({
                type: 'select2:select',
                params: {
                    data: formatted_data
                }
            });
        });
    });

PATCH request when interface is modified:
data[6ffb1ff6-7572-4a34-81f4-d8213d6df0b2][destination_interface]: 7f9a3a5d-c244-4f69-97fb-3db5123e95aa
action: edit

PATCH request when only the description field is modified:
data[6ffb1ff6-7572-4a34-81f4-d8213d6df0b2][description]: PDC-ENC3-PRDVC1-X2R
data[6ffb1ff6-7572-4a34-81f4-d8213d6df0b2][destination_interface]:
action: edit

Any help is appricated.

select not working in standalone

$
0
0

I am trying to create a standalone editor Registration form. I already have an "admin" page for users to go in and approve once somebody submits a registration record. The datatable/editor works fine on the admin page. However, on the registration page (both pages using the same API) , the UserDepartment select list is not working correctly.

admin page (working fine)

        var UsersEditor = new $.fn.dataTable.Editor({
            ajax: 'api/Users',
            table: '#Users',
            fields: [
                { label: "Windows Login:", name: "Users.WindowsLogin" },
                { label: "First Name:", name: "Users.UserFirstName" },
                { label: "Last Name:", name: "Users.UserLastName" },
                { label: "Email Address:", name: "Users.UserEmail" },
                { label: "Department:", name: "Users.UserDepartmentID", type: "select" },
                { label: "Admin?", name: "Users.IsAdmin", type: "select" },
                { label: "Approved?", name: "Users.IsApproved", type: "select" },
                {
                    label: "Record Added",
                    name: "Users.RecordAdded",
                    type: "readonly",
                    def: function () {
                        var d = new Date();
                        return d;
                    }
                }
            ]
        });

        var table = $('#Users').DataTable({
            dom: "Bfrtip",
            ajax: 'api/Users',
            columns: [
                { data: "Users.WindowsLogin" },
                { data: "Users.UserFirstName" },
                { data: "Users.UserLastName" },
                { data: "Users.UserEmail" },
                { data: "Departments.DepartmentName" },
                {
                    data: "Users.IsAdmin",
                    render: function (data, type, row) {
                        return (data == 1) ? "Yes" : "No";
                    }
                },

                {
                    data: "Users.Approved",
                    render: function (data, type, row) {
                        return (data == 1) ? "Yes" : "No";
                    }
                },
                { data: "Users.RecordAdded" },
            ],
            select: true,
            lengthChange: false,
            buttons: [
                { extend: "create", editor: UsersEditor },
                { extend: "edit", editor: UsersEditor },
                { extend: "remove", editor: UsersEditor }
            ]
        });

Registration Page. the dropdown does not populate with the list of departments

    $(document).ready(function () {
        userNameCookie = readCookie('userNameCookie');
        var RegistrationEditor = new $.fn.dataTable.Editor({
            ajax: '/api/Users',
            fields: [
                { label: "Email Address:", name: "Users.WindowsLogin", def: userNameCookie, type:"readonly"},
                { label: "First Name", name: "Users.UserFirstName" },
                { label: "Last Name", name: "Users.UserLastName" },
                { label: "Email Address:", name: "Users.UserEmail" },
                { label: "Department:", name: "Users.UserDepartmentID", type:"select" },
                { label: "Last Name", name: "Users.IsAdmin", type: "hidden" },
                { label: "Last Name", name: "Users.IsApproved", type: "hidden" },
                { label: "Last Name", name: "Users.RecordAdded", type: "hidden" }
            ]
        });

        RegistrationEditor
            .create()
            .title('Add new record')
            .display(true)
            .set("Users.IsAdmin", 0)
            .set("Users.IsApproved", 0)
            .set("Users.RecordAdded", '7/1/2020')
            .buttons('Save')
            ;
    });

controller:

    public class UsersController : ApiController
    {
        [Route("api/Users")]
        [HttpGet]
        [HttpPost]
        public IHttpActionResult Users()
        {
            var request = HttpContext.Current.Request;
            var settings = Properties.Settings.Default;

            using (var db = new Database(settings.DbType, settings.DbConnection))
            {

                var response = new Editor(db, "Users", "WindowsLogin")
                    .Model<UsersModel>("Users")
                    .Field(new Field("Users.RecordAdded")
                        .Set(false)
                    )
                    .Field(new Field("Users.UserDepartmentID")
                        .Validator(Validation.NotEmpty())
                        .Validator(Validation.Numeric())
                        .Options(new Options()
                                    .Table("Departments")
                                    .Value("DepartmentID")
                                    .Label("DepartmentName")
                        )
                    )
                    .Field(new Field("Departments.DepartmentName"))
                    .Field(new Field("Users.IsApproved")
                        .Validator(Validation.NotEmpty())
                        .Validator(Validation.Numeric())
                        .Options(() => new List<Dictionary<string, object>>{
                            new Dictionary<string, object>{ {"value", "0"}, {"label", "No"} },
                            new Dictionary<string, object>{ {"value", "1"}, {"label", "Yes"} },
                        })
                    )
                    .Field(new Field("Users.IsAdmin")
                        .Validator(Validation.NotEmpty())
                        .Validator(Validation.Numeric())
                        .Options(() => new List<Dictionary<string, object>>{
                            new Dictionary<string, object>{ {"value", "0"}, {"label", "No"} },
                            new Dictionary<string, object>{ {"value", "1"}, {"label", "Yes"} },
                        })
                    )
                    .LeftJoin("Departments", "Departments.DepartmentID", "=", "Users.UserDepartmentID")
                    .Process(request)
                    .Data();
                return Json(response);
            }
        }
    }

API\Users returns Department options correct, again, the Admin page works just fine. And if I change the registration form, taking away type: "select" I am able to type in a DepartmentID and the record will save just fine.

Viewing all 82277 articles
Browse latest View live


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