Editor - Loading table from DOM & customising AJAX control

Editor - Loading table from DOM & customising AJAX control

christopherbrianchristopherbrian Posts: 3Questions: 1Answers: 0

Hi,

I recently downloaded trial of Editor tables which I am looking to integrate into my Django project (although the framework/ language I’m using isn’t really relevant to my query).

In my application I load an editable table from the DOM as outlined here which works fine. The data loaded into the table initially is from a web service and, once the user as edited it as necessary, the data will ultimately form part of a HTTP POST request in the form of a JSON object which will be written to a database. The problem I’m trying to get my head around is in this construction of the JSON object.

The initial table itself is created from parsing my own JSON in the format using a page template:

[
                {'links': {'self': 'https://apiservice.com/directorships/12345-678910-13243028/'}, 
                    'type': 'directorship', 'id': '12345-678910-13243028', 
                    'attributes': {'locality': 'Germany', 'occupation': 'Legal Counsel', 'address': 'N5 9BA', 'first_name': 'John', 'surname': 'Swinton'}},
                {'links': {'self': 'https://apiservice.com/directorships/12345-678910-15689568/'}, 
                    'type': 'directorship', 'id': '12345-678910-15689568', 
                    'attributes': {'locality': '', 'occupation': 'Chartered Accountant', 'address': 'N51 9CD', 'first_name': 'Mary', 'surname': 'Berry'}},
                ...
                ]

The table created doesn’t used all of the information supplied as noted below…

...
$('#directors').DataTable({
            dom: 'Bt',
            paging: false,
            columns: [
                {"data": "name"},
                {"data": "address"},
                {"data": "occupation"}
            ],
            select: true,
            "bDestroy": true, // Added in to stop table being initialised twice https://datatables.net/manual/tech-notes/3
            buttons: [
                {extend: 'create', editor: editor},
                {extend: 'edit', editor: editor},
                {extend: 'remove', editor: editor}
            ]
        });
...

…so my thoughts were that I’d also be storing my initial JSON object in a variable which gets modified in the AJAX call as the user makes changes similar to the example at DataTables example - Ajax override - using localStorage for the data source so that updates are written to both the table as it gets redrawn but also to my JSON object as it gets prepared ready for the HTTP POST request when the user has completed the rest of the form.

Based around the localStorage example, I’m currently trying to work out if it’s possible to start off with a table that has been sourced from the DOM so that that in the initial set up…

var editor; // use a global for the submit and return data rendering in the examples
 
$(document).ready(function() {
    // Object that will contain the local state
    var todo = {};
 
    // Create or update the todo localStorage entry
    if ( localStorage.getItem('todo') ) {
        todo = JSON.parse( localStorage.getItem('todo') );
    }
 
    // Set up the editor
    editor = new $.fn.dataTable.Editor( {

the variable todo is already populated from the DOM so that it can be referenced and amended appropriately.

(BTW, If there is an easier approach to what I am trying to achieve than this, I’d obviously be keen to hear that as well)

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin

    The easier approach is to have the entire data structure used in the DataTable - just not visible. You can do that with hidden columns:

    {"data": "dataPointName", visible: false}
    

    Another option is to not write the data into the DOM yourself, but rather use the data option to populate the table. That way the original data object for the row is the one that is retained and used.

    I think it would be possible to do it the way you have been looking at, but to be honest, its probably the most complicated option :).

    Does that all make sense?

    Allan

  • christopherbrianchristopherbrian Posts: 3Questions: 1Answers: 0

    Hi Allan,

    Thanks for the reply. Marshalling the data using the certainly made more sense & looks like it is much easier to manage.

    Further, I can see using the following checks…

    editor
                .on( 'create', function ( e, json, data ) {
        console.log('Create ' + JSON.stringify( json ));
    } )
                .on( 'edit', function ( e, json, data ) {
        console.log('Edit ' + JSON.stringify( json ));
    } )
    

    …that the JSON object is being updated correctly whereby, performing an update via ‘edit’ on a row shows the following in the console:

    {"data":[{"type":"directorship","id":"123456-123456-06158288","attributes":{"surname":"Holdan","postcode":"M252NT","town":"Luton","birthdate":"1975-10-00","appointment_type":"P","occupation":"Solicitor","suffix":"","first_name":"Steve","nationality":"British","county":"Sussex","date_appointed":"2003-09-24","other_appointments":"Y","locality":"10 Oak Way","date_resigned":"2005-09-01","address":"Oak Farm","title":"Mr"},"links":{"self":"https://apiservice.com/v3/directorships/123456-123456-06158288/"}}],"error":"","fieldErrors":[]}
    

    However, I’m still not sure how to take the data that has been prepared in the datatable and include it in a HTTP (non-Ajax) POST request when the user has completed the full form that the table is a part of.

    So, if I initially set up with

    var directorJSON = myJSONfromWebService ;
    

    which loads into my table, thus:

    $('#directors').DataTable({
        data: directorJSON,
        ...
    

    where it can be edited, added to, etc

    How would one be best to get the final, updated object after the various changes have been made to various rows to post with other elements in the form (via, say, a hidden input field)

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin
    Answer ✓

    I’m still not sure how to take the data that has been prepared in the datatable and include it in a HTTP (non-Ajax) POST request

    Presumably you have a form element in this case, with a button that says "Save" or similar? If so, what you need to do is enter the information from the table into that form.

    For example, if you wanted to just get the whole data set, you could do:

    $('#myHiddenFormElement').val(
      JSON.stringify( table.rows().data().toArray() )
    );
    

    You could be more slick about it of course - you could only send the rows that were edited (i.e. update the form input element with the edit event). Possibly use an input element per row - that will really depend upon how you want to send the data to the server.

    Regards,
    Allan

  • christopherbrianchristopherbrian Posts: 3Questions: 1Answers: 0
    table.rows().data().toArray()
    

    That was the bit I was missing - looks to be working fine as I wanted now.

    Thank you!!

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin

    Worth me stating why you need the toArray() call perhaps: without it JSON.stringify would see the entire DataTables API object and attempt to stringify that. Which ends up being massive.

    Good to hear that does the business for you.

    Allan

This discussion has been closed.