How to update/add buttons once instantiated datatables - javascript

I am new to JavaScript and I lack knowledge javascript objects.
I would like to know how I can add the extension of the datatable 1.10 button once created .
My code is:
var table;
$('#MyDiv').DataTable({someCode;});
$.fn.dataTable.ext.buttons.ok = {
text: 'OK',
action: function (e, dt, node, config) {
console.log("Hi");
}
};
table = $('#MyDiv').DataTable();
//!Here I want to add my button in table var!

Option 1
The easiest way to do it (in my opinion) is to use the option form of the button declaration, instead of the function form you are attempting to use here. In your case, that would look something like this:
table = $('#MyDiv').DataTable({
/*Other DataTables config options go here*/
buttons: [
{
text: 'OK',
action: function ( e, dt, node, config ) {
console.log("Hi");
}
}
]
});
This can be found in the DataTables examples, which is a great source for DataTables information.
Option 2
If instead you wish to keep using the function notation, then you would simply have to add a button declaration to the options instead of the whole action/text block that is there in the above example. See below:
var table;
//You should not have 2 .DataTable() calls, so I removed this one
//Move any other options you had to the other call below
$.fn.dataTable.ext.buttons.ok = {
text: 'OK',
action: function (e, dt, node, config) {
console.log("Hi");
}
};
table = $('#MyDiv').DataTable({
/*Other DataTables config options go here*/
buttons: [
'ok'
]
});
Either way should work, it just depends on how you prefer to organize your code.
I'd also refer you to the custom buttons documentation on the DataTables website to get more information or to see where I got these code blocks from.

Related

Odoo field doesn't update when changed from javascript with an RPC call

I want to be able to change the context of a one2many field (work_unit) programatically to modify the default value of one of its fields (product_id).
Ideally I would like to change the o2m context directly from my widget, but I haven't had any success doing that, the view doesn't acknowledge any changes I make from javascript.
Current approach: I have another field selected_chapter which I pass through context as the default for work_unit.product_id. This works fine: when I change selected_chapter manually, the o2m context picks up the new default for the field product_id.
Now, I want to be able to modify selected_chapter programatically from a widget in javascript.
I do this by calling a python method with an _rpc() call from my widget, and it works, but the view doesn't update selected_chapter until I save the record which defeats the purpose of the call.
Widget code:
ListRenderer.include({
...
_setSelectedChapter: function () {
var self = this;
this.trigger_up('mutexify', {
action: function () {
return self._rpc({
model: 'sale.order',
method: 'set_selected_chapter',
args: [
[self.res_id]
],
kwargs: {
chapter_id: self.filter.getSelected()
},
}).then(function (result) {
console.log("res", result);
self._render();
});
},
});
},
...
})
Model code:
selected_chapter = fields.Many2one('product.product')
#api.multi
def set_selected_chapter(self, chapter_id):
chapter = self.env['product.product'].browse(chapter_id)
if not chapter.exists():
return
# I've also tried using self.update(), same results
self.selected_chapter = chapter
View code:
<field name="work_unit" mode="tree,kanban" filter_field="product_id" context="{'default_product_id': selected_chapter}">
First, rename work_unit to work_unit_ids.
Then, on the server side write an onchange method. See https://www.odoo.com/documentation/12.0/reference/orm.html#onchange-updating-ui-on-the-fly

Modify DataTables Button Action

I want to add the search keyword to the URL of a custom button action element in order to pass the keyword as a GET parameter.
I am initializing the data table like so:
var table = $('#list').DataTable( {
dom: 'lBfrtip',
buttons: [
{
text: 'Export to PDF',
className: 'export-to-pdf',
action: function ( e, dt, button, config ) {
window.open('generate_pdf.php?case_id=<?= $case_id? ?>','_blank');
}
And attempting to append the keyword to the URL using:
// append keyword search values to pdf url
$('#list').on('search.dt', function() {
var keyword = $('.dataTables_filter input').val();
//FAILS HERE
var export_pdf_url = $(".export-to-pdf").attr("href");
// remove keywords if they already exist
removeURLParameter(export_pdf_url, 'keyword');
// append filter value to filtered pdf href
$(".export-to-pdf").attr("href", export_pdf_url + '&keyword='+keyword);
});
This seems to be failing because the action function is not actually assigning the the button a href attribute.
Any suggestions on how to dynamically modify the action function or other approaches would be very much appreciated.
Use search() API method which returns currently applied global search when called without arguments.
Then generate URL directly in the callback function for action option.
For example:
buttons: [
{
text: 'Export to PDF',
className: 'export-to-pdf',
action: function ( e, dt, button, config ) {
var query = dt.search();
window.open('generate_pdf.php?case_id=<?= $case_id? ?>&keyword=' + encodeURIComponent(query), '_blank');
}
}
],

How to customize edit event in JsGrid

I'm using jsGrid and want to know if it's possible how to customize onclick event of editButton. Basically, doing something like displaying modal instead of inline editing. I know that we can get the HTML output of control column like this :
{
type: 'control',
itemTemplate: function() {
var $result = jsGrid.fields.control.prototype.itemTemplate.apply(this, arguments); // Array of string
return $result;
}
}
But how to have control on EditButton?
You can try this:
editItem: function(item) {
var $row = this.rowByItem(item);
if ($row.length) {
console.log('$row: ' + JSON.stringify($row)); // I modify this
this._editRow($row);
}
},
at your jsGrid config.
All lines except line // I modify this are default from original source of jsGrid, so dont change them.

Custom rendering when using server side processing

I was wondering if the rendering of the table after receiving an ajax response can be modified. This seems related to the render function described here: https://www.datatables.net/manual/orthogonal-data.
My server returns Data like
{
"name":
{
id: "123456",
value: "Tiger Nixon"
}
}
I want to add to each name cell the id of the name as data-attribute or as id for the td and want to add a .on( "click", handler ) for each cell.
Is this possible?
Thanks in advance
You can use DT_RowData or DT_RowAttr (requires DataTables 1.10.5 or higher) parameters in your returned data to assign attributes to <tr> element which you can later retrieve in click handler, see Server-side processing chapter in the manual.
Alternatively you can use render method but it may not be as effective. I assumed below that index of your name column is 0 and that you want to set data-id attribute.
var table = $('#example').DataTable({
"columnDefs": [{
"data": "name.value",
"targets": 0,
"render": function ( data, type, full, meta ) {
if(type === 'display'){
$('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
}
return data;
}
}]
});
You can add click event handler using the code below:
$(document).ready(function(){
var table = $('#example').DataTable({
// Define DataTables initialization options here
});
$('#example tbody').on('click', 'td', function(){
// Use table to access various API function
//
// For example:
// var data_cell = table.cell(this).data();
});
});
This is possible by using the columns.createdCell function.
The answer of Gyrocode is correct for an old DataTables version.

How do I assign a real function into a javascript object to use as a callback?

I've got a Javascript mess that looks something like:
Note: Not working code, just trying to illustrate my problem...
$(function() {
$(foo).Something( { //Something is a grid control
buttons: {
add: {
onClick: function() { //Build dialog box to add stuff to grid
$('<div></div>')
.html('...')
.dialog({
buttons: {
done: { //Finished button on dialog box
OnClick: function() {
$(this).dialog('close');
}
}
}
});
}
}
}
} );
});
I'd like to replace some of the function(){...}s with real functions, to clean things up a bit and to get rid of all that indenting. How do I assign a real function to one of the callbacks rather than an anonymous function?
function abc(){
return false;
}
var callback = {click : abc}
You can then use callback.click.call or callback.click.apply
Give the function name instead of function(){ ... }.
+1 because of the awesome indentation example.
You can define named functions as Joyce stated; you can also considerably clean up that deeply nested code by just declaring some variables (function or not) and spreading the code into multiple, non-nested statements.
The dialog creation would be my first candidate for that type of refactoring (and it demonstrates uses a named function):
function CreateDialog() { //Build dialog box to add stuff to grid
$('<div></div>')
.html('...')
.dialog({
buttons: {
done: { //Finished button on dialog box
OnClick: function() {
$(this).dialog('close');
}
}
}
$(function() {
$(foo).Something( { //Something is a grid control
buttons: {
add: {
onClick: CreateDialog
}
}
}
} );
});
I should also note that you can initialize most jQuery objects (looks like you are using jQueryUI) after they are created. For example, you don't have to configure the buttons all in one shot: http://jqueryui.com/demos/dialog/#option-buttons
OK then, here goes my answer:
Oops.. You did functionname() (note the extra ()s). :sigh: That's what you get for working on this at 3 AM.

Categories

Resources