Dynamically load data to grid - extjs4

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.

Related

JQuery DataTable data not available even data is received from server

I want to draw a table to show users data from my server.
First I am using Ajex to get the users data:
var usersList = {};
usersList.users = ["Afthieleanmah", "Hadulmahsanran","tabletest1"];
var dataSet1=[];
var i;
$.ajax({
url: '../users',
type: 'POST',
contentType: 'application/json',
cache: false,
data: JSON.stringify(usersList),
success:function(response, text){
if(response.users !== undefined){
dataSet1 = response.users;
}
}
});
I can successfully get the users data and save the data in dataSet1 as a JSON array contains Objects. Its format is like this:
[
{
username: "Tiger Nixon",
job_title: "System Architect",
city: "Edinburgh",
extn: "5421"
},
{
username: "Tiger Nixon2",
job_title: "System Architect",
city: "Edinburgh",
extn: "5421"
}
]
Then I create a table and pass in configuration:
// table confirgurations
var tableConfig={
pageLength: 5,
bLengthChange: false,
columns:[
{data: "username", title: "Name"},
{data: "job_title", title: "Position"},
{data: "city", title: "City"}
],
data:dataSet1
};
// create table
var userTable=$('#table-id').DataTable(tableConfig);
I am sure that I can get users data from API "/users" and save it into dataSet1. But everytime I load the page containing the table, the table always shows "No data available in table". I set a breakpoint on this line :
var tableConfig={
and let it continue to run. The weird things happen. The Table shows the data.............. No idea why
You should initialize your table after you receive response from the server in the success function. Also use destroy in case you're performin your Ajax request multiple times.
For example:
$.ajax({
// ... skipped ...
success:function(response, text){
if(response.users !== undefined){
dataSet1 = response.users;
}
// table confirgurations
var tableConfig={
// ... skippped ...
destroy: true
};
// ... skippped ...
var userTable=$('#table-id').DataTable(tableConfig);
}
});
However ideally you should let jQuery DataTables do the Ajax request using ajax option.

How To pass Id in jQUERY

Want to perform Edit in popup, I have code but its not working
here is my script
$("#mylink").click(function(e) {
var count = 0;
var $dialog = $("<div id='divCreateTask'></div>");
var Id = $(this).data(e);//
url: "TaskTimeSheet/EditTaskPopUp/" + Id //
var url = "EditTaskUrl" + id;var url = '#Url.Action("EditTaskPopUp", "TaskTimeSheet")';
url += '/?Id=' +Id; $("#tab1").load(url);
$dialog.empty();$dialog.dialog({
autoOpen: true,
width: 600,
height: 650,
resizable: false,
modal: true,
open: function (event, ui) {
$(this).load(url);
},
buttons: {
"Cancel": function () {
$(this).dialog("close"); }
});
} });
#Html.ActionLink("Edit", "TaskTimeSheet", new {id="mylink", param = dr["id"].ToString() })
From this link i have to pass id .....
This all is loaded in table Table Each row Have Edit Button ....now ho to pass Id to the querY,..
use an ajax call
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'post',
cache: false,
async: true,
data: { id: "ID" },
success: function(result){
$('.divContent').html(result);
}
});
});
your controller action would be something like
[HttpPost]
public PartialViewResult Action(int id){
var Model = //query the database
return PartialView("_PartialView", Model);
}
This will call your controller, return a partial view and put it into a container with class "divContent". Then you can run your dialog code to pop up the container.
row id update
to get the id of a table row I use this in the row click event
$(this).closest('tr').find('.ID').val(); // or .html() if you have put it in the cell itself
this will get the row that you are on and then find a cell in that row with class ID. Hopefully this helps.

Print form values

I have the following form. I need to print the value the user entered for textfiled uname ? How can i do this ?
Ext.create('Ext.form.Panel', {
title: 'Basic Form',
renderTo: Ext.getBody(),
bodyPadding: 5,
width: 350,
// Any configuration items here will be automatically passed along to
// the Ext.form.Basic instance when it gets created.
// The form will submit an AJAX request to this URL when submitted
url: 'save-form.php',
items: [{
fieldLabel: 'NAME',
name: 'uname'
}],
buttons: [{
text: 'Submit',
handler: function() {
// The getForm() method returns the Ext.form.Basic instance:
var form = this.up('form').getForm();
if (form.isValid()) {
// CONSOLE.LOG (FORM VALUES) ///////////////////////////////////////
}
}
}]
});
Use the getValues method to get an object containing all of the field values in the form:
var form = this.up('form').getForm();
if (form.isValid()) {
var values = form.getValues();
// log all values.
console.log(values);
// log uname value.
console.log(values['uname']);
}
Alternatively, use the findField method to access a specific field within the form:
var form = this.up('form').getForm();
if (form.isValid()) {
// log uname value.
var field = form.findField('uname');
console.log(field.getValue());
}
Example: http://jsfiddle.net/5hndW/

Creating CheckBox for JSON Objects

I am using extjs4,I need to add check box group based on my JSON Object,
JSON
{"Provider":[{"id":3,"name":"Beta House","npi":0,"taxId":0,
"address":{
"state":{"id":"1","stateName":"Alabama","code":"AL"},
"zipcode":0,"country":"USA","email":"beta#gmail.com"},
"type":"CP","LabProvider":[],"ListOfProvider":[]}]}
ExtJs
Ext.define('providerList', {
extend: 'Ext.data.Model',
fields: ['id','name']
});
var provider = Ext.create('Ext.data.Store', {
model: 'providerList',
autoLoad: true,
proxy: {
type: 'ajax',
url : url+'/lochweb/loch/clinicalProvider/getAll',
reader: {
type: 'json',
root: 'Provider'
}
}
});
Panel
var checkboxconfigs = [];
provider.each(function(record) {
checkboxconfigs.push(
{
boxLabel: 'record.id',
name: 'record.name'
})
});
var checkboxes = new Ext.form.CheckboxGroup({
fieldLabel:'Providers',
columns:2,
items:checkboxconfigs
});
var patientProvider = new Ext.FormPanel({
renderTo: "patientProvider",
frame: true,
title: 'Association',
bodyStyle: 'padding:5px',
width: 500,
items: [{
checkboxes
}],
});
There is no check box in the form.How to populate checkbox from JSON store
You can define the items array before you use it as children of checkboxes. Each element of items array is created base on each record of the store.
var items = [];
provider.each(function(record) { items.push({boxLabel: 'up-to-you', name: 'up-to-you'}) }, );
var checkboxes = new Ext.form.CheckboxGroup({
fieldLabel:'Providers',
columns:2,
items:items
});
Here you can determine the boxLabel and name for each checkbox (the attributes of record may be used as prefix, suffix...)
A couple of tips:
in the definition of panel items remove {} around checkboxes, like this:
items: [ checkboxes ]
second, make sure that the store is available when you are populating checkboxes.
I have a similar situation in my app where store is available after panel is rendered. Panel is dynamically populated with list of checkboxes like this:
panel.add(new Ext.form.CheckboxGroup({
columns: 1,
vertical: true,
items: checkItems
}));
panel.doLayout();
EDIT: another tip:
remove qutoes '' from this code:
{
boxLabel: 'record.id',
name: 'record.name'
}
or you will end up with all labels 'record.id'

Sencha Touch FormPanel With Store

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.