Rejoining Remote and Local Data on postSubmit
Rejoining Remote and Local Data on postSubmit
The purpose of this table is to display remote data from an external source along with local data. One of the requirements of this project is that remote data cannot be saved locally, but saving any additional user-created data is allowed. Such as comments.
Loading the table:
One approach to this was to return joined remote and local data from a php script called joined_remote_and_local_data.php. This script retrieves remote data, selects and joins any local data with a shared id, or creates a new empty local record if none is found.
Editing rows:
In this case, a regular Editor php script will save and return local data. The issue here is that whenever Editor tries to rebuild an edited row, any remote data in that row is lost. That is because none of the remote data can be saved locally.
This was mostly fixed by rejoining remote and local data on a postSubmi event. The only problem is that the pre-edit row data is stored and referenced based on the last clicked row. That works fine if user clicks anywhere on the screen except on another row's inline-editable field.
The question here is: How can this be done better? Is there another way to reference the row that is about to be edited other than on a click event? Should maybe the rejoining after an edit happen in the php script?
Below is a sample of the code:
$(document).ready(function() {
var editedRow;
var table = $('#myTable').DataTable({
ajax: "assets/php/joined_remote_and_local_data.php",
// The joined_remote_and_local_data.php script is returning
// remote data (id, remote_email) from an external API
// joined with local sql data (id, local_name)
idSrc: "id",
columns: [
{
data: 'id'
}, {
data: 'local_name',
className: 'inline-editable'
}, {
data: 'remote_email'
}
]
});
var editor = new $.fn.dataTable.Editor({
ajax: {
url: 'assets/php/table.local_data.php'
// This table.local_data.php Editor script only
// deals with local data (id, local_name)
},
table: '#myTable',
idSrc: "id",
fields: [
{
label: 'ID:',
name: 'id',
type: 'readonly'
}, {
label: 'Name:',
name: 'name'
}, {
label: 'Email:',
name: 'email',
type: 'readonly'
}
]
});
$('#myTable').on( 'click', 'tbody td.inline-editable', function (e) {
editedRow = this;
editor.inline(
this,
{
onBlur: 'submit'
}
);
});
editor.on('postSubmit', function(e, json) {
var response = json;
var rowData = table.row(editedRow).data();
repopulateEditedRow(rowData, response);
// repopulateEditedRow() works as a middleman rejoining
// returned edited data from table.local_data.php with
// existing rowData that is not local (remote_email)
});
});
function repopulateEditedRow(rowData, response) {
for (var key in rowData) {
if (rowData.hasOwnProperty(key) && key.substring(0, 6) == "remote_") {
response.data[0][key] = rowData[key];
}
}
return response;
}
Thank you!