ui-grid using external Pagination and exporting data - angularjs

I am currently using ui-grid implemented with external pagination to display my data. I've run into as issue where I can only export the currently viewed data, however I need to be able to export ALL data as well.
Anyone know a work around to export all data using external pagination?

I ended up using csvExport function included with ui-grid. I added an "Export All" custom menu item and it works great! Here is my code:
gridMenuCustomItems: [
{
title: 'Export All',
action: function ($event) {
$http.get(url).success(function(data) {
$scope.gridOptions.totalItems = data.totalFeatures;
$scope.gridOptions.data = data.features;
$timeout(function()
{
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL, myElement );
}, 1000);
});
}
}
]
Hope this helps someone!

Ok, so I took ui-grids server side example and modified their plnkr a bit. I simply created a button outside the ui-grid and that button calls your datasource which converts json into CSV and downloads the file
http://plnkr.co/edit/xK3TYtKANuci0kUgGacQ?p=preview
<button ng-click="exportAllData()">Export Data</button>
then in your controller:
$scope.exportAllData = function()
{
setTimeout(function()
{
$http.get('largeLoad.json').success(function(response)
{
$scope.JSONToCSVConvertor(response, "Data Title", true);
});
},100);
};
$scope.JSONToCSVConvertor = function(JSONData, ReportTitle, ShowLabel)
{
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
JSONToCSVConverter() source: http://jsfiddle.net/hybrid13i/JXrwM/

Related

how to skip first line of csv file data using angularjs?

I am using datatables to print the csv file data. The CSV file consists of data .this is an exmple data file.
name,city,category,discount
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
I want to skip first line of data . How to stop displaying th first line in my datatable. And my code is`
//saving csv file to firebase
$('#save-csv').bind('click', function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var file = document.getElementById('files').files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv);
var csvObj = {}
for(key in data){
csvObj[key] = {};
csvObj[key].name = data[key][0];
csvObj[key].city = data[key][1];
csvObj[key].category = data[key][2];
csvObj[key].discount = data[key][3];
}
console.log(csvObj);
$scope.csvStores.stores = csvObj;
$scope.csvStores.$save().then(function(res){
console.info(res);
}).catch(function(err){
console.error(err);
});
$("#myModal").modal("hide");
swal(
'Saved',
'Successfully Saved',
'success'
)
}
}else {
}
});
Before you iterate over your data you should somehow remove/skip the first line.
In my opinion it is better to remove, cause if you would like to use later this array, then you have to skip again.
I have two ideas:
before the iteration call:data = data.shift();
based on this: http://www.w3schools.com/jsref/jsref_shift.asp
This will remove the first element.
Or if you are using lodash, than you can easily call data = _.tail(data); based on this: https://lodash.com/docs/4.16.4#tail

store data issue with generic grid rendered in tabs

I have a generic grid component.
on click of menu item corresponding grid is displayed in independent tabs.
on rendering the grid component, store data is set dynamically and grid is populated.
The problem if I open two grids in two tabs, on navigating to the first tab, grid data is not displayed as the store data is set to second grid data.
Hoping to find solution.Thank you
code in main controller:
OnMenuItemClick: function(c){
var nodeText = c.text,
tabs = Ext.getCmp('app-tab'),
tabBar = tabs.getTabBar(),
tabIndex;
for(var i = 0; i < tabBar.items.length; i++) {
if (tabBar.items.get(i).getText() === nodeText) {
tabIndex = i;
}
}
if (Ext.isEmpty(tabIndex)) {
/* Note: While creating the Grid Panel,here we are passing the Menu/Grid Id along with it for future reference */
tabs.add(Ext.create('DemoApp.view.grid.GenericGrid',{title:nodeText,gridId:c.id,overflowY: 'scroll',closable:true}));
tabIndex = tabBar.items.length - 1 ;
}
tabs.setActiveTab(tabIndex);
}
code in generic grid controller:
renderGridMetadata: function(genericGrid) {
var store = Ext.getStore("DemoApp.store.GenericGrid"),
gridId = genericGrid.up().gridId,
resourceURL = "resources/data/" + gridId + ".json";
var serviceInput = Util.createServiceResponse(gridId);
/*Dynamically add the proxy URL to the ViewModel
DemoApp.model.GenericGrid.getProxy().setUrl(resourceURL);*/
Ext.getBody().mask("Loading... Please wait...", 'loading');
Ext.Ajax.request({
url: Util.localGridService,
method: 'POST',
headers: {
"Content-Type": "application/json",
'SM_USER': 'arun.x.kumar.ap#nielsen.com',
'SM_SERVERSESSIONID': 'asdfadsf'
},
jsonData: {
getConfigurationAndDataRequestType: serviceInput
},
success: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
var data = Util.decodeJSON(conn.responseText);
/* Apply REST WebServices response Metadata to the Grid */
var recordsMetaData = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record;
var jsonMetaDataArray = [];
for (var c = 0; c < recordsMetaData.length; c++) {
var jsonMetaDataObject = {};
var text = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record[c].displayName;
var dataIndex = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record[c].columnName;
jsonMetaDataObject["text"] = text;
jsonMetaDataObject["dataIndex"] = dataIndex;
jsonMetaDataArray.push(jsonMetaDataObject);
}
/* Apply REST WebServices response data to the Grid */
var recordsData = data.getConfigurationAndDataReplyType.gridDataResponse.record;
var jsonDataArray = [];
for (var r = 0; r < recordsData.length; r++) {
var columnsData = data.getConfigurationAndDataReplyType.gridDataResponse.record[r].column;
var jsonDataObject = {};
for (var c = 0; c < columnsData.length; c++) {
jsonDataObject[columnsData[c].columnId] = columnsData[c].columnValue;
}
jsonDataArray.push(jsonDataObject);
}
store.setData(jsonDataArray);
genericGrid.reconfigure(store, jsonMetaDataArray);
},
failure: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
Util.showErrorMsg(conn.responseText);
}
});
store.load();
}
});
Most likely there is only one instance of DemoApp.store.GenericGrid.
Frankly, I only guess because I see that you call Ext.getStore("DemoApp.store.GenericGrid") that implies the store is declared in stores:["DemoApp.store.GenericGrid"] array probably in the application class.
If a store is declared this way then Ext automatically creates one instance of it setting storeId to the string listed in stores:[]. Hence, Ext.getStore() returns that instance.
If you want to have two independent instances of the grid you have to create store instances yourself preferably in initComponent override.

How to loop range of cells and set value in adjacent column

I'm learning Google Apps Scripts for use with Google Spreadsheets.
I have a list of URLs in one column and I want to write a script to get the title element from each URL and write it in the adjacent cell. I have accomplished this for one specific cell as per the following script:
function getTitles() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("url_list");
var range = sheet.getRange("G3");
var url = range.getValue();
var response = UrlFetchApp.fetch(url);
var doc = Xml.parse(response.getContentText(),true);
var title = doc.html.head.title.getText();
var output = sheet.getRange("H3").setValue(title);
Logger.log(title);
return title;
}
This gets the URL in G3, parses it, pulls the element and writes the output in H3.
Now that I have this basic building block I want to loop the entire G column and write the output to the adjacent cell but I'm stuck. Can anyone point me in the right direction?
May look something like this:
function getTitles() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("url_list");
var urls = sheet.getRange("G3:G").getValues();
var titleList = [], newValues = [],
response, doc, title;
for (var row = 0, var len = urls.length; row < len; row++) {
if (urls[row] != '') {
response = UrlFetchApp.fetch(urls[row]);
doc = Xml.parse(response.getContentText(),true);
title = doc.html.head.title.getText();
newValues.push([title]);
titleList.push(title);
Logger.log(title);
} else newValues.push([]);
}
Logger.log('newValues ' + newValues);
Logger.log('titleList ' + titleList);
// SET NEW COLUMN VALUES ALL AT ONCE!
sheet.getRange("H3").offset(0, 0, newValues.length).setValues(newValues);
return titleList;
}

How can I make a grid with checkboxes that maintain state between page loads?

How can we make checkboxes remain checked when the page is refreshed in a Sencha ExtJS 3.3.0 GridPanel?
I have a GridPanel which displays some information with checkboxes. When the page is refreshed, the checkbox should still be checked.
Any suggestions, ideas, or code samples?
Had the same problem and I fixed it in such way - manually save id's of records that I show in cookies. Solution is not beautiful, but works for me.
store.on({
'beforeload': function () {
var checkeditems = [];
for(var i=0;i<gridResources.selModel.selected.length;i++)
{ checkeditems.push(grid.selModel.selected.items[i].data.ID);
}
if(checkeditems.length>0)
setCookie("RDCHECKBOXES", checkeditems.join("|"));
},
'load': function () {
if (getCookie("RDCHECKBOXES")) {
var checkeditems = getCookie("RDCHECKBOXES").split("|");
for (var i = 0; i<gridResources.store.data.items.length && checkeditems.length>0; i++) {
for(var j=0;j<checkeditems.length;j++) {
if (gridResources.store.data.items[i].data.ID == checkeditems[j]) {
gridResources.selModel.select(gridResources.store.data.items[i], true);
checkeditems.splice(j, 1);
break;
}
}
}
}
}
});
Here are code for functions getCookie() and setCookie():
// Example:
// setCookie("foo", "bar", "Mon, 01-Jan-2001 00:00:00 GMT", "/");
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
// Example:
// myVar = getCookie("foo");
function getCookie(name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset)
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
return(setStr);
}
Have you looked at all at the ExtJS documentation or the included samples? There's a sample grid using the CheckColumn extension that does exactly what you ask.
In the example linked, take note that the checkbox column is linked to a boolean record field
// in your record
{name: 'indoor', type: 'bool'}
and represented in the grid's column model by a CheckColumn:
// in the grid's column model
xtype: 'checkcolumn',
header: 'Indoor?',
dataIndex: 'indoor',
width: 55
This way, when boolean data comes into the store from the server in JSON or XML, the values are represented as checkboxes in the grid. As long as you write your changes to the server, your checkbox boolean values will be preserved.

How do I select elements from json_encode d array?

I'm using JSON and javascript to retrieve data from a php file which connects to the database. This is how my php code looks like:
while($row = $stmt->fetch_assoc()) {
$data[] = $row;
}
header("Content-type: text/plain");
echo json_encode($data,true);
This is my Javascript:
var displayfeeds = new ajaxObject('ajax/users/display.feeds.php');
displayfeeds.callback = function (responseText,status) {
var feed = JSON.parse(JSON.stringify(responseText));
$("#feeds-feedback").html(feed);
}
displayfeeds.update();
When I run this, it prints out an array like this:
[
{
"userID":"39160902151",
"content":"bar bar bar bar",
"published":"2011-06-07 10:33:35"
},
{
"userID":"5896858666",
"content":"foo foo foo foo foo",
"published":"2011-06-06 22:54:51"
}
]
My question is: How do I then display say "userID" and "content" from this?
I have really struggled. I am new in JSON.
You need to transform your json objects into html to display them. So in your callback function I would do something like this:
displayfeeds.callback = function (responseText,status) {
var feed = JSON.parse(JSON.stringify(responseText));
var html = '';
// build html for each feed item
for (var i = 0; i < feed.length; i++) {
html += '<h3>UserID:: '+ feed[i]['userID'] +'</h3>';
html += '<p>'+ feed[i]['content'] +'</p>';
html += '<div><strong>published</strong>: '+ feed[i]['userID'] +'</div>';
html += '<hr />';
}
// append content once all html is built
$("#feeds-feedback").append(html);
}
To get first user id:
var feed = JSON.parse(responseText);
feed[0].userID

Resources