ExtJS - Form submit - javascript

I've got code:
win = desktop.createWindow({
id: 'admin-win',
title: 'Add administration users',
width: 740,
height: 480,
iconCls: 'icon-grid',
animCollapse: false,
constrainHeader: true,
xtype: 'form',
bodyPadding: 15,
url: 'save-form.php',
items: [{
xtype: 'textfield',
fieldLabel: 'Field',
name: 'theField'
}],
buttons: [{
text: 'Submit',
handler: function () {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
success: function (form, action) {
Ext.Msg.alert('Success', action.result.message);
},
failure: function (form, action) {
Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
}
});
}
}
}]
});
And buttons doesn't work. It creates error - this.up('form') is undefined. How can I call getForm() in such code like that?
UPDATE:
Thanks for really quick reply!
I modified your code for my needs, this is it, and it works with Desktop Example:
win = desktop.createWindow({
id: 'admin-win',
title: 'Add administration users',
width: 740,
iconCls: 'icon-grid',
animCollapse: false,
constrainHeader: true,
items: [{
xtype: 'form',
bodyPadding: 15,
url: 'save-form.php',
items: [{
xtype: 'textfield',
fieldLabel: 'Field',
name: 'theField'
}],
buttons: [{
text: 'Submit',
handler: function () {
var form = this.up('form').getForm();
if (form.isValid()) {
this.up().up().submit({
success: function (form, action) {
Ext.Msg.alert('Success', action.result.message);
},
failure: function (form, action) {
Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
}
});
}
}
}]
}]
});

As I already said, it seems that you have problems with your code. You are passing Ext.form.Panel options to a Ext.window.Window (I assuming this because the name of the method that you are calling). I'm writing an example with a window for you. Just a moment.
It is ready. Take a look:
Ext.create('Ext.window.Window', {
title: 'This is a Window with a Form',
height: 200,
width: 400,
layout: 'fit',
items: [{ // the form is an item of the window
id: 'admin-win',
title: 'Add administration users',
width: 740,
height: 480,
iconCls: 'icon-grid',
animCollapse: false,
constrainHeader: true,
xtype: 'form',
bodyPadding: 15,
url: 'save-form.php',
items: [{
xtype: 'textfield',
fieldLabel: 'Field',
name: 'theField',
allowBlank: false
}],
buttons: [{
text: 'Submit',
handler: function() {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
success: function(form, action) {
Ext.Msg.alert('Success', action.result.message);
},
failure: function(form, action) {
Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
}
});
} else {
Ext.Msg.alert( "Error!", "Your form is invalid!" );
}
}
}]
}]
}).show();
jsFiddle: http://jsfiddle.net/davidbuzatto/vWmmD/

Related

console.log not working in JS file

I am trying to debug a JavaScript file within a larger project and for some reason, the console.log() is not outputting anything to my console view. I have tried other functions such as alert() as well but they have also given me the same results.
Here is my code:
Ext.define('chefRoleSetupFormPanel', {
extend: 'Ext.form.Panel',
id: 'chefRoleSetupFormPanel',
title: 'Role Information',
url: 'chefCreateRole.php',
bodyPadding: 10,
items: [{
xtype: 'textfield',
name: 'roleName',
fieldLabel: 'Name',
allowBlank: false,
anchor: '100%'
}, {
xtype: 'textareafield',
grow: true,
name: 'roleDescription',
fieldLabel: 'Description',
anchor: "100% 75%"
}],
buttons: [{
text: 'Reset',
handler: function() {
this.up('form').getForm().reset();
}
}, {
text: 'Submit',
formBind: true, //only enabled once the form is valid
disabled: true,
handler: function() {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
success: function(form, action) {
var roleSetupForm = Ext.getCmp('chefRoleSetupFormPanel');
roleSetupForm = roleSetupForm.getForm();
var roleName = roleSetupForm.findField('roleName')['value'];
var roleDescription = roleSetupForm('roleDescription')['value'];
var chefRequiredCookbooksGrid = Ext.getCmp('chefRequiredCookbooksGrid');
var runList = chefRequiredCookbooksGrid.getStore().getRange();
console.log(runList);
roleSetupForm.submit({
params: {
roleName: roleName,
roleDescription: roleDescription,
runList: JSON.stringify(runList)
}
})
},
failure: function(form, action) {
}
});
}
}
}]
});
Any ideas as to why this may be happening?
Thanks
Try to log in the failure. You might have an error you are not catching.
console.log() is great but I would suggest to use Ext.log(...).
This is just a best practice I was suggested to follow.
Usage:
Ext.log({level:'debug'}, 'Message Here');

How would I put part of a Handler function into a controller in Sencha

I have a handler function that creates a Ext.window.Window, with fields to enter data, I need o move this part of the code to a controller function, and separate it from the main ajax request, this is for code reuse purposes.
var win = Ext.create('Ext.window.Window', {
title: 'New Client',
id: 'addClientWindow',
width: 500,
height: 300,
items: [{
xtype: 'form',
bodyPadding: 10,
items: [{
xtype: 'fieldset',
title: 'My Fields',
items: [{
xtype: 'textfield',
anchor: '100%',
id: 'nameTextField',
fieldLabel: 'Name',
labelWidth: 140
}, {
xtype: 'textfield',
anchor: '100%',
id: 'physicalTextField',
fieldLabel: 'Physical Address',
labelWidth: 140
}, {
xtype: 'textfield',
anchor: '100%',
id: 'postalTextField',
fieldLabel: 'Postal Address',
labelWidth: 140
}]
}],
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
items: [{
xtype: 'button',
id: 'cancelClientBtn',
text: 'Cancel',
listeners: {
click: function(c) {
Ext.getCmp('addClientWindow').close();
}
}
}, {
xtype: 'tbspacer',
flex: 1
}, {
xtype: 'button',
id: 'saveClientBtn',
text: 'Save',
listeners: {
click: function(c) {
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'Company',
method: 'add',
data: Ext.encode({
name: Ext.getCmp('nameTextField').getValue(),
physical: Ext.getCmp('physicalTextField').getValue(),
postal: Ext.getCmp('postalTextField').getValue()
})
},
success: function(response) {
Ext.MessageBox.alert('Status', 'Record has been updated.');
Ext.getStore('CompanyStore').reload();
Ext.getCmp('addClientWindow').close();
},
failure: function() {
Ext.MessageBox.alert('Status', 'Failed to update record.');
}
});
}
}
}]
}]
}]
});
win.show();
The button opens this window and performs this ajax request, I just need the two separated from one another. Any help appreciated.
You can define your window in a separated file and give it an alias:
Ext.define('MyApp.view.MyWindow', {
extend: 'Ext.window.Window',
alias: 'widget.addclient',
...
click: function(){
var data = Ext.encode({
name: Ext.getCmp('nameTextField').getValue(),
physical: Ext.getCmp('physicalTextField').getValue(),
postal: Ext.getCmp('postalTextField').getValue()
});
// I assume here "this" links to the window component,
// if not, adjust accordingly
if(this.mycallback){
this.mycallback(data);
}
}
});
Then you can call it from other controllers and provide a callback:
Ext.define('MyApp.view.MyController', {
extend: 'Ext.app.ViewController',
requires: 'MyApp.view.MyWindow',
openWindow: function(){
var win = Ext.widget('addclient');
win.mycallback = this.onAddClientCallback.bind(this);
win.show();
},
onAddClientCallback: function(data){
console.log("data from window", data);
}
});

How to POST a grid within a form in ExtJS

I have a form that has comboboxes, tagfields, date pickers, etc., and a grid. Each of these elements has a different store. The user is going to make selections from the comboboxes, etc,. and enter values into the grid. Then the values from the grid and other form elements are all sent on a POST to the server. I know how to POST the data from the comboboxes, tagfields, and date pickers. However, I don't know how to send the data in the grid with the form. Here is the form view:
Ext.define('ExtTestApp.view.main.List', {
extend: 'Ext.form.Panel',
xtype: 'cell-editing',
frame: true,
autoScroll: true,
title: 'Record Event',
bodyPadding: 5,
requires: [
'Ext.selection.CellModel',
'ExtTestApp.store.Personnel'
],
layout: 'column',
initComponent: function(){
this.cellEditing = new Ext.grid.plugin.CellEditing({
clicksToEdit: 1
});
Ext.apply(this, {
//width: 550,
fieldDefaults: {
labelAlign: 'left',
labelWidth: 90,
anchor: '100%',
msgTarget: 'side'
},
items: [{
xtype: 'fieldset',
//width: 400,
title: 'Event Information',
//height: 460,
//defaultType: 'textfield',
layout: 'anchor',
defaults: {
anchor: '100%'
},
items: [{
xtype: 'fieldcontainer',
fieldLabel: 'Event',
layout: 'hbox',
defaults: {
hideLabel: 'true'
},
items: [{
xtype: 'combobox',
name: 'eventTypeId',
width: 300,
//flex: 1,
store: {
type: 'events'
},
valueField: 'eventTypeId',
// Template for the dropdown menu.
// Note the use of the "x-list-plain" and "x-boundlist-item" class,
// this is required to make the items selectable.
allowBlank: false
}
]
},
{
xtype: 'container',
layout: 'hbox',
margin: '0 0 5 0',
items: [
{
xtype: 'datefield',
fieldLabel: 'Date',
format: 'Y-m-d',
name: 'startDate',
//msgTarget: 'under', //location of error message, default is tooltip
invalidText: '"{0}" is not a valid date. "{1}" would be a valid date.',
//flex: 1,
emptyText: 'Start',
allowBlank: false
},
{
xtype: 'datefield',
format: 'Y-m-d',
name: 'endDate',
//msgTarget: 'under', //location of error message
invalidText: '"{0}" is not a valid date. "{1}" would be a valid date.',
//flex: 1,
margin: '0 0 0 6',
emptyText: 'End',
allowBlank: false
}
]
}]
},
{
xtype: 'fieldset',
//height: 460,
title: 'Platform Information',
//defaultType: 'textfield',
layout: 'anchor',
defaults: {
anchor: '100%'
},
items: [
{
xtype: 'fieldcontainer',
layout: 'hbox',
fieldLabel: 'Platform',
//combineErrors: true,
defaults: {
hideLabel: 'true'
},
items: [
{
xtype: 'combobox',
name: 'platformId',
store: {
type: 'platforms'
},
valueField: 'platformId',
allowBlank: false
}
]
}
]
},
{
xtype: 'fieldcontainer',
layout: 'hbox',
fieldLabel: 'Software Type(s)',
//combineErrors: true,
defaults: {
hideLabel: 'true'
},
items: [
{
xtype: 'tagfield',
width: 400,
//height: 50,
fieldLabel: 'Software Type(s)',
name: 'softwareTypeIds',
store: {
type: 'softwareTypes'
},
labelTpl: '{softwareName} - {manufacturer}',
valueField: 'softwareTypeId',
allowBlank: false
}
]
},
{
xtype: 'gridpanel',
layout: 'anchor',
defaults: {
anchor: '100%'
},
width: 1300,
//columnWidth: 0.78,
//title: 'Metrics',
plugins: [this.cellEditing],
title: 'Personnel',
store: {
type: 'personnel'
},
columns: [
{ text: 'Name', dataIndex: 'name', editor: 'textfield' },
{ text: 'Email', dataIndex: 'email', flex: 1 },
{ text: 'Phone', dataIndex: 'phone', flex: 1 }
]
}
],
buttons: [
{
text: 'Save Event',
handler: function() {
var form = this.up('form'); // get the form panel
// if (form.isValid()) { // make sure the form contains valid data before submitting
Ext.Ajax.request({
url: 'api/events/create',
method:'POST',
headers: { 'Content-Type': 'application/json' },
params : Ext.JSON.encode(form.getValues()),
success: function(form, action) {
Ext.Msg.alert('Success', action.result);
},
failure: function(form, action) {
//console.log(form.getForm().getValues());
Ext.Msg.alert('Submission failed', 'Please make sure you selected an item for each required field.', action.result);
}
});
// } else { // display error alert if the data is invalid
// Ext.Msg.alert('Submit Failed', 'Please make sure you have made selections for each required field.')
// }
}
}
]
});
this.callParent();
}
});
var grid = Ext.ComponentQuery.query('grid')[0];
Here is the store for the grid:
Ext.define('ExtTestApp.store.Personnel', {
extend: 'Ext.data.Store',
alias: 'store.personnel',
fields: [
'name', 'email', 'phone'
],
data: { items: [
{ name: 'Jean Luc', email: "jeanluc.picard#enterprise.com", phone: "555-111-1111" },
{ name: 'Worf', email: "worf.moghsson#enterprise.com", phone: "555-222-2222" },
{ name: 'Deanna', email: "deanna.troi#enterprise.com", phone: "555-333-3333" },
{ name: 'Data', email: "mr.data#enterprise.com", phone: "555-444-4444" }
]},
autoLoad: true,
proxy: {
type: 'memory',
api: {
update: 'api/update'
},
reader: {
type: 'json',
rootProperty: 'items'
},
writer: {
type: 'json',
writeAllFields: true,
rootProperty: 'items'
}
}
});
Ideally, you would need to create a custom "grid field" so that the grid data is picked up on form submit like any other field.
You can also use this workaround: in the "Save Event" button handler, dig out the grid store and fish data out of it:
var gridData = [];
form.down('gridpanel').store.each(function(r) {
gridData.push(r.getData());
});
Then get the rest of the form data and put the grid data into it:
var formData = form.getValues();
formData.gridData = gridData;
Finally, include it all in your AJAX call:
params: Ext.JSON.encode(formData)

button.form() is undefined

getting error at that button.up('form').getForm().reset(); is undefined....
functions of Submit - is send user details to server
cancel button - it sgould reset form.
// this is code of controller for login form..which consist of two event s for submit button & for cancel
Ext.define('Packt.controller.Login',
{
extend: 'Ext.app.Controller',
views: [
'Login'
],
init: function(application)
{
this.control({
"button#submit": {
click: this.onButtonClickSubmit
},
"button#cancel": {
click: this.onButtonClickCancel
}
});
},
// implementation of action to be executed when events happnes
onButtonClickSubmit: function(button, e, options)
{
get login form referance
var formPanel = button.up('form'),
login = button.up('login'),
user = formPanel.down('textfield[name=user]').getValue(),
pass = formPanel.down('textfield[name=password]').getValue(),
if (formPanel.getForm().isValid())
{
encryptting password
pass = Packt.util.MD5.encode(pass);
sending user details to server
Ext.Ajax.request({
url: 'php/login.php',
params: {
user: user,
password: pass
}
});
}
},
onButtonClickCancel: function(button, e, options)
{
button.up('form').getForm().reset();
}
});
code of view for form :
Ext.define('Packt.view.Login', {
extend: 'Ext.window.Window',
alias: 'widget.login',
autoShow: true,
height: 170,
width: 360,
layout: {
type: 'fit'
},
iconCls: '.key',
title: 'Login',
closeAction: 'hide',
closable: false ,
items: [
{
type: 'form',
frame: false,
bodyPadding: 15,
defaults: {
xtype: 'textfield',
anchor: '100%',
labelWidth: 60 ,
allowBlank: false,
vtype: 'alphanum',
minLength: 3,
msgTarget: 'side'
},
items: [
{
name: 'user',
fieldLabel: 'user',
maxLength :25
},
{
inputType: 'password',
name: 'password',
fieldLabel: 'Password',
maxLength :15,
enableKeyEvents: true,
id: 'password'
}
]
}
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'bottom',
items: [
{
xtype: 'tbfill'
},
{
xtype: 'button',
itemId: 'cancel',
iconCls: 'cancel',
text: 'Cancel'
},
{
xtype: 'button',
itemId: 'submit',
formBind: true,
iconCls: 'key-go',
text: 'Submit'
}
]
}
]
});
this is code of app.js that is main
Ext.application({
// namespace fr project
name: 'Packt',
/*requires: [
'Packt.view.Login'
],
views: [
'Login'
],
*/
controllers: [
'Login'
],
init: function()
{
splashscreen = Ext.getBody().mask('Loading application','splashscreen');
splashscreen.addCls('splashscreen');
Ext.DomHelper.insertFirst(Ext.query('.x-mask-msg')[0], {cls: 'x-splash-icon' });
splashscreen.next().fadeOut({
duration: 1000,
remove:true,
listeners: {
afteranimate: function(el, startTime, eOpts )
{
Ext.widget('login');
}
}
});
}
});

Bind Ext form data into GridPanel in ExtJS

I had created a demo page using ExtJS for the first time.
I have created the .JS file as below.
Ext.require([
//'Ext.form.*',
//'Ext.layout.container.Column',
//'Ext.tab.Panel'
'*'
]);
Ext.onReady(function() {
Ext.QuickTips.init();
var bd = Ext.getBody();
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
var simple = Ext.widget({
xtype: 'form',
layout: 'form',
collapsible: true,
id: 'userForm',
frame: true,
title: 'User Details',
bodyPadding: '5 5 0',
align: 'center',
width: 350,
buttonAlign: 'center',
fieldDefaults: {
msgTarget: 'side',
labelWidth: 75
},
defaultType: 'textfield',
items: [{
id: 'txtName',
fieldLabel: 'Name',
name: 'name',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'dDOJ',
fieldLabel: 'Date Of Joining',
name: 'doj',
xtype: 'datefield',
format: 'd/m/Y',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'txtAge',
fieldLabel: 'Age',
name: 'age',
xtype: 'numberfield',
minValue: 0,
maxValue: 100,
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'chkActive',
xtype: 'checkbox',
boxLabel: 'Active',
name: 'cb'
}],
buttons: [{
text: 'ADD',
listeners: {
click: {
fn: function() {
debugger;
if (Ext.getCmp('txtName').getValue() == "" || Ext.getCmp('dDOJ').getValue() == "" || Ext.getCmp('txtAge').getValue() == "") {
alert("Please Enter All Required Details!");
return false;
}
var reply = confirm("Are You Sure You Want To Save?")
if (reply != false) {
fnShowGrid();
}
}
}
}
}]
});
simple.render(document.body);
});
function fnShowGrid() {
debugger;
var vName = Ext.getCmp('txtName').getValue();
var vDOJ = Ext.Date.format(Ext.getCmp('dDOJ').getValue(), 'd/m/Y');
var vAge = Ext.getCmp('txtAge').getValue();
var vIsActive = "InActive";
if (Ext.getCmp('chkActive').getValue() == true) {
vIsActive = "Active";
}
var store = Ext.create('Ext.data.ArrayStore', {
storeId: 'myStore',
idIndex: 0,
fields: [
{ name: 'name' },
{ name: 'doj' },
{ name: 'age' },
{ name: 'active' }
],
//data: { name: vName, doj: vDOJ, age: vAge, active: vIsActive}
data: [[vName, vDOJ, vAge, vIsActive]]
});
store.load({
params: {
start: 1,
limit: 3
}
});
Ext.create('Ext.grid.Panel', {
title: 'User Details',
store: store,
columns: [
{
header: 'Name',
width: 160,
sortable: true,
dataIndex: 'name'
},
{
header: 'Date Of Join',
width: 75,
sortable: true,
dataIndex: 'doj'
},
{
header: 'Age',
width: 75,
sortable: true,
dataIndex: 'age'
},
{
header: 'Active',
width: 75,
sortable: true,
dataIndex: 'active'
}],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
//detailsGrid.render(document.body);
}
The gridPanel is being displayed. But each time add a new data its creating a new grid!
I want to display GridPanel only once including all before added data.
Here's fiddle: http://jsfiddle.net/pratikhsoni/wc9mD/1/
Here is the working example based on your fiddle!
Ext.require([
'*'
]);
store = Ext.create('Ext.data.ArrayStore', {
storeId: 'myStore',
idIndex: 0,
fields: [
{ name: 'name' },
{ name: 'doj' },
{ name: 'age' },
{ name: 'active' }
],
//data: { name: vName, doj: vDOJ, age: vAge, active: vIsActive}
});
Ext.onReady(function() {
Ext.QuickTips.init();
var bd = Ext.getBody();
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
var simple = Ext.widget({
xtype: 'form',
layout: 'form',
collapsible: true,
id: 'userForm',
frame: true,
title: 'User Details',
bodyPadding: '5 5 0',
align: 'center',
width: 350,
buttonAlign: 'center',
fieldDefaults: {
msgTarget: 'side',
labelWidth: 75
},
defaultType: 'textfield',
items: [{
id: 'txtName',
fieldLabel: 'Name',
name: 'name',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'dDOJ',
fieldLabel: 'Date Of Joining',
name: 'doj',
xtype: 'datefield',
format: 'd/m/Y',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'txtAge',
fieldLabel: 'Age',
name: 'age',
xtype: 'numberfield',
minValue: 0,
maxValue: 100,
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'chkActive',
xtype: 'checkbox',
boxLabel: 'Active',
name: 'cb'
}],
buttons: [{
text: 'ADD',
listeners: {
click: {
fn: function() {
debugger;
if (Ext.getCmp('txtName').getValue() == "" || Ext.getCmp('dDOJ').getValue() == "" || Ext.getCmp('txtAge').getValue() == "") {
alert("Please Enter All Required Details!");
return false;
}
var reply = confirm("Are You Sure You Want To Save?")
if (reply != false) {
fnShowGrid();
}
}
}
}
}]
});
simple.render(document.body);
});
function fnShowGrid() {
debugger;
var vName = Ext.getCmp('txtName').getValue();
var vDOJ = Ext.Date.format(Ext.getCmp('dDOJ').getValue(), 'd/m/Y');
var vAge = Ext.getCmp('txtAge').getValue();
var vIsActive = "InActive";
if (Ext.getCmp('chkActive').getValue() == true) {
vIsActive = "Active";
}
if (!Ext.getCmp('sample-grid')) {
store.add({
name: vName,
doj: vDOJ,
age: vAge,
active: vIsActive
});
Ext.create('Ext.grid.Panel', {
title: 'User Details',
store: store,
id: 'sample-grid',
columns: [
{
header: 'Name',
width: 160,
sortable: true,
dataIndex: 'name'
},
{
header: 'Date Of Join',
width: 75,
sortable: true,
dataIndex: 'doj'
},
{
header: 'Age',
width: 75,
sortable: true,
dataIndex: 'age'
},
{
header: 'Active',
width: 75,
sortable: true,
dataIndex: 'active'
}
],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
} else {
store.add({
name: vName,
doj: vDOJ,
age: vAge,
active: vIsActive
});
}
}
First of All.
Its very good to see you getting touch with EXT js. Mistake's i will like to highlight in your code.
1. if (reply != false) {
fnShowGrid();
}
In this you are calling your grid to be created which is being called why you are creating a new grid . you just have to update the store.
Approach: You must call it only once check if it exist and if yes then update the store like this.
if (reply != false) {
if(!Ext.getCmp('hello')) {
fnShowGrid();
} else {
var store=Ext.getCmp('hello').getStore();
store.add ({
name: 'sadad',
doj:'25/01/2015',
age:'26',
active:'false'
});
store.reload();
}
}
So in all you have to update the store add the new records. I have hardcoded right now you can get the values as you have got when creating it.
Please find Updated fiddle.
Fiddle

Categories