Bind dynamic file contents in array format to jtable - arrays

I'm working with ASP.NET MVC 3, and wondering how to return the contents of a file, as an array to a jtable in a view. Each line of the array contains a comma separated list. (The contents of the file came from either a .csv file or excel spreadsheet)
The first column contains the field headers, and the number of field headers in the file can vary, so I guess you could say the contents of the jtable would be dynamic?
I've written jtables with explicitly named fields, but that's when I know how many fields to expect. In this case, it could be anywhere from 1 to 11 fields, and since the field names are in the first line of the array, i'm not quite sure how to setup the jtable to recognize them as column headers for the jtable.
For starters, here's a couple of examples of an array I would expect to bind to the table.
array[0] = "phone,first,last";
array[1] = "1111111111,firstname,lastname";
OR
array[0] = "first,last,email";
array[1] = "firstname,lastname,emailaddress#email.com";
For the first example, I would not need to display the 'email' field, and for the second I don't need the phone field. The actual contents would probably contain many lines, which is why I want to bind it to jtable with paging enabled.
In my controller method, I have the contents of the file as a string array, one line with comma separated fields per array item. Where do I go from there is the question.
Thanks for any help,
Carrie
Actually, I've solved my first problem by using the Expando object, to create a list of dynamic objects . . . problem now is that jtable seems to need to bind to the results returned from a post. The json object i now have has already been returned, so I don't need to do a post to get it. So, the question now is, is it possible to bind a json result to a jtable without making jtable do the post?
Again, thanks.

Working on a similar question; I am returning json and need to bind to jtable. Here is the code from within my ajax call. The only jtable method I found is the addRecord.
Hope this helps and I will edit as I improve and get this fully functional. Yeh, I know that I should only include well formed answers but since you have had no help, we can start with this and let it be a work in progress.
if (data.Result == "OK") {
for (var i = 0; i < data.Records.length; i++) {
$("#SearchResultsAddContact").jtable('addRecord', {
record: {
FirstName: data.Records[i].FirstName,
LastName: data.Records[i].LastName,
NumGroups: data.Records[i].NumGroups,
NumPhones: data.Records[i].NumPhones,
NumTexts: data.Records[i].NumTexts,
NumTags: data.Records[i].NumTags,
NumTDDs: data.Records[i].NumTDDs,
NumEmails: data.Records[i].NumEmails
}
});
}
$("#SearchResultsAddContact").jtable('load');
Make sure that you edit your jquery.jtable.js file as follows: (lines 1297-1308)
addRecord: function (options) {
var self = this;
options = $.extend({
**clientOnly: true,**
animationsEnabled: self.options.animationsEnabled,
url: self.options.actions.createAction,
success: function () { },
error: function () { }
}, options);
Change the clientOnly: to true

Related

React : Access data in .json file to check if it matches with an input

I'm doing a dashboard about covid. I want to use a json file but the way data is encapsulated causes me an issue.
As you can see, the "real" name of the country is written inside the "location" field inside the "airport" name. Is there a way I can sort of bypass the "airport" name to access "location" field ? (Maybe like going through all of the "airport" names and search for location inside of them or looking for "location" field directly). Then I will be able to check if the country written in the input matches with one country inside the json file.
There are only these 2 layers ("airport" name & what's inside) in the json file.
About my code, I'm usig react. For now I just fecth the url of the json file to get it.
Thanks in advance !
Just in case someone faces the same issue as me, this helped me find what to do :
Object.keys(data)
Creates an array consisting of all the keys present in the object
Object.values(data)
Creates an array consisting of all the values present in the object
Object.entries(data)
Creates an array consisting of both the keys and values present in the object
In my case, to get location I do this :
for (var i = 0; i < Object.values(data).length; i++) {
if (this.state.country === Object.values(data)[i].location) {
this.setState({
post: Object.values(data)[i]
})
}
}

ng2-smart-table display list of object

Is there a way to display a list of objects in a single table cell for ng2-smart-table? I have tried creating a renderComponent but I am getting an empty value. Another question is will the filtering and sorting still work for this?
As I understood , You have a object and you want to display that data in ng2-smart-table.
For that follow this step.
import { LocalDataSource } from 'ng2-smart-table';
source : any = LocalDataSource;
When you call API then you have to set that data in source.
this.apiService.POST({}, 'getProductList').subscribe((res) => {
console.log(res);
this.source = new LocalDataSource(res.data); // Set response as per your res.
});
As you can see I have also set one array and that array has objects of data and I have set in table.
I hope this may help you. :)

Extracting Arrays as values in a JSON file using AngularJS

This is sort of a three part question. I have a JSON file. A few of the values in the JSON file are arrays. Keeping that in mind:
1) On any given page, I'd only want one set of values coming out of the JSON file. For example (as you'll see in code below) my JSON file is a list of attorneys. On any given bio page, I'd obviously only want one attorney's information. I'm currently, successfully, doing this by pulling back the entire JSON and then using ng-show. But this is causing some other issues that I'll explain in later points, so I'm wondering if there's something to put in the app.factory itself to only bring back the one set in the first place.
2) As mentioned, some of the values are arrays. This comes into play two ways in this situation. One of the ways is that there is an array of quotes about the attorney that I'll need to drop into a JS array so that my JS function can loop through them. Currently, I'm hardcoding the quotes for the one test attorney but I'm really trying to figure out how to make this dynamic. This is one reason I'm trying to figure out how to bring back only one attorney's information so I can then, somehow, say his quotes go into this array.
3) Another array value is a list of his specialty areas. I have another, hardcoded, JS object, associating the short terms with the display names. I realized though, that this has two issues.
a) The JS renders after the Angular, so I can't reference that JS in the Angular code
b) I have no way , anyway, to display the JS dynamically inside the Angular code.
My solution to that aspect was to create a second JSON file holding the area hash but besides being a little cumbersome, I'm also not sure how to dynamically display just the ones I want. e.g: If my attorney only specializes in securities and litigation, how would I tell the code to only display {{areas.securities}} and {{areas.litigation}}? So,I'm open to thoughts there as well.
Here is the current, relevant code. If you need more, just ask.
Thanks.
attorneys.json (irrelevant lines removed)
{"attorneys":
[
{
"id":1,
"name":"Bob Smith",
"quotes":
[
{
"id": 1,
"quote": "Wonderful guy!",
"person": "Dovie"
},
{
"id": 2,
"quote": "If ye be wanting a haggis like no other, Bob be yer man!",
"person": "Angus McLoed"
},
{
"id": 3,
"quote": "Wotta Hottie!",
"person": "Bob's wife"
}
],
"areas": ["altdispute", "litigation", "securities"],
}
]
}
...and the relevant current JS object that I'm not sure what to do with:
var practiceareas = {
altdispute: "Alternative Dispute Resolution",
businesscorp: "Businesses & Corporations",
estateplanning: "Estate Planning",
futures: "Futures & Derivatives",
litigation: "Litigation",
productliability: "Product Liability",
realestate: "Real Estate",
securities: "Securities"
}
script.js (relevant function)
var idno = 0;
/* This is what I want replaced by the Angular pull */
var quotelist = ["\"Wonderful guy!\"<br/>-Dovie", "\"If ye be wanting a haggis like no other, Bob be yer man!\"<br/>-Angus McLoed", "\"Hubba, Hubba! What a hottie!\"<br/>-Bob's wife"];
$("#bio_quotes").html(quotelist[0]);
function quoteflip(id, total){
var src1 = quotelist[idno];
$("#bio_quotes").fadeOut(500, function(){
$("#bio_quotes").html(src1).fadeIn(500);
});
idno = (id + 1) % total;
window.setTimeout(function(){quoteflip(idno, quotelist.length);}, 5000);
}
window.setTimeout(function(){quoteflip(idno, quotelist.length);}, 500);
By the way, as far as the quotes, I'm even happy to turn the JSON into a more condensed version by removing the id and consolidating the quote and author - making it an array of strings instead of mini-objects - if that makes it easier. In fact, it might be easier as far as the function anyway.
Can definitely filter things out at the service / factory using Array.filter. If you want to filter it server side, you have to have the code at server side that will do that.
Not sure what your backend store is but definitely doable.
Again, you can do this pretty easily with Array.map which let you pull specific values into a new Array. If you just want the name and quotes' quote and person name, you can definitely do this using Array .filter and .map and bind the new array to your viewmodel / scope.
Hmm.. again, I'd disagree, this look like the same issue with JavaScript array manipulation. You can definitely as part of the transformation in point 1 and 2, include this so it will transfer area to the long practice area names. The easiest way to show the relevant practice area is to map it to the long name during the transformation in the service layer.
//get matching attorney from the store by id
var matches = data.attorneys.filter(function(a) {
return a.id === id;
});
//If match found,
if (matches.length === 1) {
var result = matches[0];
//map the long name for practicing area
//use the matching attorney's area name as key
//and overwrite the result areas with the map
result.areas = result.areas.map(function(a) {
return practiceareas[a];
});
return result;
}
See this solution: http://embed.plnkr.co/xBPju7/preview
As for the fade in and fade out, I'll let you figure it out...

Create an instance of a Model in its Controller

This is probably a simple question but I'm having a hard time trying to create an object of the Model. I want to create a temporary variable that is the same as the model so I can update its internal values according to the data I am posting to the action.
My data is successfully posted to the action in the controller.
Currently what I am doing is grabbing all the items in the database and then assigning it the first item from the array. This way I can overwrite existing value, but if the table is empty it won't work.
I am using cakephp 2.x, I am new to this stuff which will explain why I couldn't figure this out.
Here is the code from the controller:
public function lcadd()
{
if ($this->request->is('post'))
{
// Create a new Local Clock object
$temp = $this->LocalClock->find('all'); // THIS IS THE PROBLEM AREA
$temp = $temp[0];
$temp['LocalClock']['name'] = $this->request->data['LocalClock']['Name'];
debug($temp); // THIS DEBUG ONLY DISPLAYS SOMETHING IF THE DATABASE TABLE IS NOT EMPTY
debug($this->request->data); // THE DATA COMING IN IS CORRECT AND I CAN ACCESS IT WITHOUT A PROBLEM
if($this->request->data['LocalClock']['Time Zone'] == 0 or $this->request->data['LocalClock']['Time Zone'] == -1)
{
//debug('Hello');
$temp['LocalClock']['auto_offset'] = 1;
}
else if($this->request->data['LocalClock']['Time Zone'] == 1)
{
$temp['LocalClock']['auto_offset'] = 0;
}
// Check the value posted from the DST
if($this->request->data['LocalClock']['DST Definition'] == -1 or $this->request->data['LocalClock']['DST Definition'] == 0)
{
$temp['LocalClock']['in_month'] = 0;
}
else if($this->request->data['LocalClock']['DST Definition'] == 2)
{
$temp['LocalClock']['in_month'] = $this->request->data['LocalClock']['InMonth'];
}
if ($this->LocalClock->save($temp))
{
$this->set('localClocks', $this->request->data);
$this->set('islcAddValid', true);
$this->set('lcaddValidationErrors', false);
}
}
}
I can't figure out how to make a simple object from the model. The model is LocalClock, and the controller is LocalClocksController.
The function above is in the LocalClocksController.
Thanks in advance.
A few things I noticed...
FIRST ISSUE:
// Create a new Local Clock object
$temp = $this->LocalClock->find('all'); // THIS IS THE PROBLEM AREA
$temp = $temp[0];
That's not creating a new Local Clock object. The first line returns an array (ie, not an object) containing ALL records in your Local Clock database table. Then, the second line says 'take the first row of the results, and store it in $temp'. So, now $temp holds an array (still NOT an object), containing the data of the first record in the LocalClock table.
You actually don't need an object, though, since the 'save' method that you call later on doesn't accept an object - it just accepts an array of data. You also don't need to get anything from the database in order to save a new record. So the code above should be replaced with:
$temp = array(); // Create an empty array. We will populate it as we go, with the data for the new record.
All the stuff in the middle of your method, up until you try to save the record, should work fine as it is.
SECOND ISSUE:
if ($this->LocalClock->save($temp))
Before calling 'save', you'll first need to call 'create' -
$this->LocalClock->create(); // prepare the Model to save a new record
if ($this->LocalClock->save($temp)) // This should now save a new record successfully.
Make sense? Let me know if you have any more questions.
Also, understanding how to retrieve, manipulate and save data from Models is very crucial to using CakePHP, and if you learn how to do it properly from the beginning, you'll save yourself countless hours of frustration in future. I'd recommend reading the following pages end-to-end:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
http://book.cakephp.org/2.0/en/models/saving-your-data.html

How to stringify JSON to JavaScript array

My form in the html DOM is a checkbox to click (there can be more than one). The problem occurs in the description string when ever I use an apostrophe, since my list object is single-quote deliniated. This is one of the checkboxes in the form:
<input type="checkbox" id="cbx" name="cbx" value="{'getPic': 'url', 'picsrc': 'http://lh3.ggpht.com/_ZB3cttqooN0/SVmJPfusGWI/AAAAAAAADvA/GuIRgh6eMOI/Grand%20Canyon%201213_121508214.JPG', 'pos': None, 'description': 'Here's what it REALLY looks like at 5:30am! Bring your headlight!'}">
The javascript that reads the values of the checked checkboxes and pushes them into an array (list):
var pylist = [];
for (i=0; i<document.picList.cbx.length; i++) {
if (document.picList.cbx[i].checked) {
pylist.push( document.picList.cbx[i].value );
}
}
var getstr = JSON.stringify(pylist);
The problem is always that getstr at this point has chopped off everthing after the single quote in the description property.
I've tried different ways of escaping it to little avail.
The problem is that the value of the checkbox already is a JSON string. One solution would be to call JSON.parse() on the value:
var pylist = [];
for (i=0; i<document.picList.cbx.length; i++) {
if (document.picList.cbx[i].checked) {
pylist.push( JSON.parse( document.picList.cbx[i].value) );
}
}
var getstr = JSON.stringify(pylist);
I've run into the same issue - we stick json in a hidden field so we don't have to query the server on every page. We replace apostrophes with a "code" before putting into the html - we added a javascript function that replaces the code with an apostrophe.
Really hacky, but it works really well. Of course, we have one place in the code that gets json from the server and one place where javascript needs to parse it - if you find you're repeating the methods throughout your code, your mileage will vary.

Resources