ExtJS - How to implement a container with its own isValid and hasInvalidField methods - forms

For example, let's say we have three phone number fields: mobile, home, business, that we want to encapsulate as a contact item.
The phone number fields can be blank or, if not, have their own validity checks, the contact item has its own validity check in that at least one number must be provided.
I'm thinking about doing something like this:
Ext.define('My.widgets.contact', {
// To make use of Ext.form.Labelable mixin
extend: 'Ext.form.fieldcontainer',
xtype: 'contact',
alias: 'widget.contact',
requires: [
'My.widgets.phone'
],
mixins: [
// To link in isValid and other methods
'Ext.form.field.Field'
],
items: [
{
xtype: 'phone',
fieldLabel: 'mobile'
},
{
xtype: 'phone',
fieldLabel: 'home'
},
{
xtype: 'phone',
fieldLabel: 'business'
}
],
isValid: function() {
let valid = false;
if (this.callParent(arguments)) {
for (const item in this.getItems()) {
if (item.getValue() != '') {
valid = true;
break;
}
}
}
return valid;
}
});
Is this the right way to do this?
The idea is to have the minimum extra fluff. For example, form panels have dockable, button, header and footer elements which aren't needed. Also, I've read about problems in ExtJS having multiple form items on a page, so want to avoid sequential or nested forms on a single page.
Another approach might be to extend Ext.container.Container with the Ext.form.Labelable and Ext.form.field.Field mixins. Would that work?

In ExtJs fieldcontainer have method query so you use this to check your Validation.
Query retrieves all descendant components which match the passed selector. Executes an Ext.ComponentQuery.query using this container as its root.
As you have used this.getItems() it will return all the items of fieldcontainer as whatever it contain. In this case you need to maintain condition to check getValue() only for fields.
Query will return only that component as you want to check.
I have created an Sencha Fiddle demo hope this will be help you to achieve your solution.
//Custom xtype for phone
Ext.define('Ext.form.field.Phone', {
extend: 'Ext.form.field.Text',
alias: 'widget.phone',
xtype: 'phone',
maskRe: /[\d\.]/,
regex: /^\d+(\.\d{1,2})?$/,
maxLength: 11,
enforceMaxLength: true
});
//Contact details
Ext.define('ContactForm', {
extend: 'Ext.form.FieldContainer',
alias: 'widget.contact',
xtype: 'contact',
flex: 1,
layout: 'vbox',
defaults: {
xtype: 'phone'
},
items: [{
fieldLabel: 'mobile'
}, {
fieldLabel: 'home'
}, {
fieldLabel: 'business'
}],
isValid: function () {
return this.query('phone[value=""]').length > 0;//you can also use like this { this.query('phone[value!=""]') };
}
});
//Panel this will contain contact
var panel = Ext.create('Ext.panel.Panel', {
itemId: 'myPanel',
bodyPadding: 5,
width: 300,
renderTo: Ext.getBody(),
title: 'Contact Details',
items: [{
xtype: 'contact'
}],
buttons: [{
text: 'Submit Details',
handler: function () {
var contactFrm = this.up('#myPanel').down('contact'), //you also use like this this.up('panel').down('contact')
title = 'Success',
msg = 'Good you have entered the contact details..!';
if (!contactFrm.isValid()) {
title = 'Error';
msg = 'Plese enter at least one contact detail..!'
}
Ext.Msg.alert(title, msg);
}
}]
});

Related

ExtJS 7.2 - Loading record into a form with chained comboboxes and forceSelection:true does not load all values

I have a form with two chained comboboxes. The first chained combobox dictates the values that appear in the second. I have forceSelection:true on the second combobox so that when a user changes the first combo, the second will be set blank because it no longer will be a valid option. The chained combos function as expected but when I load a record into this form using getForm().loadRecord(record) the value for the first combo is set properly but the second is not unless I set forceSelection:false.
The following fiddle should make things pretty clear: sencha fiddle
Clicking "Load Record" should load in Fruits/Apple, but only Fruits is shown. Clicking "Load Record" a second time achieves the desired result. If you comment out forceSelection: true it works as expected but then the chained combos don't function as desired. Is there anything I'm doing wrong here?
It is not so easy. What is happening when you are running form.loadRecord(rec).
you set the FoodGroup combobox
you set the FoodName combobox. BUT the value is not there, because your filter did not switch to appropriate food groups. That is why commenting force selection helps. (That is why commenting filter also help).
turned on the filter of food names. Store now have new values.
You are clicking the button second time. The first combobox value is the same, filters are not trigged (triggered?), you already have appropriate values in the second store and the value is selected.
How to fix:
The fix is ugly. You can listen on store 'refresh' (it means the filters are triggered) and then set the second value (or set the values again).
Ext.define('Fiddle.view.FormModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.fiddle-form-model',
stores: {
foodgroups: {
fields: ['name'],
data: [{
foodgroupname: 'Fruits'
}, {
foodgroupname: 'Vegetables'
}]
},
foods: {
fields: ['foodgroupname', 'foodname'],
filters: {
property: 'foodgroupname',
value: '{selectedFoodgroup.foodgroupname}'
},
data: [{
foodname: 'Apple',
foodgroupname: 'Fruits'
}, {
foodname: 'Banana',
foodgroupname: 'Fruits'
}, {
foodname: 'Lettuce',
foodgroupname: 'Vegetables'
}, {
foodname: 'Carrot',
foodgroupname: 'Vegetables'
}]
}
}
});
Ext.define('Fiddle.view.Form', {
extend: 'Ext.form.Panel',
xtype: 'fiddle-form',
viewModel: {
type: 'fiddle-form-model'
},
title: 'Combos',
items: [{
xtype: 'combo',
itemId: 'FoodGroup', // To access FoodGroup
displayField: 'foodgroupname',
bind: {
store: '{foodgroups}',
selection: '{selectedFoodgroup}'
},
valueField: 'foodgroupname',
forceSelection: true,
name: 'foodgroup',
fieldLabel: 'Food Group',
value: 'Vegetables'
}, {
xtype: 'combo',
itemId: 'FoodName', // To access FoodName
bind: {
store: '{foods}'
},
queryMode: 'local',
forceSelection: true, //COMMENTING THIS OUT ACHIEVES DESIRED LOAD RECORD BEHAVIOR
displayField: 'foodname',
valueField: 'foodname',
name: 'food',
fieldLabel: 'Food',
value: 'Carrot'
}],
buttons: [{
text: 'Load Record',
handler: function (btn) {
// OUR UGLY FIX
var form = btn.up('form'),
foodGroupComboBox = form.down('combobox#FoodGroup'),
foodNameComboBox = form.down('combobox#FoodName'),
record = Ext.create('Ext.data.Model', {
foodgroup: 'Fruits',
food: 'Apple'
});
foodNameComboBox.getStore().on('refresh', function (store) {
form.loadRecord(record);
}, this, {
single: true
})
form.loadRecord(record);
}
}]
});
Ext.application({
name: 'Fiddle',
launch: function () {
var form = new Fiddle.view.Form({
renderTo: document.body,
width: 600,
height: 400
});
}
});

extjs form panel set default value textfield

This seems like a trivial issue, but... I have a list of addresses in a panel to which I wish to add geolocation coordinates (and to display them on a map) that is rendered in a form panel, so that when I click on the address of interest in the panel an onTap is fired to do execute the onSelectGeolocation given below to open the form panel rendered in the ViewPort and to add any existing records to the associated form elements:
onSelectGeolocation: function(view, index, target, record, event) {
console.log('Selected a Geolocation from the list');
var geolocationForm = Ext.Viewport.down('geolocationEdit');
if(!geolocationForm){
geolocationForm = Ext.widget('geolocationEdit');
}
geolocationForm.setRecord(record);
geolocationForm.showBy(target);
}
The line that uses the setRecord method to write any existing records in my store to the form elements, however, is preventing the default values in my form panel below from getting written to the desired form elements. When I comment this out, all is good. Problem is that I need to grab those records that exist in my store, e.g., address, to display in my form. How can I do this AND write default values to my textfield elements in my form?
My form panel that is rendered as a ViewPort via the onTap is:
Ext.define('EvaluateIt.view.GeolocationEdit', {
extend: 'Ext.form.Panel',
alias : 'widget.geolocationEdit',
requires: [
'Ext.form.Panel',
'Ext.form.FieldSet',
'Ext.field.Number',
'Ext.field.DatePicker',
'Ext.field.Select',
'Ext.field.Hidden'
],
config: {
// We give it a left and top property to make it floating by default
left: 0,
top: 0,
// Make it modal so you can click the mask to hide the overlay
modal: true,
hideOnMaskTap: true,
// Set the width and height of the panel
width: 400,
height: 330,
scrollable: true,
layout: {
type: 'vbox'
},
defaults: {
margin: '0 0 5 0',
labelWidth: '40%',
labelWrap: true
},
items: [
{
xtype: 'datepickerfield',
destroyPickerOnHide: true,
name : 'datOfEvaluatione',
label: 'Date of evaluation',
value: new Date(),
picker: {
yearFrom: 1990
}
},
{
xtype: 'textfield',
name: 'address',
label: 'Address',
itemId: 'address'
},
{
xtype: 'textfield',
name: 'latitude',
label: 'Latitude',
itemId: 'latitude',
value: sessionStorage.latitude,
},
/* {
xtype: 'textfield',
name: 'longitude',
label: 'Longitude',
itemId: 'longitude',
value: sessionStorage.longitude
},
{
xtype: 'textfield',
name: 'accuracy',
label: 'Accuracy',
itemId: 'accuracy',
value: sessionStorage.accuracy
},*/
{
xtype: 'button',
itemId: 'save',
text: 'Save'
}
]
}
});
Behavior is as expected. I will use Ext.getCmp on the id's for each item instead.

How to get data from fieldset in Sencha Touch 2?

I hava a fieldset in Sencha Touch 2 as follows:
{
id:'contactForm',
xtype: 'fieldset',
title: 'Information',
items: [
{
xtype: 'textfield',
label: 'First Name',
placeHolder: 'Your First Name',
name:'firstName',
id:'firstName',
},
{
xtype: 'textfield',
label: 'Last Name',
placeHolder: 'Your Last Name',
name:'lastName'
},
{
xtype: 'emailfield',
label: 'Email',
placeHolder: 'email#example.com'
},
{
xtype: 'button',
height: 37,
style: 'margin-left:35%',
width: 100,
iconAlign: 'center',
text: 'Submit',
action:'ContactSubmit'
},
{
xtype: 'hiddenfield',
id: 'HNumberOfBedRoom',
value:'2'
},
{
xtype: 'hiddenfield',
id: 'HPetFriendlyId',
value:'2'
}
]
}
In my controller,
I have the following:
refs: {
contactForm: '#contactForm'
}
I can retrive the value by using
var frmItems=this.getContactForm().getItems();
console.log(frmItems.items[1]._value);
This works fine but i want to retrieve the values something like
frm.get('name/id of component')
is there any way to achieve this?
Use a Ext.form.Panel as your primary container.
example snippet
Ext.define('App.view.ContactForm',
{
extend : 'Ext.form.Panel',
xtype : 'contactform',
id : 'contactForm',
config : {
items : [
{
xtype : 'fieldset',
items : [
{
{
xtype: 'textfield',
label: 'First Name',
placeHolder: 'Your First Name',
name:'firstName',
},
]
}
});
in your controller
refs : { contactForm : '#contactForm' }
then in your function you can either do
this.getContactForm().getValues().firstName
(uses the name value of the field)
or
var vals = this.getContactForm().getValues();
vals.firstName;
Avoid using Ext.getCmp() or a flat Ext.get() at the top level if you absolutely can help it. If you're building custom controls you might have to make use of those, otherwise you're making things too hard on yourself.
You should be able to assign an id to your field, and then Ext.getCmp('-yourId-'); or Ext.get('-yourId-');
( http://docs.sencha.com/touch/2-0/#!/api/Ext.Component-cfg-id )
Dont struggle too much
first assign the id to that field and get the value using id thats it..
{
xtype: 'textfield',
id: 'username', // id
name: 'username',
placeHolder: '------UserName------',
},
Ext.getCmp('username').getValue(); // now get value using that id..
refs:[
{
ref:'contentForm',
// selector:'#contentForm'
contentForm:'#contentForm'
}
],
-
var form = Ext.getCmp('contentForm');
console.log(form.getValues());
Assign itemId: firstName to textfield
And in Controller, where you want to get the value, use this:
Ext.ComponentQuery.query('textfield[itemId=firstName]')[0].getData();

ExtJS 4 MVC Application: Form undefined error

I am new to ExtJS 4 and am trying to implement a simple application in MVC style. The documentation is really good and this is one of the topics covered in the Form package guide, but it doesn't seem to work in my case.
The app basically can create, edit and delete articles.The creation and editing are in pop-up windows.
The pop-up window contains a form with a text field and html-editor.
Please click on the link below,this is the error in Google Chrome Console when I click on the submit button in the 'window'
http://www.freeimagehosting.net/mjig7
Here is the code which I've written
Model:
Ext.define('AM.model.Article', {
extend: 'Ext.data.Model',
fields: ['name', 'data'],
proxy: {
type: 'rest',
url: 'users/data',
reader: {
type: 'json',
root: 'myJaxBean',
successProperty: 'success'
},
writer: {
type: 'json'
}
}
});
View:
Ext.define('AM.view.New', {
extend: 'Ext.window.Window',
alias : 'widget.new',
title : 'New Article',
autoShow: true,
fieldDefaults: {
labelAlign: 'top',
msgTarget: 'side'
},
layout: 'fit',
bodyStyle:'padding:5px 5px 0',
width: '70%',
height: '40%',
initComponent: function() {
this.items = [
{
xtype: 'form',
anchor: '99%',
items: [
{
xtype: 'textfield',
name : 'name',
fieldLabel: 'Article Name',
anchor: '99%'
},
{
xtype: 'htmleditor',
name : 'data',
fieldLabel: 'Article',
anchor: '99% -25'
}
],
buttons: [
{
text: 'Submit',
handler: function() {
var form = this.up('form').getForm(), // get the basic form
record = form.getRecord(); // get the underlying model instance
if (form.isValid()) { // make sure the form contains valid data before submitting
form.updateRecord(record); // update the record with the form data
record.save({ // save the record to the server
success: function(user) {
Ext.Msg.alert('Success', 'User saved successfully.')
},
failure: function(user) {
Ext.Msg.alert('Failure', 'Failed to save user.')
}
});
} else { // display error alert if the data is invalid
Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
}
}
},
{
text: 'Cancel',
scope: this,
handler: this.close
}
]
}
],
this.callParent(arguments);
}
});
and finally the code in my controller which makes the window visible
Controller:
.....
'viewport > panel > panel > tbar button[action=newarticle]' :{
click: this.newArticle
},
....
newArticle: function(button){
var view = Ext.widget('new');
},
Please point me in the right direction in case I am doing something wrong.
Thanks in advance.
Check the docs getRecord():
Returns the last Ext.data.Model instance that was loaded via
loadRecord
so it's clear that you haven't load any record, so you getRecord() returns undefined. And you are getting your error further.

ExtJS Table Layout not displaying fieldlabels or adding padding

I have a form which has a number of different fields and ultimately will become a dynamic formPanel.
I've opted for the table layout since it's easier to lay out the components but for some reason, the defaults settings are not applying and no field Labels are being displayed for any fields.
I've set out the configuration like:
SearchForm = Ext.extend(Ext.FormPanel, {
id: 'myForm'
,title: 'Search Form'
,frame:true
,waitMessage: 'Please wait.'
,labelWidth:80,
buttonAlign:'center'
,initComponent: function() {
var config = {
items: [{
layout:{
type:'table',
columns:5
},
defaults:{
//width:150,
bodyStyle:'padding:20px'
},
items:[{
xtype: 'label',
name: 'dateLabel',
cls: 'f',
text: "Required:"
},
{
xtype: 'datefield',
fieldLabel: "From Date",
value: yesterday,
width: 110,
id: 'date1'
},
{
xtype: 'datefield',
fieldLabel: "To Date",
id: 'date2',
width: 110,
value: yesterday
},
{
xtype: 'displayfield', value: ' ',
height:12,
colspan:2
}
],
buttons: [{
text: 'Submit',
id: "submitBtn",
handler: this.submit,
scope: this
},{
text: 'Reset',
id: "resetBtn",
handler: this.reset,
scope: this
}
]
}]};
// apply config
Ext.apply(this, config);
Ext.apply(this.initialConfig, config);
SearchForm.superclass.initComponent.apply(this, arguments);
}
});
The problem is because you're defining the layout to be table, hence ExtJS not rendering the labels of fields correctly.
In each column, wrap your fields with an Ext.Container and give the panel a layout of form. That will tell ExtJS to render the labels correctly.