Couldnt read and set Json data with extjs4 - javascript

I want to read json data in extjs here is my code below.
What i'm doing wrong ? I'm pretty new at Extjs.
I think i couldn't get the json value, or couldn't properly write it down on panel.
Thanks in advance.
Ext.require([ 'Ext.grid.*', 'Ext.data.*', 'Ext.dd.*' ]);
var urlGetName = '${ctx}/main/list';
Ext.define('DataObject', {
extend : 'Ext.data.Model',
fields : [ 'name' ]
});
var storeName = Ext.create('Ext.data.Store',{
model:'DataObject',
autoLoad : false,
proxy : {
type : 'ajax',
actionMethods: {
read: 'GET'
},
reader : {
type : 'json',
root: 'data',
},
api : {
read: urlGetName
}
},listeners: {
load: function(store, records) {
dataa =store.getAt(0).get('data');
}
}
});
Ext.onReady(function() {
var firstGridStore = Ext.create('Ext.data.Store', {
model : 'DataObject',
data : dataa
});
var columns = [ {
text : "Name",
flex : 1,
sortable : true,
dataIndex : 'name'
} ];
// declare the source Grid
var firstGrid = Ext.create('Ext.grid.Panel', {
multiSelect : true,
viewConfig : {
plugins : {
ptype : 'gridviewdragdrop',
dragGroup : 'firstGridDDGroup',
dropGroup : 'secondGridDDGroup'
},
listeners : {
drop : function(node, data, dropRec, dropPosition) {
var urlL = '${ctx}/main/list';
var param = data;
postDataAsParamsINN({param:param},urlL,function(resp){
var success=resp.success;
if(success){
Ext.MessageBox.alert('succes', 'bravaa');
}else{
Ext.MessageBox.alert('error','eroross' );
}
});
}
}
},
store : firstGridStore,
columns : columns,
stripeRows : true,
title : 'First Grid',
margins : '0 2 0 0'
});
});

You shouldn't use two stores to fill the one with the other. Delete the FirstGridStore and use the predefined remote store instead:
// Model
Ext.define('DataObject', {
extend : 'Ext.data.Model',
fields : [ 'name' ],
idProperty: 'name'
});
// Store
var storeName = Ext.create('Ext.data.Store',{
model:'DataObject',
autoLoad: true,
queryMode: local,
proxy: {
type: 'ajax',
actionMethods: {
read: 'GET'
},
reader: {
type : 'json',
root: 'data',
},
api: {
read: urlGetName
}
}
});
// Grid
var columns = [{
text : "Name",
flex : 1,
sortable : true,
dataIndex : 'name'
}];
// declare the source Grid
var firstGrid = Ext.create('Ext.grid.Panel', {
multiSelect : true,
viewConfig : {
plugins : {
ptype : 'gridviewdragdrop',
dragGroup : 'firstGridDDGroup',
dropGroup : 'secondGridDDGroup'
},
listeners : {
drop : function(node, data, dropRec, dropPosition) {
var urlL = '${ctx}/main/list';
var param = data;
postDataAsParamsINN({param:param},urlL,function(resp){
var success=resp.success;
if(success){
Ext.MessageBox.alert('succes', 'bravaa');
}else{
Ext.MessageBox.alert('error','eroross' );
}
});
}
}
},
store : storeName, // defined store
columns : columns,
stripeRows : true,
title : 'First Grid',
margins : '0 2 0 0'
});
});

Related

Ext js form validator validate with unique names

I have Ext Form :
Ext.define('Count.view.AddJListForm', {
extend : 'Ext.form.Panel',
controller : 'List',
xtype : 'add-list',
name : 'addListForm',
cls : 'addFormToolbar',
width : '100%',
height : '100%',
layout : 'hbox',
fullscreen : true,
scrollable : true,
items :
[
{
xtype : 'titlebar',
title : 'Add New Name',
docked : 'top',
},
{
xtype : 'formpanel',
fullscreen : true,
items :
[
{
xtype : 'hiddenfield',
name : 'id'
},
{
xtype : 'textfield',
name : 'ListName',
maxLength : 100,
label : 'List name',
labelAlign : 'top',
required : true
},
{
xtype : 'numberfield',
name : 'Count',
maxLength : 10,
label : 'Count',
labelAlign : 'top',
required : true
},
]
},
{
xtype : 'toolbar',
ui : 'plain',
docked : 'bottom',
items :
[
{
xtype : 'spacer'
},
{
xtype : 'button',
text : 'CANCEL',
name : 'closeAddListFormView',
},
{
xtype : 'button',
text : 'SAVE',
name : 'formSave',
}
]
}
]
});
Controller function :
In this function to get the form values and stored into Database:
Ext.define('Count.view.ListController', {
extend: 'Ext.app.ViewController',
alias: 'controller.JapaList',
control: {
'button[name=formSave]': {
tap : 'saveListData'
}
}
// File save function
saveListData : function(button, record)
{
var form = button.up('formpanel');
var values = form.getValues();
var BgImage = '';
var audioFile = '';
if(form.validate())
{
var ListName = values.ListName;
var Count = values.Count;
callBackSaveData var table = JapaCount.Db.tblJapaList;
toDbArray['ListName'] = ListName;
toDbArray['Count'] = Count;
Count.Db.dbInsertWithCallback(table,toDbArray, me.loadStore, me);
}
data stored on DB. But I need to validate ListName must be unique like a username. if there are any rerecords like the same name it should show an error. In this function were to check that validator or function? anyone have an idea please share
You can find record with ListName using method findRecord on instance of store.
let record = store.findRecord('ListName', ListName, 0, false, false, true);
if (!record) {
//do smth here if ListName not found
}

Feeding the dataview from JsonStore

Feeding the viewdata from the jsonstore
I want to use a JsonStore to feed my dataview. currently with the code below, the store is empty in the dataview. For testing, I wrote some code in the controller before opening the window and I can
see that the restful service retrieves data - getActivitiesToRescueCallback --> responce.responseText.
How can I feed my dataview with the Jsonstore?
In th ViewController:
getActivitiesToRescueCallback : function(options, success, response) {
if (success)
var result = Ext.decode(response.responseText); // Here I am getting data
},
getActivitiesToRescue : function() {
Ext.Ajax.request({
url : '/test/json_p',
params : {
"params[]" : "RESCUE",
"respName" : "",
"method" : "GetActivities",
"format" : "json"
},
callback : 'getActivitiesToRescueCallback',
scope : this
});
},
**View**
Ext.define('Tuv.test.rescue.RescueView', {
extend : 'Ext.window.Window',
alias : 'widget.rescueview',
alias : 'controller.rescueview',
bind : {
title : '{rescueTexts.masseRescue}'
},
height : 400,
width : 600,
constrainHeader : true,
maximizable : true,
closeAction : "hide",
layout : 'card',
activeItem : 0,
items : [ {
xtype : 'panel',
title : 'check activities',
layout : 'hbox',
border : false,
layoutConfig : {
align : 'stretch'
},
tbar : [ {
xtype : "button",
text : "copy",
handler : function() {},
scope : this
} ],
items : [ {
autoScroll : true,
width : 150,
items : {
xtype : 'dataview',
listeners : {
'afterrender' : function(comp) {
console.log('Test');
},
scope : this
},
store : new Ext.data.JsonStore({
url : '/test/json_p',
baseParams : {
"params[]" : "RESCUE",
respName : "",
method : "GetActivities",
format : "json"
},
idProperty : 'ACT_ID',
fields : [ 'ACT_ID', '_ACT_TYPE', '_FIRST_FORM', 'PRUEFSTATUS', '_DEBUG', '_SYNC_STATUS', '_SYNC_STATUS2', 'EQART', 'INVNR', 'ZTSPRID', 'ANLAGE_ZTSPRID', 'ZTSPRIDT' ]
}),
itemSelector : 'tr.dataRow',
tpl : new Ext.XTemplate('<table id="dataRescueTable">' + '<tpl for=".">', '<tr class="dataRow"><td>' + '<span <tpl if="STATUS==50">style="font-weight: bold;color:green"</tpl>>{name}</span></td></tr>', '</tpl>', '</table>')
}
} ],
bbar : {
buttonAlign : 'right',
items : [ {
text : "next",
handler : function(button) {
},
scope : this
} ]
}
} ]
});
To load the store I had to call store.load() or adding autoLoad: true as a config to the store.

How to get the value of a field in jtable?

I'm new to jtable and trying to figure out how can I get the selected value of a field (Types, dropdown); and based on this value, I need to make a call to a Java class and get the value for field 2 (Price, input type).
$(document).ready(function() {
var selectedValue = null;
$('#StudentTableContainer').jtable({
title : 'Students List',
actions : {
listAction : 'Controller?action=list',
createAction : 'Controller?action=create',
updateAction: function(postData) {
var values = [];
console.log("updating from custom function...");
return $.Deferred(function($dfd) {
$.ajax({
url: './Controller?action=update',
type: 'POST',
`enter code here` dataType: 'json',
data: postData,
success: function(data) {
$.each(data, function(entryindex, entry) {
values.push(entry['typeId']);
});
alert(values);
$dfd.resolve(data);
},
error: function() {
$dfd.reject();
}
});
});
},
deleteAction : 'Controller?action=delete'
},
fields : {
studentId : {
title : 'Student Id',
width : '30%',
key : true,
list : true,
edit : false,
create : true
},
name : {
title : 'Name',
width : '30%',
edit : true
},
emailId : {
title : 'Email',
width : '20%',
edit : true
},
typeId : {
title : 'types',
width : '20%',
edit : true,
listClass:'genderClass',
options: { 'S':'Select','D': 'Dynamic', 'F': 'Fixed', 'C':'Customize' }
},
priceId : {
title : 'Price',
width : '20%',
edit : true
}
}
});
});
Based on the selection of 'TypeId', I need to populate the value of the Price. I tried putting in some logic in the 'updateAction', but no luck.

how to add a record to a database java servlet from extjs

Hi I have my database in PostgreSQL, im using extjs for servlet. I want to add new records in grid to my database but i dont know how to connect that from servlet. Is anyone can help me? p.s: I should use doPost method but i dont know how can i do that with this. Here is my codes:
Ext.define('Book.Person', {
extend : 'Ext.data.Model',
fields : ['ID', 'Username']
});
var store = Ext.create('Ext.data.Store', {
model : 'Book.Person',
autoLoad : true,
autoSync : true,
proxy : {
type : 'ajax',
url : 'Sheldon.xml',
reader : {
type : 'xml',
record : 'Item',
totalProperty : 'total'
}
},
data : [{
title : '',
manufacturer : '',
author : ''
}]
});
var inputForm = Ext.create('Ext.form.Panel', {
activeRecord : null,
iconCls : 'icon-user',
frame : true,
title : 'User -- All fields are required',
defaultType : 'textfield',
bodyPadding : 2,
fieldDefaults : {
anchor : '100%',
labelAlign : 'right'
},
items : [{
fieldLabel : 'ID',
name : 'ID',
allowBlank : false
}, {
fieldLabel : 'Username',
name : 'Username',
allowBlank : false
}
],
dockedItems : [{
xtype : 'toolbar',
dock : 'bottom',
ui : 'footer',
items : ['->', {
iconCls : 'icon-user-add',
text : 'Create',
scope : this,
handler : function() {
createFunction();
}
}, {
iconCls : 'icon-reset',
text : 'Reset',
scope : this,
handler : function() {
inputForm.getForm().reset();
}
}]
}]
});
var windowToShow = Ext.create('Ext.window.Window', {
title : 'New Book',
height : 200,
width : 400,
layout : 'fit',
items : inputForm
});
var createFunction = function() {
var form = inputForm.getForm();
if (form.isValid()) {
var tt = form.findField('ID').getValue();
var mf = form.findField('Username').getValue();
// inputForm.fireEvent('create', inputForm, form.getValues());
var newBook = new Book.Person({
ID : tt,
Username : mf
});
/*
* windowToShow.show(); rec, edit = this.editing; edit.cancelEdit();
*/
/*
* this.store.insert(0, newBook); edit.startEditByPosition({ row : 0,
* column : 1});
*/
store.add(newBook);
store.load();
form.reset();
}
windowToShow.hide();
};
var resetFunction = function() {
inputForm.getForm().reset();
};
Ext.define('Book.Form', {
extend : 'Ext.form.Panel',
alias : 'widget.Bookform',
requires : ['Ext.form.field.Text'],
initComponent : function() {
// Ext.apply(this, this.bookform);
this.callParent();
},
setActiveRecord : function(record) {
this.activeRecord = record;
if (record) {
this.down('#save').enable();
this.getForm().loadRecord(record);
} else {
this.down('#save').disable();
this.getForm().reset();
}
}
/*
* onSave: function(){ var active = this.activeRecord, form =
* this.getForm();
*
* if (!active) { return; } if (form.isValid()) {
* form.updateRecord(active); this.onReset(); } },
*/
});
Ext.define('Book.Grid', {
extend : 'Ext.grid.Panel',
alias : 'widget.Bookgrid',
requires : ['Ext.grid.plugin.CellEditing', 'Ext.form.field.Text',
'Ext.toolbar.TextItem'],
initComponent : function() {
this.editing = Ext.create('Ext.grid.plugin.CellEditing');
Ext.apply(this, {
iconCls : 'icon-grid',
frame : true,
plugins : [this.editing],
dockedItems : [{
xtype : 'toolbar',
items : [{
iconCls : 'icon-add',
text : 'Add',
scope : this,
handler : this.onAddClick
}, {
iconCls : 'icon-delete',
text : 'Delete',
disabled : true,
itemId : 'delete',
scope : this,
handler : this.onDeleteClick
}]
}, {
weight : 2,
xtype : 'toolbar',
dock : 'bottom',
items : {
xtype : 'tbtext',
text : '<b>#Sebahat&Volkan</b>'
}
}, {
weight : 1,
xtype : 'toolbar',
dock : 'bottom',
ui : 'footer',
items : ['->', {
iconCls : 'icon-save',
text : 'Sync',
scope : this,
handler : this.onSync
}]
}],
columns : [{
text : '',
width : 40,
sortable : true,
resizable : false,
draggable : false,
hideable : false,
menuDisabled : true,
dataIndex : 'id',
renderer : function(value) {
return Ext.isNumber(value)
? value
: ' ';
}
}, {
header : 'ID',
width : 100,
sortable : true,
dataIndex : 'ID',
field : {
type : 'textfield'
}
}, {
header : 'Username',
width : 100,
sortable : true,
dataIndex : 'Username',
field : {
type : 'textfield'
}
}]
});
this.callParent();
this.getSelectionModel().on('selectionchange',
this.onSelectChange, this);
},
onSelectChange : function(selModel, selections) {
this.down('#delete').setDisabled(selections.length === 0);
},
onSync : function() {
this.store.sync();
},
onDeleteClick : function() {
var selection = this.getView().getSelectionModel()
.getSelection()[0];
if (selection) {
this.store.remove(selection);
}
},
onAddClick : function() {
windowToShow.show();
rec, edit = this.editing;
edit.cancelEdit();
this.store.insert(4, rec);
edit.startEditByPosition({
row : store.getTotalCount()+1,
column : 1
});
}
});
var rec = new Book.Person({
ID : '',
Username : ''
});
Ext.require(['Ext.data.*', 'Ext.tip.QuickTipManager', 'Ext.window.MessageBox']);
Ext.onReady(function() {
Ext.tip.QuickTipManager.init();
Ext.create('Ext.button.Button', {
margin : '0 0 20 20',
text : 'Reset sample database back to initial state',
tooltip : 'The sample database is stored in the session, including any changes you make. Click this button to reset the sample database to the initial state',
handler : function() {
Ext.getBody().mask('Resetting...');
Ext.Ajax.request({
url : 'app.php/example/reset',
callback : function(options, success, response) {
Ext.getBody().unmask();
var didReset = true, o;
if (success) {
try {
o = Ext.decode(response.responseText);
didReset = o.success === true;
} catch (e) {
didReset = false;
}
} else {
didReset = false;
}
if (didReset) {
store.load();
main.down('#form').setActiveRecord(null);
Ext.example.msg('Reset', 'Reset successful');
} else {
Ext.MessageBox.alert('Error',
'Unable to reset example database');
}
}
});
}
});
var main = Ext.create('Ext.container.Container', {
padding : '0 0 0 20',
width : 500,
height : Ext.themeName === 'neptune' ? 700 : 650,
renderTo : document.body,
layout : {
type : 'vbox',
align : 'stretch'
},
items : [{
// itemId: 'form',
xtype : 'Bookform',
manageHeight : false,
margin : '0 0 10 0',
listeners : {
create : function(form, data) {
store.insert(0, data);
}
}
}, {
// itemId: 'grid',
xtype : 'Bookgrid',
title : 'User List',
flex : 1,
store : store
/*
* listeners : { selectionchange :
* function(selModel, selected) {
* main.child('#form') .setActiveRecord(selected[0] ||
* null); } }
*/
}]
});
});
package net.davon;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Test_DB
*/
#WebServlet("/Sheldon.xml")
public class OrnekTest extends HttpServlet {
private static final long serialVersionUID = 1L;
private PrintWriter pw;
private Connection conn;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
String connectionString = "jdbc:postgresql://localhost:5432/Davon_User"; // +
// "databaseName=Davon_User;user=postgres;password=volkan";
String queryString = "select * from dvn_user";
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(connectionString, "postgres",
"volkan");
if (conn == null) {
System.out.println("CANNOT CONNECT DATABASE!");
System.exit(0);
}
statement = conn.createStatement();
resultSet = statement.executeQuery(queryString);
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\"?>\n").append("<Items>\n");
while (resultSet.next()) {
xml.append("\t<Item>\n");
String user_id = resultSet.getString("id");
String username = resultSet.getString("user_name");
xml.append("\t\t<ID>" + user_id + "</ID>\n");
xml.append("\t\t<Username>" + username + "</Username>\n");
xml.append("\t</Item>\n");
}
xml.append("</Items>\n");
response.getWriter().println(xml.toString());
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
}
}
There are a few things you should read up on.
First your extjs store proxy needs a writer the extjs docs have a useful guide to get you started
Then you would need to create the endpoint in your java Servlet class to handle the http requests that the store would emit on save.
This new endpoint would then call the method/service you are using to write to the database, passing the appropriate information required into the call.
Then your servlet method would resond with an appropriate http code so that the client can indicate success/failure as appropriate.

How to add itemtap

I have a list and I cant get items in the list to be clickable. I have onItemDisclosure and that should work but it is not. I would like the whole row to be clickable but I cant seem to get anything to work.
onItemDisclosure : function(record, btn, index) {
//window.location = 'http://www.google.com';
}
Here is my full source code
Ext.ns("Course", "Course.stores");
Course = new Ext.Application({
defaultTarget : 'viewport',
name : 'Course',
launch : function() {
console.log('begin');
this.viewport = new Ext.Panel({
fullscreen : true,
dockedItems : [ {
title : 'Course Catalog',
xtype : 'toolbar',
ui : 'light',
dock : 'top'
} ],
layout : 'fit',
scroll : 'vertical',
items : [ {
xtype : 'list',
itemTpl : '<span id="{letter}">{course}</span>',
store : Course.stores.Properties,
singleSelect : true,
itemSelector : 'span.id',
onItemDisclosure : function(record, btn, index) {
//window.location = 'http://www.google.com';
}
} ],
flex : 1
});
}
});
Ext.regModel('Properties', {
fields : [ {
name : 'letter',
type : 'string'
}, {
name : 'course',
type : 'string'
} ]
});
Course.stores.Properties = new Ext.data.Store({
model : 'Properties',
sorters: 'letter',
getGroupString : function(record) {
return record.get('letter')[0];
},
proxy : {
type : 'ajax',
url : '../lib/course_catalog.php',
reader : {
type : 'json',
}
},
autoLoad : true
});
Try something like this:
items : [ {
xtype : 'list',
itemTpl : '<span id="{letter}">{course}</span>',
store : Course.stores.Properties,
listeners: {
scope : this,
itemtap : function(foo, bar, etc) {
doSomething...
}
} ],
The reason that taps are not being handled is because you are overriding the itemSelector config:
itemSelector : 'span.id',
You should not do this, as Ext.List expects it to be a certain internally-set value in order to handle events on items properly. Simply removing this from your config should make it start working.

Categories

Resources