Reinitialize datatable using the new API - javascript

I've found some SO threads about reinitializing a datatable using the old API, but I think they're deprecated now.
I have an existing rendered datatable. I would like to refresh it with new settings. Using the new API, how would I do the following:
var dataTable = $('table.dataTable').DataTable();
var newDataTableSettings = {
data: { /* some data */ },
columns: { /* some columns*/ },
bFilter: false,
// etc...
};
// something like dataTable.clear().data(newDataTableSettings).draw()
My closest attempt:
dataTable.clear().draw()
dataTable.rows.add({ /* some data */ }).draw();

Use the destroy option :
$('#example').DataTable({
data: [{ test : 'test' }, { test : 'qwerty'}],
columns : [ { data : 'test', title: 'test' } ]
});
reinitialise with new data and removed search capabilities .
$("#reinit").on('click', function() {
$('#example').DataTable({
destroy: true, //<--- here
data: [{ newCol : '100010'}, { newCol : '234234'}],
columns: [ { data : 'newCol', title: 'header' } ],
searching: false
})
});
http://jsfiddle.net/3sonfsfm/
If you use an options literal you must reset it before reusing it :
var options = {
data: [{ test : 'test' }, { test : 'qwerty'}],
columns : [ { data : 'test', title: 'test' } ]
}
$("#reinit").on('click', function() {
options = {}; //<--- RESET
options.destroy = true;
options.data = [{ newCol : '100010'}, { newCol : '234234'}];
options.columns = [ { data : 'newCol', title: 'header' } ];
options.searching = false;
$('#example').DataTable(options).draw();
});
This is because the options object is enriched with different values such as aaData, aoColumns an so on, which will conflict if you specify new data and new columns.

Related

How to dinamically fill sap.m.Select with data?

I need to display some odata's data in a sap.m.Select but don't know why is not working, This is the code I have so far
var oModel = new sap.ui.model.json.JSONModel();
var data = [];
var sUrlCard = "odata's url";
var oDataModel = new sap.ui.model.odata.ODataModel(sUrlCard, true);
oDataModel.read("CardBrandCollectionSet", {
async: false,
success: function(oData, response) {
$.each(oData.results, function(i, val) {
data.push(val);
});
oModel.setData({
'card': data
});
sap.ui.getCore().setModel(oModel, "card");
},
error: function(oError) {
console.log(oError);
}
});
table where the select input is located
var oTable = new sap.m.Table({
mode: oMode,
columns: [
{
hAlign: 'Center',
header: new Text({
text: "Card"
})
}
]
});
Select input I need to fill with data
var oSelectMarca = new sap.m.Select({
items: {
path: "/card",
template: new sap.ui.core.ListItem({
key: '{Codcard}',
text: '{Descript}'
}),
templateShareable: true
},
selectedKey: '{Marca}'
});
The binding path of the select control is wrong:
sap.ui.getCore().setModel(oModel, "card"); // model is set at core with name as card
$.each(oData.results, function(i, val) {
data.push(val);
});
oModel.setData({
'card': data // setting data in an object with name as card
});
var oSelectMarca = new sap.m.Select({
items: {
path: "card>/card/", //Binding path model name along with array name
template: new sap.ui.core.ListItem({
key: '{card>Codcard}', // model name with property name
text: '{card>Descript}' // model name with property name
}),
templateShareable: true
},
selectedKey: '{card>Marca}' // model name with property name
});
fist of all you do not want to create your odata model like that, please specify it in your manifest:
in "sap.app" part:
"dataSources": {
"yourRemote": {
"uri": "YOUR_URI",
"type": "OData",
"settings": {
"odataVersion": "2.0"
}
}
}
in "sap.ui5" part:
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "YOUR_i18n"
}
},
"remoteModel": {
"dataSource": "yourRemote"
}
}
2nd you dont want to create controls in js, you do that in your xml files:
https://sapui5.hana.ondemand.com/#/topic/1409791afe4747319a3b23a1e2fc7064
https://blogs.sap.com/2018/05/01/why-do-we-use-xml-views-rather-js-views-in-sapui5/
in that your select needs to be bound like that:
<Select
id="anID"
valueState="{vsModel>/otherText}"
valueStateText="{i18n>someText}"
forceSelection="false"
items="{
path: 'remoteModel>/CardBrandCollectionSet',
sorter: {
path: 'Descript'
}
}">
<core:Item key="{remoteModel>Codcard}" text="{remoteModel>Descript}" />
</Select>

Is there any way to read the dojo Objectstore and convert it as JS array object

Looking for a way to read the all the rows from DOJO enhancedgrid ObjectStore as JS Array object.
OnRowClick, I need to get the all items as an array. Here is the sample code:
Layout, Id are defined in another methods. Id is first header.
IN the following code, store is dataStore.
function constructEnhancedGrid(jsObject) {
require(
["dojo/store/Memory", "dojo/data/ObjectStore",
"dojox/grid/EnhancedGrid",
"dojox/grid/enhanced/plugins/Pagination", "dojo/domReady!"
],
function(Memory, ObjectStore, EnhancedGrid, Pagination) {
jsGlobalObject = jsObject;
jsObject = JSON.parse(jsObject);
var objectStoreMemory = new Memory({
data: jsObject,
idProperty: [tableheaders[0]]
});
dataStore = new ObjectStore({
objectStore: objectStoreMemory
});
constructEnhancedGridlayout(tableheaders);
if (typeof rtGrid === "undefined") {
rtGrid = new EnhancedGrid({
store: dataStore,
structure: enhancedGridLayout,
plugins: {
pagination: {
pageSizes: ["10", "25", "50", "100"],
description: true,
sizeSwitch: false,
pageStepper: true,
gotoButton: false,
maxPageStep: 5,
position: "top",
defaultPageSize: 20
}
},
}, "rtGrid");
rtGrid.startup();
} else {
rtGrid.setStructure(enhancedGridLayout);
rtGrid.setStore(dataStore);
rtGrid.currentPage(1);
rtGrid.render(dataStore);
rtGrid.startup();
}
dojo.connect(rtGrid, "onRowClick", function(e) {
dataStore.fetch({
query: {},
onComplete: function(items) {
var resArray;
dataStore.objectStore.get().then(function(result) {
resArray = result;
});
}
});
});
});
}
Updated answer
Initially I assumed that you use JsonRest, but now I see that you use Memory object to populate your datagrid. Instance of Memory has attribute data with an array of data it contains. You can access it directly in you code.
grid.on("RowClick", function (e) {
var data = this.store.objectStore.data;
})
});

Refresh / Redraw Datatables over function

and i call the datatable over the function.
Here is my function :
function drawTable(yearParameter) {
var oTable = $('#horizontal-monthly').DataTable({
processing: true,
serverSide: true,
ajax: {
url : '{!! route('adm1n.laporan-bulanan-data') !!}',
data : function (d) {
d.year = yearParameter;
}
},
columns: [
{ data: 'B_01', name: 'B_01', sortable: false },
{ data: 'B_02', name: 'B_02', sortable: false }
],
dom : '<"dt-panelmenu clearfix"lr>t<"dt-panelfooter clearfix"ip>',
});
}
And i have event change to call my function above and pass parameter on it.
How to reload the datatables? Cause right now datatables won't reload.
I try to use :
oTable.destroy();
oTable.draw();
It make datatables functionality not work. Like search, pagination etc.
Edit
Here is my change event :
$('#year-value').on('change', function(e) {
var yearParam = $('#year-value').val();
drawTable(yearParam);
});
How to handle that?
Thank you??
Please try
oTable.clear();
oTable.draw();
Also, can I see your change event? I can help you re-add the rows
UPDATE 2
Ok, you can't call DT constructor more than once. First thing what you want to do is to save DT object as global object.
function drawTable() {
if(!oTable)
{
oTable = $('#horizontal-monthly').DataTable({
processing: true,
serverSide: true,
ajax: {
url : '{!! route('adm1n.laporan-bulanan-data') !!}',
data : function (d) {
d.year = filterYearParam;
}
},
columns: [
{ data: 'B_01', name: 'B_01', sortable: false },
{ data: 'B_02', name: 'B_02', sortable: false }
],
dom : '<"dt-panelmenu clearfix"lr>t<"dt-panelfooter clearfix"ip>',
});
}
}
else
{
oTable.ajax.reload().draw();
}
$('#year-value').on('change', function(e) {
filterYearParam = $('#year-value').val();
drawTable();
});
Try this, and then I can try making your year to work.

ExtJS TaskRunner

I'm still in the learning process with EXTJS and any help would be much appreciated.
The goal for me is to load data into a grid where one cell needs to have the value incremented every minute. From my research using the TaskRunner function is the way to go but can't figure out where to put it and how to use it. My assumption is that it needs to go into the model or the controller but I'm not sure. In my simple project I'm using the MVC architecture.
Currently my gird works as expected. It reads in a file does a date conversion that produces a minute value. It's that minute value that I need to increment.
The code below is a sample TaskRunner snippit that I'm working with, right or wrong I don't know yet.
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
}),
interval: 60000 // 1-minute interval
});
task.start();
Model:
Ext.define("myApp.model.ActionItem", {
extend : "Ext.data.Model",
fields : [
{
name: 'pri',
type: 'int'
},
{
name: 'request',
type: 'int',
defaultValue: 0,
convert : function(v, model) {
return Math.round((new Date() - new Date(v)) / 60000);
}
}
]
});
Controller:
Ext.define("myApp.controller.HomeController", {
extend: "Ext.app.Controller",
id: "HomeController",
refs: [
{ ref: "ActionItemsGrid", selector: "[xtype=actionitemgrid]" },
{ ref: "DetailsPanel", selector: "[xtype=actionitemdetails]" }
],
pri: "",
models: ["ActionItem"],
stores: ["myActionStore"],
views:
[
"home.ActionItemDetailsPanel",
"home.ActionItemGrid",
"home.HomeScreen"
],
init: function () {
this.control({
"#homescreen": {
beforerender: this.loadActionItems
},
"ActionItemsGrid": {
itemclick: this.displayDetails
}
});
},
displayDetails: function (model, record) {
this.getDetailsPanel().loadRecord(record);
},
loadActionItems: function () {
var store = Ext.getStore("myActionStore");
store.load();
this.getActionItemsGrid().reconfigure(store);
}
});
View:
Ext.define("myApp.view.home.ActionItemGrid", {
extend: "Ext.grid.Panel",
xtype: "actionitemgrid",
resizable: true,
multiSelect: false,
enableDragDrop : false,
store: null,
columns:
[
{ header: "Pri", dataIndex: "pri", sortable: false, autoSizeColumn: true},
{ header: "Req", dataIndex: "request", sortable: false, autoSizeColumn: true}
],
viewConfig:
{
listeners: {
refresh: function(dataview) {
Ext.each(dataview.panel.columns, function(column) {
if (column.autoSizeColumn === true)
column.autoSize();
})
}
}
}
});
Sample JSON File:
{
"actionitems" : [
{
"pri": 1,
"request": "2014-12-30T03:52:48.516Z"
},
{
"pri": 2,
"request": "2014-12-29T05:02:48.516Z"
}
]
}
You have error in code which creates task - you should provide function to run configuration property, not result of invocation. Try this:
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: function() {
store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
})
},
interval: 60000 // 1-minute interval
});
task.start();
You can put that code in loadActionItems method.

Couldnt read and set Json data with extjs4

I want to read json data in extjs here is my code below.
What i'm doing wrong ? I'm pretty new at Extjs.
I think i couldn't get the json value, or couldn't properly write it down on panel.
Thanks in advance.
Ext.require([ 'Ext.grid.*', 'Ext.data.*', 'Ext.dd.*' ]);
var urlGetName = '${ctx}/main/list';
Ext.define('DataObject', {
extend : 'Ext.data.Model',
fields : [ 'name' ]
});
var storeName = Ext.create('Ext.data.Store',{
model:'DataObject',
autoLoad : false,
proxy : {
type : 'ajax',
actionMethods: {
read: 'GET'
},
reader : {
type : 'json',
root: 'data',
},
api : {
read: urlGetName
}
},listeners: {
load: function(store, records) {
dataa =store.getAt(0).get('data');
}
}
});
Ext.onReady(function() {
var firstGridStore = Ext.create('Ext.data.Store', {
model : 'DataObject',
data : dataa
});
var columns = [ {
text : "Name",
flex : 1,
sortable : true,
dataIndex : 'name'
} ];
// declare the source Grid
var firstGrid = Ext.create('Ext.grid.Panel', {
multiSelect : true,
viewConfig : {
plugins : {
ptype : 'gridviewdragdrop',
dragGroup : 'firstGridDDGroup',
dropGroup : 'secondGridDDGroup'
},
listeners : {
drop : function(node, data, dropRec, dropPosition) {
var urlL = '${ctx}/main/list';
var param = data;
postDataAsParamsINN({param:param},urlL,function(resp){
var success=resp.success;
if(success){
Ext.MessageBox.alert('succes', 'bravaa');
}else{
Ext.MessageBox.alert('error','eroross' );
}
});
}
}
},
store : firstGridStore,
columns : columns,
stripeRows : true,
title : 'First Grid',
margins : '0 2 0 0'
});
});
You shouldn't use two stores to fill the one with the other. Delete the FirstGridStore and use the predefined remote store instead:
// Model
Ext.define('DataObject', {
extend : 'Ext.data.Model',
fields : [ 'name' ],
idProperty: 'name'
});
// Store
var storeName = Ext.create('Ext.data.Store',{
model:'DataObject',
autoLoad: true,
queryMode: local,
proxy: {
type: 'ajax',
actionMethods: {
read: 'GET'
},
reader: {
type : 'json',
root: 'data',
},
api: {
read: urlGetName
}
}
});
// Grid
var columns = [{
text : "Name",
flex : 1,
sortable : true,
dataIndex : 'name'
}];
// declare the source Grid
var firstGrid = Ext.create('Ext.grid.Panel', {
multiSelect : true,
viewConfig : {
plugins : {
ptype : 'gridviewdragdrop',
dragGroup : 'firstGridDDGroup',
dropGroup : 'secondGridDDGroup'
},
listeners : {
drop : function(node, data, dropRec, dropPosition) {
var urlL = '${ctx}/main/list';
var param = data;
postDataAsParamsINN({param:param},urlL,function(resp){
var success=resp.success;
if(success){
Ext.MessageBox.alert('succes', 'bravaa');
}else{
Ext.MessageBox.alert('error','eroross' );
}
});
}
}
},
store : storeName, // defined store
columns : columns,
stripeRows : true,
title : 'First Grid',
margins : '0 2 0 0'
});
});

Categories

Resources