Send data from extjs popup window to spring controller - spring

I have an extjs popup window with form panel inside and I wanted to know how can I send datas in the form panel to my spring controller ?
var formPanel = {
xtype : 'form',
height : 125,
autoScroll : true,
id : 'formpanel',
defaultType : 'field',
frame : true,
items : [
{
fieldLabel : 'Name'
},
{
fieldLabel : 'Age'
}
]
};
function openIFrame() {
Ext.create('Ext.window.Window', {
title : 'Import your devices',
width: 500,
height: 500,
layout: 'fit',
items: [formPanel]
}).show();
}

Get the form by some selector from controller and then call getForm().getValues() method. Method returns an object made by form fields and its values.
Then you can use send this object to the server using Ext.Ajax.request method (docs: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.Ajax-method-request)

You can send request to server with params via this code:
Ext.Ajax.request({
url: '/requestUrl',
params: {
param1: data1,
param2: data2
},
method: 'POST',
success: function(response) {
//do something...
}
})
Also you need to add this code to some listener on your popup, for example in onButtonClick
function openIFrame() {
Ext.create('Ext.window.Window', {
title : 'Import your devices',
width: 500,
height: 500,
layout: 'fit',
items: [formPanel],
buttons: [
{
text: 'Submit',
handler: function () {
//function which listed above
}
}
]
}).show();
And to handle request at BE you need create controller like this:
#ResponseBody
#RequestMapping(value = "/requestUrl")
public void handler(#RequestParam ("param1") String param1,
#RequestParam ("param2") String param2) throws Exception {
//do something with data
}

Related

Validating an email textfield using a button extjs

I have a textfield which takes email as its value by using
vtype : 'email'
I am trying to validate this textfield using a button, wherein, when clicked, it should alert me if the textfield has email input or not. Based on my code, the validation always gives me false no matter the input. how should I do this? Here is my code:
Ext.create('Ext.form.Panel', {
title: 'Contact Info',
width: 300,
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
id: 'emailField',
fieldLabel: 'EmailAddress',
vtype: 'email',
allowBlank: false,
validator: function (val) {
var fieldValidation = Ext.form.field.VTypes.email(val);
if (fieldValidation === true) {
this.setFieldStyle("background-color : #BCF5A9");
} else {
this.setFieldStyle("background-color : #F6CECE");
}
},
}, {
xtype: 'button',
text: 'select',
handler: function () {
alert(Ext.getCmp('emailField').isValid());
}
}]
});
P.S: I understand that the problem is with the validator: function (val) I have used in the textfield. But I need it to change the color of the textfield based on the input. Is there any other way of doing this?
EDIT:
I got it working by changing the validator : function to a change : function
listeners: {
'change': function (thisField) {
if (thisField.isValid()) {
this.setFieldStyle("background-color : #BCF5A9");
} else {
this.setFieldStyle("background-color : #F6CECE");
}
}
}
Upon further investigation, your custom validator is messing up validation coming with default vtype:'email'. Remove the validator function and validation will work correctly.
If you just want to change the color of the textfield based on the validated input, all you need to do is override the css class (.x-form-invalid-field-default) which is added every time the textfield is invalid.
Hope it helps.
I got it working by changing the validator : function to a change : function
listeners: {
'change': function (thisField) {
if (thisField.isValid()) {
this.setFieldStyle("background-color : #BCF5A9");
} else {
this.setFieldStyle("background-color : #F6CECE");
}
}
}

How to validate model using collection.create()

I'm trying to make a form validated before submit. For this, I defined a create method within the View which is responsible to call collection.create() method to create the model.
Here is a sample code:
app.ContactCreateView = Backbone.View.extend({
template: _.template($('#tpl-create-contact').html()),
initialize: function () {
this.router = new app.ContactsRouter();
this.contacts = new app.ContactsCollection();
},
events: {
'click #btn-create' : 'create',
'click #btn-cancel' : 'cancel',
},
render: function() {
this.$el.html(this.template());
return this;
},
getAttributes: function () {
console.log('getAttributes()');
var attr = {
name: $('#input-name').val().trim(),
category: $('#input-category').val().trim(),
phone: $('#input-phone').val().trim(),
email: $('#input-email').val().trim(),
};
console.log('attr : ' + JSON.stringify(attr))
return attr;
},
create: function () {
console.log('create()');
// Create the Model
this.contacts.create(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
//this.hideErrors();
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
//this.showErrors(errors);
}
});
},
The 'success' callback is well called but I don't manage to get the 'error' callback called once the model.validate() method is failing.
Here is the model with the validate method :
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
// Default attributes for the Contact
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
And the collection:
app.ContactsCollection = Backbone.Collection.extend({
model: app.ContactModel,
url: '/user',
//localStorage: new Backbone.LocalStorage('contacts-backbone'),
getById: function (iId) {
return this.where({id: iId});
},
getByName: function (iName) {
return this.where({name: iName});
}
});
I really don't understand what I'm doing wrong... If somebody can help me :-(
Regards,
when the validation is failed error callback is not called , it trigger an "invalid" event on model, and set the validationError property on the model.
method 1(listening on model):
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
//your error catched here
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
method 2 (check whether validationError property is set in your view):
create: function () {
console.log('create()');
// Create the Model
this.contactModel.save(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
this.contacts.add(this.contactModel);
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
}
});
//your error catched here
if (this.contactModel.validationError) {
alert(this.contactModel.validationError)
}
},
So I played around with this for a while in an app I'm currently working on and found it kind of irritating and never really got it to work.
Instead I went the jQuery validation route and found it very helpful for doing validations. I highly recommend checking it out! It has a lot of built in validations you can just use and you can also override the error messages that display (also built in).
Example - I wanted a number only text field (excuse the coffeescript) :).
jQuery.validator.setDefaults(
debug: true,
success: "valid")
if #model.get('number_only')
$('#number_only').validate({
debug: true,
rules: {
"number[entry]": {
required: true,
range: [#model.get('min_number'), #model.get('max_number')],
number: true
}
},
messages: {
"number[entry]": {
required: "This field is required. Please enter a numeric value.",
min: jQuery.validator.format("Please enter a value greater than or equal to {0}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
number: "Please enter a numeric value"
range: jQuery.validator.format("Please enter a value between {0} and {1}.")
}
}
})
If that doesn't really get what you want (seemed like you maybe are more interested in displaying the errors your server sends back whereas this route would more be validating the content before saving your model) let me know and I can see if I can figure out your problem.

JSON encoded improperly when using KendoGrid POST payload

I am binding to a JSON data source, then rebinding after the user initiates a search based on filters on the page. The JSON payload is encoded improperly and nothing I've tried thus far seems to explain why.
If I could just add the correct JSON to the HTTP post, everything would work normally, and does with the $.ajax method listed first.
Using $.ajax call (works)
$.ajax(
{
url: '/api/DataProcessing',
type: "Post",
contentType: "application/json; charset=utf-8",
data: '' + JSON.stringify(searchObject),
dataType: 'json',
success: function (result) {
$(".kendoDataProcessing").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoDataProcessing").data("kendoGrid").dataSource.read();
$(".kendoDataProcessing").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
However, when I update the kendogrid data source in what I expect to send an equivalent payload, it encodes the JSON in an unexpected way (see below the code block for before and after HTTP requests captured in Fiddler. (encodes improperly)
$(".kendoDataProcessing").kendoGrid({
dataSource: {
transport: {
read: {
url: '/api/DataProcessing',
type: 'Post',
contentType: 'application/json; charset=utf-8',
data: '' + JSON.stringify(searchObject),
dataType: 'json',
}
},
pageSize: 25
},
height: 620,
sortable: true,
pageable: true,
filterable: true,
columns: [
{
field: "Client",
title: "Client Name",
width: 120
}, {
field: "Study",
title: "Study",
width: 100
}, {
field: "DataLogId",
title: "Batch Description",
width: 120
}, {
field: "Indicator",
title: "Indicator",
width: 100
}, {
field: "UserName",
title: "Username",
width: 110
}, {
field: "AssessmentPoint",
title: "Assessment Point",
width: 130
}, {
field: "DateStamp",
title: "Date Stamp",
width: 180
}]
});
**Expected JSON encoding (HTTP call created using $.ajax method) **
{"Client":"Choose a client...","Study":"Choose a study...","UserName":"Choose a user...","from":"","To":"","AssessmentPoint":"Choose an AP...","Indicator":"Choose an indicator...","DataLogId":""}
**Actual JSON encoding (HTTP call created using Kendogrid data source update and rebind **
0=%7B&1=%22&2=C&3=l&4=i&5=e&6=n&7=t&8=%22&9=%3A&10=%22&11=C&12=h&13=o&14=o&15=s&16=e&17=+&18=a&19=+&20=c&21=l&22=i&23=e&24=n&25=t&26=.&27=.&28=.&29=%22&30=%2C&31=%22&32=S&33=t&34=u&35=d&36=y&37=%22&38=%3A&39=%22&40=C&41=h&42=o&43=o&44=s&45=e&46=+&47=a&48=+&49=s&50=t&51=u&52=d&53=y&54=.&55=.&56=.&57=%22&58=%2C&59=%22&60=U&61=s&62=e&63=r&64=N&65=a&66=m&67 ... (continues)
It looks like it is making the json string into an array of sorts. So I tried with just a test string of "floof" and it encoded to "0=f&1=l&2=o&3=o&4=f"
Controller method called:
public HttpResponseMessage Post([FromBody]DataProcessingSearch dataProcessingSearch)
{
// dataProcessingSearch var is null (was passed oddly encoded)
}
Additional Details (search object)
var searchObject = new Object();
searchObject.Client = $('#ClientList').val();
searchObject.Study = $('#StudyList').val();
searchObject.Site = $('#SiteList').val();
searchObject.UserName = $('#UserList').val();
searchObject.from = $('#beginSearch').val();
searchObject.To = $('#endSearch').val();
searchObject.AssessmentPoint = $('#AssessmentPointList').val();
searchObject.Indicator = $('#IndicatorList').val();
searchObject.DataLogId = $('#DataLogIdText').val();
demo: http://so.devilmaycode.it/json-encoded-improperly-when-using-kendogrid-post-payload
function searchObject(){
return {
Client : $('#ClientList').val(),
Study : $('#StudyList').val(),
Site : $('#SiteList').val(),
UserName : $('#UserList').val(),
from : $('#beginSearch').val(),
To : $('#endSearch').val(),
AssessmentPoint : $('#AssessmentPointList').val(),
Indicator : $('#IndicatorList').val(),
DataLogId : $('#DataLogIdText').val()
}
}
// i have putted the dataSource outside just for best show the piece of code...
var dataSource = new kendo.data.DataSource({
transport: {
read : {
// optional you can pass via url
// the custom parameters using var query = $.param(searchObject())
// converting object or array into query sring
// url: "/api/DataProcessing" + "?" + query,
url: "/api/DataProcessing",
dataType: "json",
// no need to use stringify here... kendo will take care of it.
// also there is a built-in function kendo.stringify() to use where needed.
data: searchObject
},
//optional if you want to modify something before send custom data...
/*parameterMap: function (data, action) {
if(action === "read") {
// do something with the data example add another parameter
// return $.extend({ foo : bar }, data);
return data;
}
}*/
}
});
$(".kendoDataProcessing").kendoGrid({
dataSource: dataSource,
...
});
comments are there just for better explanation you can completely remove it if don't need it. the code is fully working as is anyway.
doc: http://docs.telerik.com/kendo-ui/api/wrappers/php/Kendo/Data/DataSource
What May be the wrong perception:-
1.The Json() method accepts C# objects and serializes them into JSON
strings. In our case we want to return an array of JSON objects; to
do that all you do is pass a list of objects into Json().
public JsonResult GetBooks()
{
return Json(_dataContext.Books);
}
Can you identify what is wrong with the above method? If you didn't already know, the above method will fail at runtime with a "circular reference" exception.
Note: try to return Json, HttpResponse may serialize the data in such a way that it is not acceptable by Kendo Grid. this has happened with me in my project.
Try this Approach:-
Now lets create instances of them in a JsonResult action method.
public JsonResult GetFooBar()
{
var foo = new Foo();
foo.Message = "I am Foo";
foo.Bar = new Bar();
foo.Bar.Message = "I am Bar";
return Json(foo);
}
This action method would return the following JSON:
{
"Message" : "I am Foo",
"Bar" : {
"Message" : "I am Bar"
}
}
In this example we got exactly what we expected to get. While serializing foo it also went into the Bar property and serialized that object as well. However, let's mix it up a bit and add a new property to Bar.
I remember working with a kendo grid in the past. Solution back then was returning jsonp. (needed to work crossdomain not sure if it does in your case)
Suggestion change you controller method to return sjonp by decorating you method with a JsonpFilterAttribute. Something like so:
[JsonpFilter]
public JsonResult DoTheThing(string data, string moreData)
{
return new JsonResult
{
Data = FetchSomeData(data, moreData)
};
}
Then in de Kendo grid try use http://demos.telerik.com/kendo-ui/datasource/remote-data-binding.
For the Jsonpfilter attribute first look at here or else here.

sencha touch 2 id of view returning undefined

I have declared a view as shown below:
Ext.define('App.view.About', {
extend: 'Ext.Panel',
id: 'about',
xtype: 'aboutpanel', // used as reference from Main.js
config: {
title: 'About',
iconCls: 'icon-file',
scrollable: true,
styleHtmlContent: true,
items: {
docked: 'top',
xtype: 'titlebar',
title: 'About'
},
html: 'This page will contain basic information.'
}
});
I have also declared a controller as shown below:
Ext.define('App.controller.About', {
extend : 'Ext.app.Controller',
config : {
refs : {
about : '#about'
}
},
init : function () {
var me = this;
me.getAbout().setHtml('Hello'); // just for testing
}
});
However in the Developer Tools of Chrome am getting an error "Cannot call method 'setHtml' of undefined". Therefore as I understand it, the controller is not getting the view by id. Am using Sencha Touch 2.2.1.
Any help please? Thanks in advance,
You won't have access to the refs in the init() function of the controller. To get similar functionality, you could do your code as an initialize listener on the about panel:
Ext.define('App.controller.About', {
extend : 'Ext.app.Controller',
config : {
refs : {
about : '#about'
},
control: {
about: {
initialize: 'initAbout'
}
}
},
initAbout: function () {
var me = this;
me.getAbout().setHtml('Hello'); // works now!
}
});
As a side note, it is redundant to give your components an id in in the definition. You should reserve id for when you're instantiating components (and you should probably use itemId instead of id in that case anyway).

Passing model to controller from view in JTable MVC using jQuery

I am trying to pass entire model from View to Controller using jTable.
Here is the code for view
I am having a filter criteria based on which the table will be loaded.
Say DropdownList of ModelId and ModelName, on selection,followed by click of a button, the function below executes.
<script type="text/javascript">
function GetModels() {
var model = {
ModelId:$("#ModelId").val(),
ModelName:$("#ModelName").val(),
ModelAge:$("#ModelAge").val()
};
$(document).ready(function () {
$('#PersonTableContainer').jtable({
title: 'Table of Models',
actions: {
listAction: '/Controller/ActionName'
},
fields: {
ModelName: {
title: 'ModelName',
width: '30%',
list: false
},
ModelId: {
title: 'ModelId',
width: '30%',
key: true,
create: false,
edit: false
}
ModelAge: {
title: 'ModelAge',
width: '30%',
create: false,
edit: false
}
}
});
$('#PersonTableContainer').jtable('load', { ModelName: model });
});
}
Here is the code for the controller.
public JsonResult GetAppropriateModel( ModelName ModelName)
{
try
{
FillAppropriateModel(ModelName);
}
catch(Exception e)
{
return Json(new { Result = "Error", Message=e.Message });
}
}
I am kind of new in AJAX and I am facing an issue where in the returned model is null, However if I cause normal submit-button postaction, then the model is retained.. I googled and got examples where they pass discrete elements and not entire model.
--Edit --
This is the link I referred.
http://www.jtable.org/Demo/Filtering
Kindly help.
Thanks.
For some reason the MVC handler doesn't decode model objects properly when jTable sends them in. I've found that setting the contentType in your jTable ajaxSettings fixes this. In your jTable definitions, add this:
ajaxSettings: {
contentType: "application/json; charset=utf-8"
}
Then you have to stringify your parameter when you send it in:
$('#PersonTableContainer').jtable('load', JSON.stringify({ ModelName: model }));

Resources