Extjs Catch pick event (combobox) - javascript

Using ExtJS 4.2.3. I have FORM with combobox field and some values inside on choose. I need to catch event when user pick 1 of the value in combobox.
Asking for help with syntax, as example to get ALERT on picking DATA3 value.
Name of combobox field - "document_type".
Example of code on ExtJS:
documentForm_window = Ext.create("Ext.window.Window", {
title: (document_GUID == null) ? "[Create]" : "[Edit]",
width: 500,
modal: true,
layout: "fit",
items: [{
xtype: "form",
frame: true,
waitMsgTarget: true,
listeners: {
afterrender: function (form) {
if (document_GUID != null) {
form.getForm().load({
url: Ext.state.Manager.get("MVC_url") + "/Document/Get",
method: "GET",
params: { document_GUID: document_GUID },
waitMsg: "[loading]",
timeout: 300,
failure: function (form, action) {
if (action.result) Ext.Msg.alert("[Error1]!", action.result.errorMessage);
else Ext.Msg.alert("[Error2]!", "[Error3]!");
}
});
}
}
},
defaults: {
anchor: "100%",
msgTarget: "side",
labelWidth: 145,
allowBlank: false
},
items: [{
xtype: "combo",
name: "document_type",
fieldLabel: "<b>[Type]<font color='Red'>*</font></b>",
displayField: "document_type_name",
valueField: "document_type",
queryMode: "local",
triggerAction: "all",
editable: false,
store: document_store
}, {
xtype: "textfield",
name: "contract_number",
fieldLabel: "<b>[TestData]</b>"
}],
formBind: true,
buttons: [{
text: (document_GUID == null) ? "[Create]" : "[Edit]",
handler: function () {
var action = (document_GUID == null) ? "Create" : "Edit";
var form = this.up("form").getForm();
if (form.isValid()) {
form.submit({
url: Ext.state.Manager.get("MVC_url") + "/Document/" + action,
params: { document_GUID: document_GUID, treasury_GUID: tree_value },
waitMsg: "[Loading...]",
success: function (form, action) {
documentForm_window.destroy();
OrderLines_store.load({
scope: this,
callback: function (records, operation, success) {
documents_List.query('*[itemId="DATA1_grid"]')[0].selModel.select(curr_position);
}
});
},
failure: function (form, action) {
if (action.result) Ext.Msg.alert("[Error1]!", action.result.msg);
else Ext.Msg.alert("[Error2]!", "[Error3]!");
}
});
}
}
}]
}]
}).show();
}
//store//
document_store = new Ext.data.ArrayStore({
fields: ["document_type", "document_type_name"],
data: [[0, "data1"], [1, "data2"], [2, "data3"]]
});
Sorry, part of code I add as screen cause of post error "It looks like your post is mostly code".

You have to add a listener for the select event to the combobox:
editable: false,
store: document_store,
listeners: {
select: function(combo, records) {
console.log(combo);
console.log(records);
if(!Ext.isArray(records)) records = [records];
Ext.each(records, function(record) {
if(record.get(combo.valueField)==3) {
Ext.Msg.alert('Value is 3 for' + record.get(combo.displayField));
}
});
}
}

Related

Assigning tpl with values for DOM manipulation in extjs

I have filter checkbox one after the other as below:
Now I want to change it to:
My approach to this problem is:
I am selecting the DOM and looping through it to select all the check boxes:
var x = $("table .x-form-type-checkbox")
$(x).each(function (index, value){
console.log(value.children)
});
OUTPUT:
I am creating the extjs combobox dropdown as:
Ext.application({
name: 'timefilter',
launch: function() {
Ext.widget({
xtype: 'combobox',
renderTo: Ext.get('newfilter1'),
fieldLabel: 'Time Frame',
labelAlign: 'right',
displayField: 'name',
editable: false,
multiSelect: false,
tpl: new Ext.XTemplate('<tpl for=".">', '<div class="x-boundlist-item">', '<input type="radio" />', '{name}', '</div>', '</tpl>'),
store: Ext.create('Ext.data.Store', {
fields: [{
type: 'string',
name: 'name'
}],
data: [{
"name": "Today"
}, {
"name": "This week"
}, {
"name": "This month"
}, {
"name": "Next week"
}, {
"name": "Next month"
}, {
"name": "All time"
}]
}),
queryMode: 'local',
listeners: {
select: function(combo, records) {
var node;
Ext.each(records, function(rec) {
node = combo.getPicker().getNode(rec);
Ext.get(node).down('input').dom.checked = true;
});
},
beforedeselect: function(combo, rec) {
var node = combo.getPicker().getNode(rec);
Ext.get(node).down('input').dom.checked = false;
}
}
});
}
});
OUTPUT:
Now I am tring to loop and map the value.children that contains each checkbox input to tpl as below:
var x = $("table .x-form-type-checkbox")
$(x).each(function(index, value) {
Ext.application({
name: 'timefilter',
launch: function() {
Ext.widget({
xtype: 'combobox',
renderTo: Ext.get('newfilter1'),
fieldLabel: 'Activity Status',
labelAlign: 'right',
displayField: 'name',
editable: false,
multiSelect: false,
tpl: value.innerHTML,
queryMode: 'local',
listeners: {
select: function(combo, records) {
var node;
Ext.each(records, function(rec) {
node = combo.getPicker().getNode(rec);
Ext.get(node).down('input').dom.checked = true;
});
},
beforedeselect: function(combo, rec) {
var node = combo.getPicker().getNode(rec);
Ext.get(node).down('input').dom.checked = false;
}
}
});
}
});
console.log(value.children)
});
But I am not getting expected OUT its:
Please let me know where I am doing wrong or is there a better approach.
You can implement this functionality using store.filter() method inside of combobox select event.
In this Fiddle, I have created a demo using same store.filter() method and select event of combo.
Node this is just an example you can change based on your requirement.
Code snippet:
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('ComboCheckbox', {
extend: 'Ext.form.field.ComboBox',
xtype: 'combocheckbox',
fieldLabel: 'Status',
tpl: new Ext.XTemplate('<tpl for=".">', '<div class="x-boundlist-item">', '<input type="checkbox" {checked} />', '{text}', '</div>', '</tpl>'),
store: Ext.create('Ext.data.Store', {
fields: ['text', 'value', {
name: 'checked',
defaultValue: ''
}],
data: [{
text: "All Statuses"
}, {
text: "Not Started"
}, {
text: "In Progress"
}, {
text: "Completed"
}, {
text: "Overdue"
}]
}),
queryMode: 'local',
listeners: {
select: function (combo, rec) {
rec.set('checked', 'checked');
},
beforedeselect: function (combo, rec) {
rec.set('checked', '');
}
}
});
Ext.define('GridStore', {
extend: 'Ext.data.Store',
alias: 'store.gridstore',
autoLoad: true,
fields: [{
name: 'issue',
mapping: 'issuetype',
convert: function (v) {
return v.toLowerCase();
}
}],
proxy: {
type: 'ajax',
url: 'task.json',
reader: {
type: 'json',
rootProperty: 'task'
}
}
});
Ext.create({
xtype: 'grid',
renderTo: Ext.getBody(),
title: 'Demo Grid',
store: {
type: 'gridstore'
},
height: 400,
width: '100%',
tbar: [{
xtype: 'combocheckbox',
listeners: {
select: function (combo, rec) {
var store = combo.up('grid').getStore();
store.clearFilter();
if (rec.get('text').toLowerCase() !== 'all statuses') {
store.filter('issue', rec.get('text').toLowerCase());
}
}
}
}],
columns: [{
text: 'Status',
width: 120,
dataIndex: 'issuetype',
renderer: function (value, metaData, record, rowIndex) {
let cls = 'notstarted';
switch (value.toLowerCase()) {
case 'in progress':
cls = 'inprocess';
break;
case 'completed':
cls = 'completed';
break;
case 'overdue':
cls = 'overdue';
break;
}
return `<span class="issuetype ${cls}">${value}</span>`;
}
}, {
text: 'Summary',
flex: 1,
dataIndex: 'summary'
}],
selModel: {
selType: 'checkboxmodel',
mode:'SIMPLE'
}
})
}
});

jqGrid inline-edit POST without editurl?

I am trying to find the information about editurl. Currently, i am working on the framework which does not permit editurl. The calls must go through javascript function which in-turn invokes the component on serverside.
Question is it possible to POST the data to javascript function instead of editurl?
I am experimenting with following:
$(document).ready(function () {
console.log(">>>1");
//--
action.setCallback(this, function(a) {
if (a.getState() === "SUCCESS") {
result = a.getReturnValue();
console.log(result);
//---=
var editActionOptions = {
keys: true,
url:null,
oneditfunc: function (rowid) {
console.log("row with rowid=" + rowid + " is editing.");
},
aftersavefunc: function (rowid, response, options) {
console.log("row with rowid=" + rowid + " is successfuly modified.");
}
};
//-------------------------------------------------------------------------------------------------------
$("#jqGrid").jqGrid({
editurl: 'clientArray',
datatype: "local",
data:result,
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
labe: 'ID',
name: 'empid',
width: 75
},
{
label : 'Name',
name: 'Name',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label: 'dob',
name: 'dob',
width: 100,
editable: true
},
{
label: 'dln',
name: 'dln',
width: 120,
editable: true
}
],
sortname: 'empid',
loadonce: true,
onSelectRow: editRow,
onSave:onSaveRow,
editParams: editActionOptions,
width: 780,
height: 400,
rowNum: 150,
pager: "#jqGridPager"
});
//------------------------------------------------------------------------------------------------------
} else if (a.getState() === "ERROR") {
$A.log("Errors", a.getError());
}
});
$A.enqueueAction(action);
var lastSelection;
function editRow(id) {
console.log(id);
if (id && id !== lastSelection) {
var grid = $("#jqGrid");
grid.jqGrid('restoreRow',lastSelection);
grid.jqGrid('editRow',id, {keys: true} );
lastSelection = id;
}
};
function onSaveRow(id){
console.log(id);
}

Kendo UI grid comboBox undefined on focus out?

I have working on Keno UI grid and I have added a comboBox as a column in the grid which also supports autocomplete feature. Apparently, comboBox is working fine but when I type half of world and focus out of the comboBox cell then it shows undefined. I have tried to handle it on combobox change event, but it is still showing undefined value? Below is my code for combobox and grid.
function productDropDownEditor(container, options) {
$('<input id="ProductDropDown" style="width:250px;" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoComboBox({
dataSource: dataSource,
autoBind: false,
dataTextField: 'ProductName',
dataValueField: 'ProductID',
filter: "contains",
suggest: true,
index: 3,
change: function (e) {
debugger;
var cmb = this;
// selectedIndex of -1 indicates custom value
if (cmb.selectedIndex < 0) {
cmb.value(0); // or set to the first item in combobox
}
},
close: function (e) {
debugger;
var cmb = this;
}
});
And here is following code for kendo grid.
$(function () {
$("#grid").kendoGrid({
columns: [
{
field: "Products", width: "250px",
editor: productDropDownEditor,
title: "Product",
template: "#=Products.ProductName#",
attributes: {
"class": "select2_single"
}
},
{ field: "PurchasePrice", width: "150px" },
{ field: "PurchaseQuantity", width: "150px" },
{ field: "SaleRate", title: "Sale Rate", width: "150px" },
{ field: "Amount", title: "Amount", width: "150px" },
{ command: "destroy", title: "Delete", width: "110px" },
],
editable: true, // enable editing
pageable: true,
navigatable: true,
sortable: true,
editable: "incell",
toolbar: ["create"], // specify toolbar commands
edit: function (e) {
//debugger;
//// var parentItem = parentGrid.dataSource.get(e.model.PurchaseID);
////e.model.set("ShipCountry", parentItem.Country);
//if (e.model.isNew()) {
// // set the value of the model property like this
// e.model.set("PropertyName", Value);
// // for setting all fields, you can loop on
// // the grid columns names and set the field
//}
},
//editable: "inline",
dataSource: {
serverPaging: true,
requestStart: function () {
kendo.ui.progress($("#loading"), true);
},
requestEnd: function () {
kendo.ui.progress($("#loading"), false);
},
serverFiltering: true,
serverSorting: true,
batch: true,
pageSize: 3,
schema: {
data: "data",
total: "Total",
model: { // define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
PurchaseID: { editable: false, nullable: true },
PurchasePrice: { nullable: true },
PurchaseQuantity: { validation: { required: true, min: 1 } },
SaleRate: { validation: { required: true, min: 1 } },
Amount: { type: "number", editable: false },
Products: {
nullable: false,
validation: { required: true},
defaultValue: {ProductID:1, ProductName:"Googo" },
//from: "Products.ProductName",
parse: function (data) {
debugger;
if (data == null) {
data = { ProductID: 1};
}
return data;
},
type: "object"
}
}
}
},
batch: true, // enable batch editing - changes will be saved when the user clicks the "Save changes" button
change: function (e) {
debugger;
if (e.action === "itemchange" && e.field !== "Amount") {
var model = e.items[0],
type = model.Type,
currentValue = model.PurchasePrice * model.PurchaseQuantity;//formulas[type](model);
if (currentValue !== model.Amount) {
model.Amount = currentValue;
$("#grid").find("tr[data-uid='" + model.uid + "'] td:eq(4)").text(currentValue);
}
//if (e.field == "Products") {
// $("#grid").find("tr[data-uid='" + model.uid + "'] td:eq(0)").text(model.Products);
//}
}
},
transport: {
read: {
url: "#Url.Action("Read", "Purchase")", //specify the URL which should return the records. This is the Read method of the HomeController.
contentType: "application/json",
type: "POST", //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
},
parameterMap: function (data, operation) {
debugger;
if (operation != "read") {
// post the products so the ASP.NET DefaultModelBinder will understand them:
// data.models[0].ProductID = data.models[0].Product.ProductID;
var result = {};
// data.models[0].ProductID = $("#ProductDropDown").val();
for (var i = 0; i < data.models.length; i++) {
var purchase = data.models[i];
for (var member in purchase) {
result["purchaseDetail[" + i + "]." + member] = purchase[member];
}
}
return result;
} else {
var purchaseID = $("#hdnPurchaseId").val();
//output = '{ purchaseID: ' + purchaseID + '}';
data.purchaseID = purchaseID; // Got value from MVC view model.
return JSON.stringify(data)
}
}
}
},
}).data("kendoGrid");

Combo box do not select Value from drop down

I am using ExtJs to create a combobox.
Here is my code:
Ext.define('Form.FormTypeDialog', {
extend : 'Ext.Window',
id: 'formTypeDialog',
formId: null,
callbackFunction : null,
modal: true,
statics : {
show : function(formId, callback) {
Ext.create(Form.FormTypeDialog", {
formId : formId,
callbackFunction : callback
}).show();
}
},
constructor : function(config) {
var me = this;
Ext.apply(this, {
buttons : [
{
text:"#{msgs.form_create_dialog_button_cancel}",
cls : 'secondaryBtn',
handler: function() {
me.close();
}
},
{
text:"#{msgs.form_create_dialog_button_next}",
handler: function() {
// Get selected form type
}
}
]
});
this.callParent(arguments);
},
initComponent:function() {
this.setTitle("#{msgs.form_create_dialog_title}");
this.setHeight(175);
this.setWidth(327);
var formTypeStore = Mystore.Store.createRestStore({
url : getRelativeUrl('/rest/form/formTypes'),
root: 'objects',
fields: ['name','value']
});
this.form = new Ext.form.Panel({
style:'padding:15px;background-color:#fff' ,
border:false,
bodyBorder:false,
items:[
new Ext.form.Label({
text: "#{msgs.form_create_dialog_select_type_label}",
margin: "25 10 25 5"
}),
new Ext.form.ComboBox({
id: 'createformTypeCombo',
margin: "8 10 25 5",
allowBlank: false,
forceSelection: true,
editable:false,
store: formTypeStore,
valueField: 'value',
displayField: 'name',
width: 260,
emptyText: '#{msgs.form_create_dialog_select_type}'
})
]
});
this.items = [
this.form
];
this.callParent(arguments);
}
});
I am creating this window on a xhtml page on a button click using :
Form.FormTypeDialog.show(null, showFormWindowCallBack);
It works fine and combo box is displayed and I can select value.
But if I open and close it 4 times, then in next show it shows the values but It do not allow me to select the last two value. I can only select first value.
Please suggest.
Note: I have tried copying and executing this code in forms of other pages of my application. But behavior is same in all cases.
This combobox is on a Ext.Window.
EDIT:
JSON RESPONSE FROM Rest:
{"attributes":null,"complete":true,"count":3,"errors":null,"failure":false,"metaData":null,"objects":[{"name":"Application
Provisioning Policy Form","value":"Application"},{"name":"Role
Provisioning Policy Form","value":"Role"},{"name":"Workflow
Form","value":"Workflow"}],"requestID":null,"retry":false,"retryWait":0,"status":"success","success":true,"warnings":null}
I have re-created this code, I had some errors showing in Firefox using your code directly so I've changed some things.
Running the code below and calling Ext.create("Form.FormTypeDialog", {}).show(); in the console window, then closing the window and repeating does not replicate this issue. Could you try using the code I have and see if you still have the same problem.
Ext.application({
name: 'HelloExt',
launch: function () {
Ext.define('Form.FormTypeDialog', {
extend: 'Ext.Window',
id: 'formTypeDialog',
formId: null,
callbackFunction: null,
modal: true,
constructor: function (config) {
var me = this;
Ext.apply(this, {
buttons: [
{
text: "#{msgs.form_create_dialog_button_cancel}",
cls: 'secondaryBtn',
handler: function () {
me.close();
}
},
{
text: "#{msgs.form_create_dialog_button_next}",
handler: function () {
// Get selected form type
}
}
]
});
this.callParent(arguments);
},
initComponent: function () {
this.setTitle("#{msgs.form_create_dialog_title}");
this.setHeight(175);
this.setWidth(327);
var myData = [
["Application Provisioning Policy Form", "Application"],
["Role Provisioning Policy Form", "Role"],
["Workflow Form", "Workflow"],
];
var formTypeStore = Ext.create("Ext.data.ArrayStore", {
fields: [
'name',
'value'
],
data: myData,
storeId: "myStore"
});
this.form = Ext.create("Ext.form.Panel", {
style: 'padding:15px;background-color:#fff',
border: false,
bodyBorder: false,
items: [
Ext.create("Ext.form.Label", {
text: "#{msgs.form_create_dialog_select_type_label}",
margin: "25 10 25 5"
}),
Ext.create("Ext.form.ComboBox", {
id: 'createformTypeCombo',
margin: "8 10 25 5",
allowBlank: false,
forceSelection: true,
editable: false,
store: formTypeStore,
valueField: 'value',
displayField: 'name',
width: 260,
emptyText: '#{msgs.form_create_dialog_select_type}'
})
]
});
this.items = [
this.form
];
this.callParent(arguments);
}
});
Ext.create('Ext.Button', {
text: 'Click me',
renderTo: Ext.getBody(),
handler: function() {
Ext.create("Form.FormTypeDialog", {}).show();
}
});
}
});
You can also play around with this code using / forking from this Fiddle
It is not clear what your problem is.
I use remote combo follows:
Ext.define('ComboRemote', {
extend: 'Ext.form.ComboBox',
xtype: 'ComboRemote',
emptyText: 'empty',
width: 75,
displayField: 'name',
valueField: 'id',
store: {
model: 'ComboModel',
proxy: {
type: 'rest',
url: '/serv/Res',
extraParams: {
query: ''
},
reader: {
root: "result", type: 'json'
}
},
autoLoad: true,
},
queryMode: 'remote',
pageSize: false,
lastQuery: '',
minChars: 0});
Ext.define('ComboModel', {
extend: 'Ext.data.Model',
fields: [
'id',
'name'
]});
I hope to help
Try these possible solutions
1. Make AutoLoad property for store as true.
2. Add delay of some ms

Extjs form submit

I searched hours and hours for a solution but can't find one. I want to submit something to a php api function. it looks like this:
/*global Ext:false */
Ext.onReady(function ()
{
var i = 0;
var form = Ext.create('Ext.form.Panel', {
title: 'base_entity_id',
bodyPadding: 5,
width: 350,
defaultType: 'textfield',
items: [{
fieldLabel: 'base_entity_id',
name: 'first',
allowBlank: false
}],
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();
}
}],
})
var tabs = Ext.create('Ext.tab.Panel',
{
renderTo: 'tabs',
id: 'tabs',
itemId: 'tabs',
fullscreen: true,
renderTo: document.body,
items:
[
{
title: 'Home',
margin: 40,
items: [form],
},
{
title: 'Results',
itemId: 'Results',
listeners:
{
activate: function (tab)
{
if(i == 0)
{
var panel = Ext.create('Ext.tab.Panel',
{
id: 'tabs2',
width: window,
height: window,
renderTo: document.body,
items:
[
{
title: '1',
itemId: '1',
closable: true,
html: '10329u9iwsfoiahfahfosaofhasohflhsalkfhoihoi3riwoifhoiashfkhasofhosahfsahfahsfosafoisaiohfaoishfoihsaoifasoifsaifhsaoifasoihfoiahsfoihasfoihasoifoisfoihsafoihasfoiasoihasfoihaoifhaoihfoiahfoiaoaffoafoiafsaoafohaoh'
},
{
title: '2',
itemId: '2',
closable: true,
}
]
})
tab.add(panel);
tab.doLayout();
i = 1;
}
}
}
}]
})
});
But when i'm submitting i get no response, can someone help me with this? I dont know what the next steps are...
I have a simple application done with Ext JS/PHP and the following code worked for me:
myFormPanel.getForm().submit({
clientValidation: true,
url: 'updateConsignment.php',
params: {
id: myFormPanel.getForm().getValues().first
},
success: function(form, action) {
Ext.Msg.alert('Success', action.result.msg);
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert('Failure', action.result.msg);
}
}
});
Source:
http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.form.BasicForm-method-submit
Well, you have set no URL for your form, and the submit button doesn't have the submit method so I'm not really sure how this was supposed to work.
You will need to add the url config to your form:
Ext.create('Ext.form.Panel', {
title: 'base_entity_id',
method: 'POST',
url: 'myBackEnd.php' // Or whatever destination you are using for your backend.
...
});
Also, I saw that you are using formbind: true and later checking if the form was valid, one action renders the other unnecessary, so choose one, there is no need for both!
Add this your button handler:
form.submit({
params: {
id: form.getForm().getValues().first
},
success: function(form, action) {
Ext.Msg.alert('Success', 'Your form was submitted successfully');
},
failure: function(form, action) {
Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
}
});
Then you should check for $_POST['id']
For more information on form methods and configurations check this doc: http://docs.sencha.com/extjs/5.0/apidocs/#!/api/Ext.form.Basic

Categories

Resources