I'm getting a "newItem() was not passed an identity for the new item" error while trying to add a new item to a JSON store - javascript

I've seen other posts in this site regarding the same issue and I've tried the solutions given. I've also visited the links that may offer a solution but I'm still stuck with the same error.
I'm using DOJO and something as simple as this won't even work
myStore.newItem({id: 'test', otherfield: 'otherinfohere'});
myStore.save();
Supposedly the "newItem() was not passed an identity for the new item" error appears when you haven't provided an identifier for the new item, which i have.
The whole purpose of this (Just in case anyone can provide a good idea or has done something similar before) is that i want to create a data grid that shows info from a particular store. The problem is, that in that store all the items may not have the same structure. For instance:
I may have a store that looks like this
{identifier: 'id',
label: 'name',
items: [
{ id:'1', name:'Ecuador', capital:'Quito' },
{ id:'2', name:'Egypt', capital:'Cairo' },
{ id:'3', name:'El Salvador', capital:'San Salvador' , additionalField: 'otherinfohere'},
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo', additionalField: 'otherinfohere'},
]}
This is possible because I'm the one constructing the store in a Spring Controller (I'm also using the Spring Framework) from information I have locally stored in a Berkeley DB. So what i need is a data grid with a dynamic layout because I don't want blank spaces to show in the view in the rows with lesser amount of fields, and i need to show all the info in the store at the same time, but i don't know how to do this.
I thought of doing it by creating a simple layout of only 1 field. In it I would load data from a store i create dynamically at runtime. The data in the store would be composed of HTML combined with the values coming from the original store so I could obtain something like this, which is inside an attribute of a JavaScript Object and let the browser parse it for me:
<div><span>id: originalID </span>....</div>
This of course is a simple example, the html layout i'm looking for is far more complicated, but i think that passing it as a string to an object might do the trick.
The problem is that i don't even know if that idea will work because i get that error whenever i try to add values to my secondary store.
rdb.modules.monitor.historicStore.fetch({onComplete: function(items, request){
for (var i = 0; i < items.length; i++){
var item = items[i];
var obj = new Object();
obj.id = rdb.modules.monitor.historicStore.getValue(item, "id");;
var html = "<div><span>";
html += rdb.modules.monitor.historicStore.getValue(item, "sql");
html += "</span></div>";
obj.html = html;
myStore.store.newItem(obj);
}
}});
In this context "historicStore" refers to the JSON store that has the values that i need to convert and add to "myStore" after i added some HTML.
I hope you got the main idea of what I'm trying to do. If anyone can help me we either of these problems i would really appreciate it. Thanks in advance

For the issue regarding store:-
"id" is mandatory for a store, if it is going to be used for a grid(datagrid, EnhancedGrid, etc. whatever). The items are handled only on basis of "id" attribute by the grid data structures.
Usually, id can be a loop variable/ auto incrementation, to avoid any cases like you have said. Before adding the store to the grid, ensure that all items have the id attribute. You can write a function which will loop through each item and check for this, else add an auto-incrementing value for the id attribute of that item.

Related

How can I change the value in a nested array of objects, after a button click using JQuery and javascript?

I'm trying to make a voting app using Node.js, Javascript, JQuery, Jade and a json file for practice.
In short, I'm trying to count the votes for each option to eventually render it into a chart. Specifically I was trying to add + 1 to the object value {"value": 0} in the json each time someone chooses a radio button correlated to the option and hits submit. I can get to the e.g. {"option": "Puppies","value": 0} in my JQuery and I've been trying to find a way to change the object value within the $("#btnVote").click(function(){}). I'm not sure if that would be possible or the best way.
Here is a sample of the JSON database.
[{
"name": "Puppies or Kitties",
"id": "f2754172-1c58-41ed-ae84-74e046888adb",
"choices" : [{"option": "Puppies","value": 0}, {"option": "Kittens","value": 0}],
"admin": true}]
Here is the Jade I am using to dynamically render the poll options.
form(method="post")
fieldset.form-group
h1 #{poll.name}
form
table
each choice in poll.choices
tr
td=choice.option
input(type='radio',value=choice.value id=choice.option name="Answer" class="clsAnswer", style='margin:10px')
br
input(type="button", value="Submit Vote", id="btnVote")
A visual if it helps
Here is the JQuery I've used so far;
//Radio button vote function
$("#btnVote").click(function () {
var selected = $(".clsAnswer:checked");
if (!selected.val()) {
alert("No Choice Was Made!");
}
else {
var optionName = $('input[type=radio][name=Answer]:checked').attr('id');
var selectedValue = selected.val();
selectedValue = parseInt(selectedValue);
alert("Value: " + selectedValue + " " + optionName);
};
});
Thank you all in advance!
There are two ways that you can change the object value in this case, either through your JSON being in a database such as mongodb or through cookies as a temporary change.
The current JQuery is set up to receive the static html and not from the JSON file.
Since the JSON file is used as practice in the folder hierarchy and static (as well as the html), this current setup will not render updating the object value in JSON or even as a temporary change as you would maybe see in cookies.
One other alternative would be to use node.js and create a new JSON file but that is not what is being aimed at in this application.

Redux handling new items and ids

I have my normalized store with lists and id mappings:
{
"byId": {
"images": {
"10984": {"id": "10984", "src": "/img.png"}
}
},
"myImages": [
"10948"
]
}
Now I want to create a new image, and add it to the list. The problem is that I don't have an id for it until I send it to the server. So I could generate a random id
"tempid19048": {"id": "tempid19048", src: "/img.png"}
"myImages": [
"10948",
"tempid19048"
]
And then I save it to the server and get an id back I dispatch an action. I may have tempid19048 used in multiple parts of the state.
What's a sane way to update everything with the new id? Am I approaching this all wrong?
Because Redux is really a client-side state manager, generally you just want to mirror the global state and thats it. As you know, unlike Flux/GraphQL, there isn't any functionality for caching, optimistic updates etc. My gut tells me building this would be difficult without compromising the pure simplicity that Redux is built on.
That said, I found redux-optimistic that mimicks Flux's optimistic updates for Redux. I've not used it, but it looks nice enough.
But with even with that said, I'd still highlight the simple solution of designing-out any need for temp ids / optimistic updates etc:
make a request to create the image on the server
show a spinner
on success message from the server, add the new image with the new id to the global state
You can make IDs in "myImage" as key-value pair.
"myImages": {
"10948": "10948",
"tempid19048": "tempid19048"
}
Now where ever you want to use you can use as
myImages["tempid19048"]
This will give you its current value as "tempid19048".
And if you need to change this tempId you need to change only the value, and key remains same.
"myImages": {
"10948": "10948",
"tempid19048": "newServerID"
}
Hence, irrespective of number of places you are using tempID now you need to update in only one place.

Databinding to Windows 8 ListView

I'm having massive problems with databinding to a ListView in a Windows 8 app using Javascript.
Inside the "activated" event on default.js I have written some code to get some data from a web service and push it into an array. This bit works OK and the array is populated.
The problem I have is that the app won't recognise the data. I have this code in a page called inspections.html:
data-win-options="{itemTemplate: select('#imageTextListCollectionTemplate'),
itemDataSource: dataList.dataSource,
layout: {type: WinJS.UI.ListLayout}}
and then in the "activated" event I declare:
var dataList = new Array();
and push the data from the web service into this array. But at runtime I get an error that says something along the lines of "can't find dataSource on undefined dataList".
I've done some of the examples on the MS website and in one of them it creates a dummy dataset and references it from a namespace. I kinda think that what I'm missing here is a namespace too but I don't know what the namespace for default.js is. Or maybe I'm wrong and it's something totally different.
Please help - this is so fundamental (and should be easy) but I can't get my head around it.
Do you want to create datalist in HTML or javascript?
It seems you want to create it from JavaScript. Assuming that you have already pushed your data into array from your webservice, you only need to call:
var dataList = new WinJS.Binding.List(array);
now accessing dataList.dataSource is perfectly valid.
Also, to create the datalist you don't always need an array. You could probably start with an empty list and then keep inserting data directly into the data list from web services, like:
var dataList = new WinJS.Binding.List([]);
dataList.push(value1);
dataList.push(value2);
...
Hope it helps. Let me know if you have any more questions.
If you are getting troubled by assigning datasource in HTML side
Prefer js side like
var list = new WinJS.Binding.List(array here);
listView.itemDataSource = list.dataSource;
by using this you can easily go through the data which you are binding to ListView.

How to pass id from one store to be used in another in Sencha touch 2

I have 2 stores, one for events and one for data captured for that event. I am trying to get the id from the events store and use it in the data store. I have the following field in my data model:
{ name: 'eventId', type: 'int' },
My controller fetches the form data, validates it and after this, my code fails. I am trying the following to get the id from the first store and then set it in the second store
var idStore = Ext.getStore('Details');
var id = idStore.findRecord('id');
currentData.set('eventId', newValues.id);
My console returns null for var id, which leads me to believe that my code is wrong, can someone help explain to me how I fetch the id and use it?
Thanks
I figured it out, the docs Docs say to specify the value after the field. All I had to do was to add '1' after the 'id' field.
This does raise some questions though, I have to ensure that my id's always start with '1', does anyone know of a better way?

Get full data set, sorted with YUI Data Table with Pagination

I hope I am describing my issue enough.. here goes:
I have a YUI data table, get a server side set of records via JSON, and then populates the data.
Users can click on the headers to sort the data in three of the 6 columns, (which are using a custom sort function for each column). The sorting is done client-side.
When a user sorts the data, I need to be able to get a complete list of the values from one of the columns being shown. I need all the data available, not just what's rendered to the page. The data hidden via pagination must be included.
Any ideas? I've tried the handleDataReturnPayload and doBeforeLoadData methods of the DataTable but both give the original, unsorted data.
I'm really stuck here and I've got a client depending on a feature that depends on me getting this sorted list.
Thanks in advance.
Satyam, over at the YUI Forums answered my question perfectly.
The data is actually stored in the
RecordSet. At any time you can go and
look at it, and it will be sorted as
shown on the screen, but it will have
all the data, whether shown or not.
Method getRecordset() will give you a
reference to it and then you can loop
through its records.
You can listen to the columnSortEvent
to be notified a sort has occurred.
I just subscribed to the columnSortEvent event and looped through the array returned by datatable.getRecordSet().getRecords().
I'd recommend posting this to the YUI forums -- http://yuilibrary.com/forum/ -- that's a great place to get support on DataTable issues.
I stumbled upon this question looking for information on how to retrieve information from a dataset that was NOT displayed in the datatable. IF you place the hidden data in the datasource before any field you wish to be displayed, it will be rendered blank, but if you place it after your last field that will be rendered (as defined by the columns object), then they will not render but still be accessible through the record).
var columns = [
{key:"Whatchamacallits", children:[
{key:"name" },
{key:"price" }
]}
];
var ds = new YAHOO.util.DataSource('index.php...');
oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
oDataSource.responseSchema = {
fields:["name","price","id"]
};
var dt = new YAHOO.widget.DataTable("dt-id", columns, ds, {});
dt.subscribe("rowClickEvent", dt.onEventSelectRow);
dt.subscribe("rowSelectEvent", function(p){ alert(p.getData('id'); });

Categories

Resources