Sencha Touch FormPanel With Store - sencha-touch

I have a store as follows.
var eventsStore = new Ext.data.Store({
model: 'Event',
sorters: [{
property: 'OccurringOn',
direction: 'DESC'
}],
proxy: {
type: 'ajax',
url: BaseURL + 'Events.php',
api: {
read: BaseURL + 'Events.php',
create: BaseURL + 'Events.php'
},
reader: {
type: 'xml',
root: 'Events',
record: 'Event'
},
writer: {
type: 'xml',
writeAllFields: false,
root: 'Events',
record: 'Event'
}
},
getGroupString: function(record) {
if (record && record.data.OccurringOn) {
console.log(record.get('OccurringOn'));
return record.get('OccurringOn').toDateString();
}
else {
return '';
}
}
});
I also have a List view which gets all Events fine. I have a form which allows user to add new event and I have FormPanel for it. The FormPanel has Toolbar which has Save button which when clicked will do following.
var eventCard = It's a card
var newEventCard = eventCard.items.items[1];
var currentEvent = newEventCard.getRecord();
newEventCard.updateRecord(currentEvent);
var errors = currentEvent.validate();
// here I check errors and prompt user about them
var eventList = eventCard.items.items[0].items.items[0];
var eventStore = eventList.getStore();
eventStore.add(currentEvent);
eventStore.sync();
eventStore.sort( [ { property: 'OccurringOn', direction: 'DESC' } ] );
eventList.refresh();
The above code adds two empty rows to the MySQL database and copies the event list view items with 3 empty new items. Why this is the behavior and what I am missing?
If you can tell me what parameters are sent as POST to the Events.php when I sync that would much appreciated.

It was my fault I figured out. I was echo'ing when there was POST request to the service.

Related

Using a custom Drop Down List field to set a value in a grid

I'm trying to use the Rally 2.1 SDK to set a custom data field (c_wsjf) in a grid. I have a custom drop down list that I want to check the value of (c_TimeCrticalitySizing).
I created c_TimeCrticalitySizing as a feature card field in my Rally workspace with different string values (such as "No decay"). Every drop down list value will set the custom field to a different integer. When I try to run the app in Rally I get this error:
"Uncaught TypeError: Cannot read property 'isModel' of undefined(…)"
I'm thinking the drop down list value may not be a string.
How would I check what the type of the drop down list value is?
How could I rewrite this code to correctly check the value of the drop down list so I can set my custom field to different integers?
Here's my code block for the complete app. I'm still trying to hook up a search bar so for now I directly call _onDataLoaded() from the launch() function.
// START OF APP CODE
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
featureStore: undefined,
featureGrid: undefined,
items: [ // pre-define the general layout of the app; the skeleton (ie. header, content, footer)
{
xtype: 'container', // this container lets us control the layout of the pulldowns; they'll be added below
itemId: 'widget-container',
layout: {
type: 'hbox', // 'horizontal' layout
align: 'stretch'
}
}
],
// Entry point of the app
launch: function() {
var me = this;
me._onDataLoaded();
},
_loadSearchBar: function() {
console.log('in loadsearchbar');
var me = this;
var searchComboBox = Ext.create('Rally.ui.combobox.SearchComboBox', {
itemId: 'search-combobox',
storeConfig: {
model: 'PortfolioItem/Feature'
},
listeners: {
ready: me._onDataLoaded,
select: me._onDataLoaded,
scope: me
}
});
// using 'me' here would add the combo box to the app, not the widget container
this.down('#widget-container').add(searchComboBox); // add the search field to the widget container <this>
},
// If adding more filters to the grid later, add them here
_getFilters: function(searchValue){
var searchFilter = Ext.create('Rally.data.wsapi.Filter', {
property: 'Search',
operation: '=',
value: searchValue
});
return searchFilter;
},
// Sets values once data from store is retrieved
_onDataLoaded: function() {
console.log('in ondataloaded');
var me = this;
// look up what the user input was from the search box
console.log("combobox: ", this.down('#search-combobox'));
//var typedSearch = this.down('#search-combobox').getRecord().get('_ref');
// search filter to apply
//var myFilters = this._getFilters(typedSearch);
// if the store exists, load new data
if (me.featureStore) {
//me.featureStore.setFilter(myFilters);
me.featureStore.load();
}
// if not, create it
else {
me.featureStore = Ext.create('Rally.data.wsapi.Store', {
model: 'PortfolioItem/Feature',
autoLoad: true,
listeners: {
load: me._createGrid,
scope: me
},
fetch: ['FormattedID', 'Name', 'TimeCriticality',
'RROEValue', 'UserBusinessValue', 'JobSize', 'c_TimeCriticalitySizing']
});
}
},
// create a grid with a custom store
_createGrid: function(store, data){
var me = this;
var records = _.map(data, function(record) {
//Calculations, etc.
console.log(record.get('c_TimeCriticalitySizing'));
var timecritsize = record.get('c_TimeCriticalitySizing');
//console.log(typeof timecritsize);
var mystr = "No decay";
var jobsize = record.get('JobSize');
var rroe = record.get('RROEValue');
var userval = record.get('UserBusinessValue');
var timecrit = record.get('TimeCriticality');
// Check that demoniator is not 0
if ( record.get('JobSize') > 0){
if (timecritsize === mystr){
var priorityScore = (timecrit + userval + rroe) / jobsize;
return Ext.apply({
c_wsjf: Math.round(priorityScore * 10) / 10
}, record.getData());
}
}
else{
return Ext.apply({
c_wsjf: 0
}, record.getData());
}
});
// Add the grid
me.add({
xtype: 'rallygrid',
showPagingToolbar: true,
showRowActionsColumn: true,
enableEditing: true,
store: Ext.create('Rally.data.custom.Store', {
data: records
}),
// Configure each column
columnCfgs: [
{
xtype: 'templatecolumn',
text: 'ID',
dataIndex: 'FormattedID',
width: 100,
tpl: Ext.create('Rally.ui.renderer.template.FormattedIDTemplate')
},
{
text: 'WSJF Score',
dataIndex: 'c_wsjf',
width: 150
},
{
text: 'Name',
dataIndex: 'Name',
flex: 1,
width: 100
}
]
});
}
});
// END OF APP CODE
The app works great until I add the if (timecritsize === mystr) conditional.
I also use console.log() to check that I've set all values for timecritsize to "No decay"

Dynamically load data to grid

I need help.
I have grid with toolbar when i create new grid with data (open window of create via button in toolbar)
the new row not displayed only after reloading the page i see the new row.
Thank you.
this is store:
var writer = new Ext.data.JsonWriter({
type: 'json',
encode: false,
listful: true,
writeAllFields: true,
returnJson: true
});
var reader = new Ext.data.JsonReader({
totalProperty: 'total',
successProperty: 'success',
idProperty: 'Id',
root: 'Data',
messageProperty: 'message'
});
var proxy = new Ext.data.HttpProxy({
reader: reader,
writer: writer,
type: 'ajax',
api: {
read: '/Item/Get',
create: '/Cart/CreateCart',
update: '/Cart/CreateCart',
destroy: '/Cart/CreateCart',
add: '/Cart/CreateCart'
},
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
});
Ext.define('ExtMVC.store.Items', {
extend: 'Ext.data.Store',
model: 'ExtMVC.model.Item',
autoLoad: true,
paramsAsHash: true,
autoSync: true,
proxy: proxy
});
this is methode to create:
additem: function (button) {
var win = button.up('window'),
form = win.down('form'),
values = form.getValues();
Ext.Ajax.request({
url: 'Item/CreateItem',
params: values,
success: function (response, options) {
var data = Ext.decode(response.responseText);
if (data.success) {
Ext.Msg.alert('Create', data.message);
}
else {
Ext.Msg.alert('Create', 'Creating is faild');
}
win.close();
}
});
}
In your function addItem you add the data (record) to your database, you don't add this record to the store (that's bound to the grid).
Because you save the data to your database it's loaded to the store (and shown in the grid) after you reload.
You can add the record to your store as follows:
var win = button.up('window'),
form = win.down('form'),
values = form.getValues();
var store = *referenceToYourGrid*.getStore();
var model = Ext.ModelMgr.getModel(store.model);
var record = model.create();
record.set(values);
store.add(record);
Now it should show in your store. Instead of store.add you could you store.insert(0, record) to insert the record in a specific place. In this case as first record (position: 0). Store.add will place the record on the end of the store (and grid). You could store.sync() to save the record to the database instead of the Ajax request. You have the api property of the proxy allready configured.

Not storing value on localstorage in sencha

I am trying to store data offline aspect, but here i want to store data on localstorage, did not store able to store this, all value getting null in localstorage.
This the based on ; http://www.robertkehoe.com/2012/11/sencha-touch-2-localstorage-example/
Models:
*Online.js*
Ext.define('default.model.Online', {
extend: 'Ext.data.Model',
config: {
fields: [
'cat_id',
'category_name'
]
}
});
Offline.js
Ext.define('default.model.Offline', {
extend: 'Ext.data.Model',
config: {
fields: [
'cat_id',
'category_name'
],
identifier:'uuid', // IMPORTANT, needed to avoid console warnings!
proxy: {
type: 'localstorage',
id : 'category'
}
}
});
Stores:
Ext.define('default.store.News', {
extend:'Ext.data.Store',
config:{
model:'default.model.Online',
proxy: {
timeout: 3000, // How long to wait before going into "Offline" mode, in milliseconds.
type: 'ajax',
url: 'http://alucio.com.np/trunk/dev/sillydic/admin/api/word/categories/SDSILLYTOKEN/650773253e7f157a93c53d47a866204dedc7c363?_dc=1376475408437&page=1&start=0&limit=25' , // Sample URL that simulates offline mode. Example.org does not allow cross-domain requests so this will always fail
reader: {
type: "json",
rootProperty: "data"
}
},
autoLoad: true
}
});
Controller:
Ext.define('default.controller.Core', {
extend : 'Ext.app.Controller',
config : {
refs : {
newsList : '#newsList'
}
},
init : function () {
var onlineStore = Ext.getStore('News'),
localStore = Ext.create('Ext.data.Store', {
model: "default.model.Offline"
}),
me = this;
localStore.load();
onlineStore.on('refresh', function (store,record) {
Ext.Msg.alert('Notice', 'You are in online mode', Ext.emptyFn);
// console.dir(record.data.name);
console.dir(record.get('category_name'));
console.log(record.items[0].raw.category_name);
console.log(record.get('category_name'));
// Get rid of old records, so store can be repopulated with latest details
localStore.getProxy().clear();
store.each(function(record) {
var rec = {
name : record.data.category_name+ ' (from localStorage)' // in a real app you would not update a real field like this!
};
localStore.add(rec);
localStore.sync();
});
});
onlineStore.getProxy().on('exception', function () {
me.getNewsList().setStore(localStore); //rebind the view to the local store
localStore.load(); // This causes the "loading" mask to disappear
Ext.Msg.alert('Notice', 'You are in offline mode', Ext.emptyFn); //alert the user that they are in offline mode
});
}
});
I think, I am not getting value from this record.data.category_nam . Here I am getting first value from this:record.items[0].raw.category_name. So how to store in localstorage.
and View file:
Ext.define('default.view.Main', {
extend : 'Ext.List',
config : {
id : 'newsList',
store : 'News',
disableSelection : false,
itemTpl : Ext.create('Ext.XTemplate',
'{category_name}'
),
items : {
docked : 'top',
xtype : 'titlebar',
title : 'News List'
}
}
});
In localstorage, following output:
category-5ea01a8d-ef1e-469e-8ec4-790ec7306aaf
{"cat_id":null,"category_name":null,"id":"5ea01a8d-ef1e-469e-8ec4-790ec7306aaf"}
category-f3e090dd-8f25-4b20-bb6e-b1a030e07900
{"cat_id":null,"category_name":null,"id":"f3e090dd-8f25-4b20-bb6e-b1a030e07900"}
category-5148e6eb-85ae-4acd-9dcd-517552cf5d97
{"cat_id":null,"category_name":null,"id":"5148e6eb-85ae-4acd-9dcd-517552cf5d97"}
category-ec23ff8b-1faa-4f62-9284-d1281707a9bc
{"cat_id":null,"category_name":null,"id":"ec23ff8b-1faa-4f62-9284-d1281707a9bc"}
category-6c1d
I have display in view but could not store in localstorage for offline propose.where i did wrong, i could not get it.
Record you created should match the SF.model.Offline model.
In your following code
var rec = {
// name is the field name of the `SF.model.Offline` model.
name : record.data.category_name+ ' (from localStorage)'
};
localStore.add(rec);
localStore.sync();
But you see there is no field called name in SF.model.Offline model.
This is how you should do
Models
Ext.define('SF.model.Online', {
extend : 'Ext.data.Model',
config: {
fields: ['cat_id','category_name'],
}
});
Ext.define('SF.model.Offline', {
extend : 'Ext.data.Model',
config: {
fields: ['cat_id','category_name'],
identifier:'uuid',
proxy: {
type: 'localstorage',
id : 'category'
}
}
});
Store
Ext.define('SF.store.Category', {
extend : 'Ext.data.Store',
config : {
model : 'SF.model.Online',
storeId : 'category',
proxy: {
timeout: 3000,
type: 'ajax',
url: 'same url' ,
reader: {
type: "json",
rootProperty: "data"
}
},
autoLoad : true
}
});
In Controller
var onlineStore = Ext.getStore('category'),
localStore = Ext.create('Ext.data.Store', {
model: "SF.model.Offline"
}),
me = this;
localStore.load();
onlineStore.on('refresh', function (store, records) {
localStore.getProxy().clear();
onlineStore.each(function(record) {
//You creating record here, The record fields should match SF.model.Offline model fields
var rec = {
cat_id : record.data.cat_id + ' (from localStorage)',
category_name : record.data.category_name + ' (from localStorage)'
};
localStore.add(rec);
localStore.sync();
});
});
onlineStore.getProxy().on('exception', function () {
me.getNewsList().setStore(localStore);
localStore.load();
Ext.Msg.alert('Notice', 'You are in offline mode', Ext.emptyFn);
});

Kendo Grid Foreign Key template

I have a foreign key inside my kendo grid, and I have created an editor for this foreign key. It's working Ok in saving, but the problem is that when the grid displays data, the foreign key value is undefined. I know I have to change the template to show correct value. I have added the function intemplate to show the correct value, but it's not working for me.
Can you help me please? Here is my code:
var collection;
$("#mygrid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: [{ name: 'create', text: 'My create' }],
columns: [
{ field: "ForeignKeyColumn", editor: categoryDropDownEditor, template: "#=getTextByValue(data)#" },
{ field: "NOTES", title: "Notes" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }],
editable: "popup",
});
//update model when choose value from dropdown list
var grid = $("#mygrid").data("kendoGrid");
grid.bind("save", grid_save);
function grid_save(e) {
if (e.model.ForeignKey) {
//change the model value
e.model.ForeignKeyColumn = 0;
//get the currently selected value from the DDL
var currentlySelectedValue = $(e.container.find("#typeCombo")[0]).data().kendoDropDownList.value();
//set the value to the model
e.model.set('ForeignKeyColumn', currentlySelectedValue);
}
}
//Editor template
function categoryDropDownEditor(container, options) {
$('<input id="typeCombo" required data-text-field="text" data-value-field="value" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: true,
dataSource: {
type: "json",
transport: {
read: {
url: '#Url.Action("SomeAction", "SomeController")',
type: "POST",
contentType: "application/json",
}
}
}
});
}
//Show template
function getTextByValue(data) {
//if the collection is empty - get it from the grid
if (!collection) {
grid = $("#GridName").data("kendoGrid");
valuesCollection = grid.options.columns[1].values;//Set the correct FKColumn index
collection = {};
for (var value in valuesCollection) {
collection[valuesCollection[value].value] = valuesCollection[value].text;
}
}
return collection[data.ForeignKeyColumn];
}
Note: valuesCollection value is undefined when I trace.
Try this,
I think it's necessary for binding foreign key column in grid. Please do not change the .cshtml view name or folder name.
Store in this location:
Location: - YourViews -> Shared -> EditorTemplates -> GridForeignKey.cshtml
GridForeignKey.cshtml:
#(Html.Kendo().DropDownListFor(m => m)
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(""))
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
.OptionLabel("--Not Category--")
)

Ext Js - TreeStore not loading data when using ASP.net WCF Service

I am trying to build a dynamic tree. I am getting my data from a C# WCF Service. It is returning me JSON data , but data is not reflecting in tree.
I am using EXTJS 4.
.Js Code -
Ext.require([
'Ext.tree.*',
'Ext.data.*',
'Ext.tip.*'
]);
Ext.onReady(function () {
Ext.QuickTips.init();
var store = Ext.create('Ext.data.TreeStore', {
proxy: {
type: 'ajax',
url: 'Services/InfographicsDataService.svc/GetTree'
},
root: {
text: 'Ext JS',
id: 'src',
expanded: true
},
reader: {
type: 'json',
root: 'd'
}
}); // End of store code
var tree = Ext.create('Ext.tree.Panel', {
store: store,
viewConfig:
{
plugins:{ ptype: 'treeviewdragdrop' }
},
renderTo: 'tree-div',
height: 300,
width: 250,
title: 'Files',
useArrows: true
}); // End of tree
}); // End of ready function
This is the code at my service end-::
[OperationContract]
[WebGet]
public List<TreeNode> GetTree()
{
List<TreeNode> nodes = new List<TreeNode>();
nodes.Add(new TreeNode() { id="src/ModelManager.js", text =
"ModelManager.js" });
nodes.Add(new TreeNode() { id="src/data", text = "data" });
nodes.Add(new TreeNode() { id="src/draw", text = "draw" });
return nodes;
}
Json returned by wcf service--
{"d":[
{
"__type":"TreeNode:#Infographics.Services.Model",
"id":"src\/ModelManager.js",
"leaf":false,
"text":"ModelManager.js"
},
{
"__type":"TreeNode:#Infographics.Services.Model",
"id":"src\/data",
"leaf":false,
"text":"data"
},
{
"__type":"TreeNode:#Infographics.Services.Model",
"id":"src \/draw",
"leaf":false,
"text":"draw"
}]
}
Call is going to server and returning the data but not adding nodes in tree
Page is showing just the root Extjs node.
Initially I thought , it is just root property of reader which I need to set to "d" , but there is something more I am missing.
Can somebody help me in finding what is that small mistake I am making ?
Can you change the store like this and try,
var store = Ext.create('Ext.data.TreeStore',
{
proxy:
{
type: 'ajax',
url: 'Services/InfographicsDataService.svc/GetTree',
reader:
{
type: 'json',
root: 'd'
}
},
root:
{
text: 'Ext JS',
id: 'src',
expanded: true
}
});