3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 * @class Ext.form.Field
9 * @extends Ext.BoxComponent
10 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
13 * @param {Object} config Configuration options
16 Ext.form.Field = Ext.extend(Ext.BoxComponent, {
18 * <p>The label Element associated with this Field. <b>Only available after this Field has been rendered by a
19 * {@link form Ext.layout.FormLayout} layout manager.</b></p>
24 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password, file (defaults
25 * to 'text'). The types 'file' and 'password' must be used to render those field types currently -- there are
26 * no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText}
27 * is not supported and should be avoided.
30 * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered,
31 * not those which are built via applyTo (defaults to undefined).
34 * @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
37 * @cfg {String} name The field's HTML name attribute (defaults to '').
38 * <b>Note</b>: this property must be set if this field is to be automatically included with
39 * {@link Ext.form.BasicForm#submit form submit()}.
42 * @cfg {String} cls A custom CSS class to apply to the field's underlying element (defaults to '').
46 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to 'x-form-invalid')
48 invalidClass : 'x-form-invalid',
50 * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided
51 * (defaults to 'The value in this field is invalid')
53 invalidText : 'The value in this field is invalid',
55 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to 'x-form-focus')
57 focusClass : 'x-form-focus',
59 * @cfg {Boolean} preventMark
60 * <tt>true</tt> to disable {@link #markInvalid marking the field invalid}.
61 * Defaults to <tt>false</tt>.
64 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
65 automatic validation (defaults to 'keyup').
67 validationEvent : 'keyup',
69 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
71 validateOnBlur : true,
73 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation
74 * is initiated (defaults to 250)
76 validationDelay : 250,
78 * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
79 * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
80 * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
81 * <pre><code>{tag: 'input', type: 'text', size: '20', autocomplete: 'off'}</code></pre>
83 defaultAutoCreate : {tag: 'input', type: 'text', size: '20', autocomplete: 'off'},
85 * @cfg {String} fieldClass The default CSS class for the field (defaults to 'x-form-field')
87 fieldClass : 'x-form-field',
89 * @cfg {String} msgTarget <p>The location where the message text set through {@link #markInvalid} should display.
90 * Must be one of the following values:</p>
91 * <div class="mdetail-params"><ul>
92 * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
93 * <div class="subdesc"><b>{@link Ext.QuickTips#init Ext.QuickTips.init} must have been called for this setting to work.</b></div</li>
94 * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
95 * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
96 * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
97 * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
102 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field
103 * (defaults to 'normal').
107 * @cfg {Boolean} readOnly <tt>true</tt> to mark the field as readOnly in HTML
108 * (defaults to <tt>false</tt>).
109 * <br><p><b>Note</b>: this only sets the element's readOnly DOM attribute.
110 * Setting <code>readOnly=true</code>, for example, will not disable triggering a
111 * ComboBox or DateField; it gives you the option of forcing the user to choose
112 * via the trigger without typing in the text box. To hide the trigger use
113 * <code>{@link Ext.form.TriggerField#hideTrigger hideTrigger}</code>.</p>
117 * @cfg {Boolean} disabled True to disable the field (defaults to false).
118 * <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>,
119 * disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p>
123 * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
124 * Defaults to <tt>true</tt>.
138 initComponent : function(){
139 Ext.form.Field.superclass.initComponent.call(this);
143 * Fires when this field receives input focus.
144 * @param {Ext.form.Field} this
149 * Fires when this field loses input focus.
150 * @param {Ext.form.Field} this
155 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.
156 * To handle other keys see {@link Ext.Panel#keys} or {@link Ext.KeyMap}.
157 * You can check {@link Ext.EventObject#getKey} to determine which key was pressed.
158 * For example: <pre><code>
159 var form = new Ext.form.FormPanel({
162 fieldLabel: 'Field 1',
166 fieldLabel: 'Field 2',
169 specialkey: function(field, e){
170 // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
171 // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
172 if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
173 var form = field.ownerCt.getForm();
183 * @param {Ext.form.Field} this
184 * @param {Ext.EventObject} e The event object
189 * Fires just before the field blurs if the field value has changed.
190 * @param {Ext.form.Field} this
191 * @param {Mixed} newValue The new value
192 * @param {Mixed} oldValue The original value
197 * Fires after the field has been marked as invalid.
198 * @param {Ext.form.Field} this
199 * @param {String} msg The validation message
204 * Fires after the field has been validated with no errors.
205 * @param {Ext.form.Field} this
212 * Returns the {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
213 * attribute of the field if available.
214 * @return {String} name The field {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
216 getName : function(){
217 return this.rendered && this.el.dom.name ? this.el.dom.name : this.name || this.id || '';
221 onRender : function(ct, position){
223 var cfg = this.getAutoCreate();
226 cfg.name = this.name || this.id;
229 cfg.type = this.inputType;
233 Ext.form.Field.superclass.onRender.call(this, ct, position);
234 if(this.submitValue === false){
235 this.el.dom.removeAttribute('name');
237 var type = this.el.dom.type;
239 if(type == 'password'){
242 this.el.addClass('x-form-'+type);
245 this.setReadOnly(true);
247 if(this.tabIndex !== undefined){
248 this.el.dom.setAttribute('tabIndex', this.tabIndex);
251 this.el.addClass([this.fieldClass, this.cls]);
255 getItemCt : function(){
260 initValue : function(){
261 if(this.value !== undefined){
262 this.setValue(this.value);
263 }else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
264 this.setValue(this.el.dom.value);
267 * The original value of the field as configured in the {@link #value} configuration, or
268 * as loaded by the last form load operation if the form's {@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
269 * setting is <code>true</code>.
271 * @property originalValue
273 this.originalValue = this.getValue();
277 * <p>Returns true if the value of this Field has been changed from its original value.
278 * Will return false if the field is disabled or has not been rendered yet.</p>
279 * <p>Note that if the owning {@link Ext.form.BasicForm form} was configured with
280 * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
281 * then the <i>original value</i> is updated when the values are loaded by
282 * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#setValues setValues}.</p>
283 * @return {Boolean} True if this field has been changed from its original value (and
284 * is not disabled), false otherwise.
286 isDirty : function() {
287 if(this.disabled || !this.rendered) {
290 return String(this.getValue()) !== String(this.originalValue);
294 * Sets the read only state of this field.
295 * @param {Boolean} readOnly Whether the field should be read only.
297 setReadOnly : function(readOnly){
299 this.el.dom.readOnly = readOnly;
301 this.readOnly = readOnly;
305 afterRender : function(){
306 Ext.form.Field.superclass.afterRender.call(this);
312 fireKey : function(e){
313 if(e.isSpecialKey()){
314 this.fireEvent('specialkey', this, e);
319 * Resets the current field value to the originally loaded value and clears any validation messages.
320 * See {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
323 this.setValue(this.originalValue);
328 initEvents : function(){
329 this.mon(this.el, Ext.EventManager.getKeyEvent(), this.fireKey, this);
330 this.mon(this.el, 'focus', this.onFocus, this);
332 // standardise buffer across all browsers + OS-es for consistent event order.
333 // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
334 this.mon(this.el, 'blur', this.onBlur, this, this.inEditor ? {buffer:10} : null);
338 preFocus: Ext.emptyFn,
341 onFocus : function(){
344 this.el.addClass(this.focusClass);
347 this.hasFocus = true;
349 * <p>The value that the Field had at the time it was last focused. This is the value that is passed
350 * to the {@link #change} event which is fired if the value has been changed when the Field is blurred.</p>
351 * <p><b>This will be undefined until the Field has been visited.</b> Compare {@link #originalValue}.</p>
353 * @property startValue
355 this.startValue = this.getValue();
356 this.fireEvent('focus', this);
361 beforeBlur : Ext.emptyFn,
367 this.el.removeClass(this.focusClass);
369 this.hasFocus = false;
370 if(this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == 'blur')){
373 var v = this.getValue();
374 if(String(v) !== String(this.startValue)){
375 this.fireEvent('change', this, v, this.startValue);
377 this.fireEvent('blur', this);
382 postBlur : Ext.emptyFn,
385 * Returns whether or not the field value is currently valid by
386 * {@link #validateValue validating} the {@link #processValue processed value}
387 * of the field. <b>Note</b>: {@link #disabled} fields are ignored.
388 * @param {Boolean} preventMark True to disable marking the field invalid
389 * @return {Boolean} True if the value is valid, else false
391 isValid : function(preventMark){
395 var restore = this.preventMark;
396 this.preventMark = preventMark === true;
397 var v = this.validateValue(this.processValue(this.getRawValue()));
398 this.preventMark = restore;
403 * Validates the field value
404 * @return {Boolean} True if the value is valid, else false
406 validate : function(){
407 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
415 * This method should only be overridden if necessary to prepare raw values
416 * for validation (see {@link #validate} and {@link #isValid}). This method
417 * is expected to return the processed value for the field which will
418 * be used for validation (see validateValue method).
419 * @param {Mixed} value
421 processValue : function(value){
426 * Uses getErrors to build an array of validation errors. If any errors are found, markInvalid is called
427 * with the first and false is returned, otherwise true is returned. Previously, subclasses were invited
428 * to provide an implementation of this to process validations - from 3.2 onwards getErrors should be
429 * overridden instead.
430 * @param {Mixed} The current value of the field
431 * @return {Boolean} True if all validations passed, false if one or more failed
433 validateValue : function(value) {
434 //currently, we only show 1 error at a time for a field, so just use the first one
435 var error = this.getErrors(value)[0];
437 if (error == undefined) {
440 this.markInvalid(error);
446 * Runs this field's validators and returns an array of error messages for any validation failures.
447 * This is called internally during validation and would not usually need to be used manually.
448 * Each subclass should override or augment the return value to provide their own errors
449 * @return {Array} All error messages for this field
451 getErrors: function() {
456 * Gets the active error message for this field.
457 * @return {String} Returns the active error message on the field, if there is no error, an empty string is returned.
459 getActiveError : function(){
460 return this.activeError || '';
464 * <p>Display an error message associated with this field, using {@link #msgTarget} to determine how to
465 * display the message and applying {@link #invalidClass} to the field's UI element.</p>
466 * <p><b>Note</b>: this method does not cause the Field's {@link #validate} method to return <code>false</code>
467 * if the value does <i>pass</i> validation. So simply marking a Field as invalid will not prevent
468 * submission of forms submitted with the {@link Ext.form.Action.Submit#clientValidation} option set.</p>
469 * {@link #isValid invalid}.
470 * @param {String} msg (optional) The validation message (defaults to {@link #invalidText})
472 markInvalid : function(msg){
473 //don't set the error icon if we're not rendered or marking is prevented
474 if (this.rendered && !this.preventMark) {
475 msg = msg || this.invalidText;
477 var mt = this.getMessageHandler();
480 }else if(this.msgTarget){
481 this.el.addClass(this.invalidClass);
482 var t = Ext.getDom(this.msgTarget);
485 t.style.display = this.msgDisplay;
490 this.setActiveError(msg);
494 * Clear any invalid styles/messages for this field
496 clearInvalid : function(){
497 //don't remove the error icon if we're not rendered or marking is prevented
498 if (this.rendered && !this.preventMark) {
499 this.el.removeClass(this.invalidClass);
500 var mt = this.getMessageHandler();
503 }else if(this.msgTarget){
504 this.el.removeClass(this.invalidClass);
505 var t = Ext.getDom(this.msgTarget);
508 t.style.display = 'none';
513 this.unsetActiveError();
517 * Sets the current activeError to the given string. Fires the 'invalid' event.
518 * This does not set up the error icon, only sets the message and fires the event. To show the error icon,
519 * use markInvalid instead, which calls this method internally
520 * @param {String} msg The error message
521 * @param {Boolean} suppressEvent True to suppress the 'invalid' event from being fired
523 setActiveError: function(msg, suppressEvent) {
524 this.activeError = msg;
525 if (suppressEvent !== true) this.fireEvent('invalid', this, msg);
529 * Clears the activeError and fires the 'valid' event. This is called internally by clearInvalid and would not
530 * usually need to be called manually
531 * @param {Boolean} suppressEvent True to suppress the 'invalid' event from being fired
533 unsetActiveError: function(suppressEvent) {
534 delete this.activeError;
535 if (suppressEvent !== true) this.fireEvent('valid', this);
539 getMessageHandler : function(){
540 return Ext.form.MessageTargets[this.msgTarget];
544 getErrorCt : function(){
545 return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
546 this.el.findParent('.x-form-field-wrap', 5, true); // else direct field wrap
549 // Alignment for 'under' target
550 alignErrorEl : function(){
551 this.errorEl.setWidth(this.getErrorCt().getWidth(true) - 20);
554 // Alignment for 'side' target
555 alignErrorIcon : function(){
556 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
560 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
561 * @return {Mixed} value The field value
563 getRawValue : function(){
564 var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
565 if(v === this.emptyText){
572 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
573 * @return {Mixed} value The field value
575 getValue : function(){
579 var v = this.el.getValue();
580 if(v === this.emptyText || v === undefined){
587 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
588 * @param {Mixed} value The value to set
589 * @return {Mixed} value The field value that is set
591 setRawValue : function(v){
592 return this.rendered ? (this.el.dom.value = (Ext.isEmpty(v) ? '' : v)) : '';
596 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
597 * @param {Mixed} value The value to set
598 * @return {Ext.form.Field} this
600 setValue : function(v){
603 this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
609 // private, does not work for all fields
610 append : function(v){
611 this.setValue([this.getValue(), v].join(''));
615 * @cfg {Boolean} autoWidth @hide
618 * @cfg {Boolean} autoHeight @hide
622 * @cfg {String} autoEl @hide
627 Ext.form.MessageTargets = {
629 mark: function(field, msg){
630 field.el.addClass(field.invalidClass);
631 field.el.dom.qtip = msg;
632 field.el.dom.qclass = 'x-form-invalid-tip';
633 if(Ext.QuickTips){ // fix for floating editors interacting with DND
634 Ext.QuickTips.enable();
637 clear: function(field){
638 field.el.removeClass(field.invalidClass);
639 field.el.dom.qtip = '';
643 mark: function(field, msg){
644 field.el.addClass(field.invalidClass);
645 field.el.dom.title = msg;
647 clear: function(field){
648 field.el.dom.title = '';
652 mark: function(field, msg){
653 field.el.addClass(field.invalidClass);
655 var elp = field.getErrorCt();
656 if(!elp){ // field has no container el
657 field.el.dom.title = msg;
660 field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
661 field.on('resize', field.alignErrorEl, field);
662 field.on('destroy', function(){
663 Ext.destroy(this.errorEl);
666 field.alignErrorEl();
667 field.errorEl.update(msg);
668 Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
670 clear: function(field){
671 field.el.removeClass(field.invalidClass);
673 Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
675 field.el.dom.title = '';
680 mark: function(field, msg){
681 field.el.addClass(field.invalidClass);
682 if(!field.errorIcon){
683 var elp = field.getErrorCt();
684 // field has no container el
686 field.el.dom.title = msg;
689 field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
691 field.ownerCt.on('afterlayout', field.alignErrorIcon, field);
692 field.ownerCt.on('expand', field.alignErrorIcon, field);
694 field.on('resize', field.alignErrorIcon, field);
695 field.on('destroy', function(){
696 Ext.destroy(this.errorIcon);
699 field.alignErrorIcon();
700 field.errorIcon.dom.qtip = msg;
701 field.errorIcon.dom.qclass = 'x-form-invalid-tip';
702 field.errorIcon.show();
704 clear: function(field){
705 field.el.removeClass(field.invalidClass);
707 field.errorIcon.dom.qtip = '';
708 field.errorIcon.hide();
710 field.el.dom.title = '';
716 // anything other than normal should be considered experimental
717 Ext.form.Field.msgFx = {
719 show: function(msgEl, f){
720 msgEl.setDisplayed('block');
723 hide : function(msgEl, f){
724 msgEl.setDisplayed(false).update('');
729 show: function(msgEl, f){
730 msgEl.slideIn('t', {stopFx:true});
733 hide : function(msgEl, f){
734 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
739 show: function(msgEl, f){
741 msgEl.alignTo(f.el, 'tl-tr');
742 msgEl.slideIn('l', {stopFx:true});
745 hide : function(msgEl, f){
746 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
750 Ext.reg('field', Ext.form.Field);
752 * @class Ext.form.TextField
753 * @extends Ext.form.Field
754 * <p>Basic text field. Can be used as a direct replacement for traditional text inputs,
755 * or as the base class for more sophisticated input controls (like {@link Ext.form.TextArea}
756 * and {@link Ext.form.ComboBox}).</p>
757 * <p><b><u>Validation</u></b></p>
758 * <p>The validation procedure is described in the documentation for {@link #validateValue}.</p>
759 * <p><b><u>Alter Validation Behavior</u></b></p>
760 * <p>Validation behavior for each field can be configured:</p>
761 * <div class="mdetail-params"><ul>
762 * <li><code>{@link Ext.form.TextField#invalidText invalidText}</code> : the default validation message to
763 * show if any validation step above does not provide a message when invalid</li>
764 * <li><code>{@link Ext.form.TextField#maskRe maskRe}</code> : filter out keystrokes before any validation occurs</li>
765 * <li><code>{@link Ext.form.TextField#stripCharsRe stripCharsRe}</code> : filter characters after being typed in,
766 * but before being validated</li>
767 * <li><code>{@link Ext.form.Field#invalidClass invalidClass}</code> : alternate style when invalid</li>
768 * <li><code>{@link Ext.form.Field#validateOnBlur validateOnBlur}</code>,
769 * <code>{@link Ext.form.Field#validationDelay validationDelay}</code>, and
770 * <code>{@link Ext.form.Field#validationEvent validationEvent}</code> : modify how/when validation is triggered</li>
773 * @constructor Creates a new TextField
774 * @param {Object} config Configuration options
778 Ext.form.TextField = Ext.extend(Ext.form.Field, {
780 * @cfg {String} vtypeText A custom error message to display in place of the default message provided
781 * for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>''</tt>). <b>Note</b>:
782 * only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
785 * @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
786 * before validation (defaults to <tt>null</tt>).
789 * @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
790 * (defaults to <tt>false</tt>)
794 * @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
799 * @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
804 * @cfg {String} vtype A validation type name as defined in {@link Ext.form.VTypes} (defaults to <tt>null</tt>)
808 * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
809 * not match (defaults to <tt>null</tt>)
813 * @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
816 disableKeyFilter : false,
818 * @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
823 * @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
827 * @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
828 * This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
829 * and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
830 * entered into the field use <tt><b>{@link Ext.form.Field#autoCreate autoCreate}</b></tt> to add
831 * any attributes you want to a field, for example:<pre><code>
832 var myField = new Ext.form.NumberField({
835 fieldLabel: 'Mobile',
836 maxLength: 16, // for validation
837 autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete: 'off', maxlength: '10'}
841 maxLength : Number.MAX_VALUE,
843 * @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
844 * validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
846 minLengthText : 'The minimum length for this field is {0}',
848 * @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
849 * validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
851 maxLengthText : 'The maximum length for this field is {0}',
853 * @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
854 * receives input focus (defaults to <tt>false</tt>)
856 selectOnFocus : false,
858 * @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
859 * fails (defaults to <tt>'This field is required'</tt>)
861 blankText : 'This field is required',
863 * @cfg {Function} validator
864 * <p>A custom validation function to be called during field validation ({@link #validateValue})
865 * (defaults to <tt>null</tt>). If specified, this function will be called first, allowing the
866 * developer to override the default validation process.</p>
867 * <br><p>This function will be passed the following Parameters:</p>
868 * <div class="mdetail-params"><ul>
869 * <li><code>value</code>: <i>Mixed</i>
870 * <div class="sub-desc">The current field value</div></li>
872 * <br><p>This function is to Return:</p>
873 * <div class="mdetail-params"><ul>
874 * <li><code>true</code>: <i>Boolean</i>
875 * <div class="sub-desc"><code>true</code> if the value is valid</div></li>
876 * <li><code>msg</code>: <i>String</i>
877 * <div class="sub-desc">An error message if the value is invalid</div></li>
882 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
883 * (defaults to <tt>null</tt>). If the test fails, the field will be marked invalid using
884 * <b><tt>{@link #regexText}</tt></b>.
888 * @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
889 * test fails during validation (defaults to <tt>''</tt>)
893 * @cfg {String} emptyText The default text to place into an empty field (defaults to <tt>null</tt>).
894 * <b>Note</b>: that this value will be submitted to the server if this field is enabled and configured
895 * with a {@link #name}.
899 * @cfg {String} emptyClass The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
900 * (defaults to <tt>'x-form-empty-field'</tt>). This class is automatically added and removed as needed
901 * depending on the current field value.
903 emptyClass : 'x-form-empty-field',
906 * @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input
907 * field (defaults to <tt>false</tt>)
910 initComponent : function(){
911 Ext.form.TextField.superclass.initComponent.call(this);
915 * Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered. The field may or
916 * may not have actually changed size according to the default logic, but this event provides
917 * a hook for the developer to apply additional logic at runtime to resize the field if needed.
918 * @param {Ext.form.Field} this This text field
919 * @param {Number} width The new field width
925 * Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
927 * @param {Ext.form.TextField} this This text field
928 * @param {Ext.EventObject} e
933 * Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
935 * @param {Ext.form.TextField} this This text field
936 * @param {Ext.EventObject} e
941 * Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
943 * @param {Ext.form.TextField} this This text field
944 * @param {Ext.EventObject} e
951 initEvents : function(){
952 Ext.form.TextField.superclass.initEvents.call(this);
953 if(this.validationEvent == 'keyup'){
954 this.validationTask = new Ext.util.DelayedTask(this.validate, this);
955 this.mon(this.el, 'keyup', this.filterValidation, this);
957 else if(this.validationEvent !== false && this.validationEvent != 'blur'){
958 this.mon(this.el, this.validationEvent, this.validate, this, {buffer: this.validationDelay});
960 if(this.selectOnFocus || this.emptyText){
961 this.mon(this.el, 'mousedown', this.onMouseDown, this);
964 this.applyEmptyText();
967 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){
968 this.mon(this.el, 'keypress', this.filterKeys, this);
971 this.mon(this.el, 'keyup', this.onKeyUpBuffered, this, {buffer: 50});
972 this.mon(this.el, 'click', this.autoSize, this);
974 if(this.enableKeyEvents){
978 keydown: this.onKeyDown,
979 keypress: this.onKeyPress
984 onMouseDown: function(e){
986 this.mon(this.el, 'mouseup', Ext.emptyFn, this, { single: true, preventDefault: true });
990 processValue : function(value){
991 if(this.stripCharsRe){
992 var newValue = value.replace(this.stripCharsRe, '');
993 if(newValue !== value){
994 this.setRawValue(newValue);
1001 filterValidation : function(e){
1002 if(!e.isNavKeyPress()){
1003 this.validationTask.delay(this.validationDelay);
1008 onDisable: function(){
1009 Ext.form.TextField.superclass.onDisable.call(this);
1011 this.el.dom.unselectable = 'on';
1016 onEnable: function(){
1017 Ext.form.TextField.superclass.onEnable.call(this);
1019 this.el.dom.unselectable = '';
1024 onKeyUpBuffered : function(e){
1025 if(this.doAutoSize(e)){
1031 doAutoSize : function(e){
1032 return !e.isNavKeyPress();
1036 onKeyUp : function(e){
1037 this.fireEvent('keyup', this, e);
1041 onKeyDown : function(e){
1042 this.fireEvent('keydown', this, e);
1046 onKeyPress : function(e){
1047 this.fireEvent('keypress', this, e);
1051 * Resets the current field value to the originally-loaded value and clears any validation messages.
1052 * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyClass}</b></tt> if the
1053 * original value was blank.
1056 Ext.form.TextField.superclass.reset.call(this);
1057 this.applyEmptyText();
1060 applyEmptyText : function(){
1061 if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
1062 this.setRawValue(this.emptyText);
1063 this.el.addClass(this.emptyClass);
1068 preFocus : function(){
1072 if(el.dom.value == this.emptyText){
1073 this.setRawValue('');
1076 el.removeClass(this.emptyClass);
1078 if(this.selectOnFocus || isEmpty){
1084 postBlur : function(){
1085 this.applyEmptyText();
1089 filterKeys : function(e){
1094 if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
1097 var cc = String.fromCharCode(e.getCharCode());
1098 if(!Ext.isGecko && e.isSpecialKey() && !cc){
1101 if(!this.maskRe.test(cc)){
1106 setValue : function(v){
1107 if(this.emptyText && this.el && !Ext.isEmpty(v)){
1108 this.el.removeClass(this.emptyClass);
1110 Ext.form.TextField.superclass.setValue.apply(this, arguments);
1111 this.applyEmptyText();
1117 * <p>Validates a value according to the field's validation rules and returns an array of errors
1118 * for any failing validations. Validation rules are processed in the following order:</p>
1119 * <div class="mdetail-params"><ul>
1121 * <li><b>1. Field specific validator</b>
1122 * <div class="sub-desc">
1123 * <p>A validator offers a way to customize and reuse a validation specification.
1124 * If a field is configured with a <code>{@link #validator}</code>
1125 * function, it will be passed the current field value. The <code>{@link #validator}</code>
1126 * function is expected to return either:
1127 * <div class="mdetail-params"><ul>
1128 * <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
1129 * <li>a String to represent the invalid message if invalid (validation halts).</li>
1133 * <li><b>2. Basic Validation</b>
1134 * <div class="sub-desc">
1135 * <p>If the <code>{@link #validator}</code> has not halted validation,
1136 * basic validation proceeds as follows:</p>
1138 * <div class="mdetail-params"><ul>
1140 * <li><code>{@link #allowBlank}</code> : (Invalid message =
1141 * <code>{@link #emptyText}</code>)<div class="sub-desc">
1142 * Depending on the configuration of <code>{@link #allowBlank}</code>, a
1143 * blank field will cause validation to halt at this step and return
1144 * Boolean true or false accordingly.
1147 * <li><code>{@link #minLength}</code> : (Invalid message =
1148 * <code>{@link #minLengthText}</code>)<div class="sub-desc">
1149 * If the passed value does not satisfy the <code>{@link #minLength}</code>
1150 * specified, validation halts.
1153 * <li><code>{@link #maxLength}</code> : (Invalid message =
1154 * <code>{@link #maxLengthText}</code>)<div class="sub-desc">
1155 * If the passed value does not satisfy the <code>{@link #maxLength}</code>
1156 * specified, validation halts.
1162 * <li><b>3. Preconfigured Validation Types (VTypes)</b>
1163 * <div class="sub-desc">
1164 * <p>If none of the prior validation steps halts validation, a field
1165 * configured with a <code>{@link #vtype}</code> will utilize the
1166 * corresponding {@link Ext.form.VTypes VTypes} validation function.
1167 * If invalid, either the field's <code>{@link #vtypeText}</code> or
1168 * the VTypes vtype Text property will be used for the invalid message.
1169 * Keystrokes on the field will be filtered according to the VTypes
1170 * vtype Mask property.</p>
1173 * <li><b>4. Field specific regex test</b>
1174 * <div class="sub-desc">
1175 * <p>If none of the prior validation steps halts validation, a field's
1176 * configured <code>{@link #regex}</code> test will be processed.
1177 * The invalid message for this test is configured with
1178 * <code>{@link #regexText}</code>.</p>
1181 * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
1182 * @return {Array} Array of any validation errors
1184 getErrors: function(value) {
1185 var errors = Ext.form.TextField.superclass.getErrors.apply(this, arguments);
1187 value = Ext.isDefined(value) ? value : this.processValue(this.getRawValue());
1189 if (Ext.isFunction(this.validator)) {
1190 var msg = this.validator(value);
1196 if (value.length < 1 || value === this.emptyText) {
1197 if (this.allowBlank) {
1198 //if value is blank and allowBlank is true, there cannot be any additional errors
1201 errors.push(this.blankText);
1205 if (!this.allowBlank && (value.length < 1 || value === this.emptyText)) { // if it's blank
1206 errors.push(this.blankText);
1209 if (value.length < this.minLength) {
1210 errors.push(String.format(this.minLengthText, this.minLength));
1213 if (value.length > this.maxLength) {
1214 errors.push(String.format(this.maxLengthText, this.maxLength));
1218 var vt = Ext.form.VTypes;
1219 if(!vt[this.vtype](value, this)){
1220 errors.push(this.vtypeText || vt[this.vtype +'Text']);
1224 if (this.regex && !this.regex.test(value)) {
1225 errors.push(this.regexText);
1232 * Selects text in this field
1233 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
1234 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
1236 selectText : function(start, end){
1237 var v = this.getRawValue();
1238 var doFocus = false;
1240 start = start === undefined ? 0 : start;
1241 end = end === undefined ? v.length : end;
1242 var d = this.el.dom;
1243 if(d.setSelectionRange){
1244 d.setSelectionRange(start, end);
1245 }else if(d.createTextRange){
1246 var range = d.createTextRange();
1247 range.moveStart('character', start);
1248 range.moveEnd('character', end-v.length);
1251 doFocus = Ext.isGecko || Ext.isOpera;
1261 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
1262 * This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
1264 autoSize : function(){
1265 if(!this.grow || !this.rendered){
1269 this.metrics = Ext.util.TextMetrics.createInstance(this.el);
1272 var v = el.dom.value;
1273 var d = document.createElement('div');
1274 d.appendChild(document.createTextNode(v));
1279 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
1280 this.el.setWidth(w);
1281 this.fireEvent('autosize', this, w);
1284 onDestroy: function(){
1285 if(this.validationTask){
1286 this.validationTask.cancel();
1287 this.validationTask = null;
1289 Ext.form.TextField.superclass.onDestroy.call(this);
1292 Ext.reg('textfield', Ext.form.TextField);
1294 * @class Ext.form.TriggerField
1295 * @extends Ext.form.TextField
1296 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
1297 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
1298 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
1299 * for which you can provide a custom implementation. For example:
1301 var trigger = new Ext.form.TriggerField();
1302 trigger.onTriggerClick = myTriggerFn;
1303 trigger.applyToMarkup('my-field');
1306 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
1307 * {@link Ext.form.DateField} and {@link Ext.form.ComboBox} are perfect examples of this.
1310 * Create a new TriggerField.
1311 * @param {Object} config Configuration options (valid {@Ext.form.TextField} config options will also be applied
1312 * to the base TextField)
1315 Ext.form.TriggerField = Ext.extend(Ext.form.TextField, {
1317 * @cfg {String} triggerClass
1318 * An additional CSS class used to style the trigger button. The trigger will always get the
1319 * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
1322 * @cfg {Mixed} triggerConfig
1323 * <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the
1324 * trigger element for this Field. (Optional).</p>
1325 * <p>Specify this when you need a customized element to act as the trigger button for a TriggerField.</p>
1326 * <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing, positioning
1327 * and appearance of the trigger. Defaults to:</p>
1328 * <pre><code>{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}</code></pre>
1331 * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
1332 * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
1333 * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
1334 * <pre><code>{tag: "input", type: "text", size: "16", autocomplete: "off"}</code></pre>
1336 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
1338 * @cfg {Boolean} hideTrigger <tt>true</tt> to hide the trigger element and display only the base
1339 * text field (defaults to <tt>false</tt>)
1343 * @cfg {Boolean} editable <tt>false</tt> to prevent the user from typing text directly into the field,
1344 * the field will only respond to a click on the trigger to set the value. (defaults to <tt>true</tt>).
1348 * @cfg {Boolean} readOnly <tt>true</tt> to prevent the user from changing the field, and
1349 * hides the trigger. Superceeds the editable and hideTrigger options if the value is true.
1350 * (defaults to <tt>false</tt>)
1354 * @cfg {String} wrapFocusClass The class added to the to the wrap of the trigger element. Defaults to
1355 * <tt>x-trigger-wrap-focus</tt>.
1357 wrapFocusClass: 'x-trigger-wrap-focus',
1362 autoSize: Ext.emptyFn,
1372 defaultTriggerWidth: 17,
1375 onResize : function(w, h){
1376 Ext.form.TriggerField.superclass.onResize.call(this, w, h);
1377 var tw = this.getTriggerWidth();
1378 if(Ext.isNumber(w)){
1379 this.el.setWidth(w - tw);
1381 this.wrap.setWidth(this.el.getWidth() + tw);
1384 getTriggerWidth: function(){
1385 var tw = this.trigger.getWidth();
1386 if(!this.hideTrigger && !this.readOnly && tw === 0){
1387 tw = this.defaultTriggerWidth;
1393 alignErrorIcon : function(){
1395 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
1400 onRender : function(ct, position){
1401 this.doc = Ext.isIE ? Ext.getBody() : Ext.getDoc();
1402 Ext.form.TriggerField.superclass.onRender.call(this, ct, position);
1404 this.wrap = this.el.wrap({cls: 'x-form-field-wrap x-form-field-trigger-wrap'});
1405 this.trigger = this.wrap.createChild(this.triggerConfig ||
1406 {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.triggerClass});
1409 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
1411 this.resizeEl = this.positionEl = this.wrap;
1414 getWidth: function() {
1415 return(this.el.getWidth() + this.trigger.getWidth());
1418 updateEditState: function(){
1420 if (this.readOnly) {
1421 this.el.dom.readOnly = true;
1422 this.el.addClass('x-trigger-noedit');
1423 this.mun(this.el, 'click', this.onTriggerClick, this);
1424 this.trigger.setDisplayed(false);
1426 if (!this.editable) {
1427 this.el.dom.readOnly = true;
1428 this.el.addClass('x-trigger-noedit');
1429 this.mon(this.el, 'click', this.onTriggerClick, this);
1431 this.el.dom.readOnly = false;
1432 this.el.removeClass('x-trigger-noedit');
1433 this.mun(this.el, 'click', this.onTriggerClick, this);
1435 this.trigger.setDisplayed(!this.hideTrigger);
1437 this.onResize(this.width || this.wrap.getWidth());
1442 * Changes the hidden status of the trigger.
1443 * @param {Boolean} hideTrigger True to hide the trigger, false to show it.
1445 setHideTrigger: function(hideTrigger){
1446 if(hideTrigger != this.hideTrigger){
1447 this.hideTrigger = hideTrigger;
1448 this.updateEditState();
1453 * Allow or prevent the user from directly editing the field text. If false is passed,
1454 * the user will only be able to modify the field using the trigger. Will also add
1455 * a click event to the text field which will call the trigger. This method
1456 * is the runtime equivalent of setting the {@link #editable} config option at config time.
1457 * @param {Boolean} value True to allow the user to directly edit the field text.
1459 setEditable: function(editable){
1460 if(editable != this.editable){
1461 this.editable = editable;
1462 this.updateEditState();
1467 * Setting this to true will supersede settings {@link #editable} and {@link #hideTrigger}.
1468 * Setting this to false will defer back to {@link #editable} and {@link #hideTrigger}. This method
1469 * is the runtime equivalent of setting the {@link #readOnly} config option at config time.
1470 * @param {Boolean} value True to prevent the user changing the field and explicitly
1473 setReadOnly: function(readOnly){
1474 if(readOnly != this.readOnly){
1475 this.readOnly = readOnly;
1476 this.updateEditState();
1480 afterRender : function(){
1481 Ext.form.TriggerField.superclass.afterRender.call(this);
1482 this.updateEditState();
1486 initTrigger : function(){
1487 this.mon(this.trigger, 'click', this.onTriggerClick, this, {preventDefault:true});
1488 this.trigger.addClassOnOver('x-form-trigger-over');
1489 this.trigger.addClassOnClick('x-form-trigger-click');
1493 onDestroy : function(){
1494 Ext.destroy(this.trigger, this.wrap);
1496 this.doc.un('mousedown', this.mimicBlur, this);
1499 Ext.form.TriggerField.superclass.onDestroy.call(this);
1503 onFocus : function(){
1504 Ext.form.TriggerField.superclass.onFocus.call(this);
1506 this.wrap.addClass(this.wrapFocusClass);
1507 this.mimicing = true;
1508 this.doc.on('mousedown', this.mimicBlur, this, {delay: 10});
1509 if(this.monitorTab){
1510 this.on('specialkey', this.checkTab, this);
1516 checkTab : function(me, e){
1517 if(e.getKey() == e.TAB){
1523 onBlur : Ext.emptyFn,
1526 mimicBlur : function(e){
1527 if(!this.isDestroyed && !this.wrap.contains(e.target) && this.validateBlur(e)){
1533 triggerBlur : function(){
1534 this.mimicing = false;
1535 this.doc.un('mousedown', this.mimicBlur, this);
1536 if(this.monitorTab && this.el){
1537 this.un('specialkey', this.checkTab, this);
1539 Ext.form.TriggerField.superclass.onBlur.call(this);
1541 this.wrap.removeClass(this.wrapFocusClass);
1545 beforeBlur : Ext.emptyFn,
1548 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
1549 validateBlur : function(e){
1554 * The function that should handle the trigger's click event. This method does nothing by default
1555 * until overridden by an implementing function. See Ext.form.ComboBox and Ext.form.DateField for
1556 * sample implementations.
1558 * @param {EventObject} e
1560 onTriggerClick : Ext.emptyFn
1563 * @cfg {Boolean} grow @hide
1566 * @cfg {Number} growMin @hide
1569 * @cfg {Number} growMax @hide
1574 * @class Ext.form.TwinTriggerField
1575 * @extends Ext.form.TriggerField
1576 * TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
1577 * to be extended by an implementing class. For an example of implementing this class, see the custom
1578 * SearchField implementation here:
1579 * <a href="http://extjs.com/deploy/ext/examples/form/custom.html">http://extjs.com/deploy/ext/examples/form/custom.html</a>
1581 Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, {
1583 * @cfg {Mixed} triggerConfig
1584 * <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the trigger elements
1585 * for this Field. (Optional).</p>
1586 * <p>Specify this when you need a customized element to contain the two trigger elements for this Field.
1587 * Each trigger element must be marked by the CSS class <tt>x-form-trigger</tt> (also see
1588 * <tt>{@link #trigger1Class}</tt> and <tt>{@link #trigger2Class}</tt>).</p>
1589 * <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing,
1590 * positioning and appearance of the triggers.</p>
1593 * @cfg {String} trigger1Class
1594 * An additional CSS class used to style the trigger button. The trigger will always get the
1595 * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
1598 * @cfg {String} trigger2Class
1599 * An additional CSS class used to style the trigger button. The trigger will always get the
1600 * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
1603 initComponent : function(){
1604 Ext.form.TwinTriggerField.superclass.initComponent.call(this);
1606 this.triggerConfig = {
1607 tag:'span', cls:'x-form-twin-triggers', cn:[
1608 {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.trigger1Class},
1609 {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.trigger2Class}
1613 getTrigger : function(index){
1614 return this.triggers[index];
1617 afterRender: function(){
1618 Ext.form.TwinTriggerField.superclass.afterRender.call(this);
1619 var triggers = this.triggers,
1621 len = triggers.length;
1623 for(; i < len; ++i){
1624 if(this['hideTrigger' + (i + 1)]){
1631 initTrigger : function(){
1632 var ts = this.trigger.select('.x-form-trigger', true),
1633 triggerField = this;
1635 ts.each(function(t, all, index){
1636 var triggerIndex = 'Trigger'+(index+1);
1637 t.hide = function(){
1638 var w = triggerField.wrap.getWidth();
1639 this.dom.style.display = 'none';
1640 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
1641 triggerField['hidden' + triggerIndex] = true;
1643 t.show = function(){
1644 var w = triggerField.wrap.getWidth();
1645 this.dom.style.display = '';
1646 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
1647 triggerField['hidden' + triggerIndex] = false;
1649 this.mon(t, 'click', this['on'+triggerIndex+'Click'], this, {preventDefault:true});
1650 t.addClassOnOver('x-form-trigger-over');
1651 t.addClassOnClick('x-form-trigger-click');
1653 this.triggers = ts.elements;
1656 getTriggerWidth: function(){
1658 Ext.each(this.triggers, function(t, index){
1659 var triggerIndex = 'Trigger' + (index + 1),
1661 if(w === 0 && !this['hidden' + triggerIndex]){
1662 tw += this.defaultTriggerWidth;
1671 onDestroy : function() {
1672 Ext.destroy(this.triggers);
1673 Ext.form.TwinTriggerField.superclass.onDestroy.call(this);
1677 * The function that should handle the trigger's click event. This method does nothing by default
1678 * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
1679 * for additional information.
1681 * @param {EventObject} e
1683 onTrigger1Click : Ext.emptyFn,
1685 * The function that should handle the trigger's click event. This method does nothing by default
1686 * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
1687 * for additional information.
1689 * @param {EventObject} e
1691 onTrigger2Click : Ext.emptyFn
1693 Ext.reg('trigger', Ext.form.TriggerField);
1695 * @class Ext.form.TextArea
1696 * @extends Ext.form.TextField
1697 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
1698 * support for auto-sizing.
1700 * Creates a new TextArea
1701 * @param {Object} config Configuration options
1704 Ext.form.TextArea = Ext.extend(Ext.form.TextField, {
1706 * @cfg {Number} growMin The minimum height to allow when <tt>{@link Ext.form.TextField#grow grow}=true</tt>
1707 * (defaults to <tt>60</tt>)
1711 * @cfg {Number} growMax The maximum height to allow when <tt>{@link Ext.form.TextField#grow grow}=true</tt>
1712 * (defaults to <tt>1000</tt>)
1715 growAppend : ' \n ',
1717 enterIsSpecial : false,
1720 * @cfg {Boolean} preventScrollbars <tt>true</tt> to prevent scrollbars from appearing regardless of how much text is
1721 * in the field. This option is only relevant when {@link #grow} is <tt>true</tt>. Equivalent to setting overflow: hidden, defaults to
1724 preventScrollbars: false,
1726 * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
1727 * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
1728 * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
1729 * <pre><code>{tag: "textarea", style: "width:100px;height:60px;", autocomplete: "off"}</code></pre>
1733 onRender : function(ct, position){
1735 this.defaultAutoCreate = {
1737 style:"width:100px;height:60px;",
1741 Ext.form.TextArea.superclass.onRender.call(this, ct, position);
1743 this.textSizeEl = Ext.DomHelper.append(document.body, {
1744 tag: "pre", cls: "x-form-grow-sizer"
1746 if(this.preventScrollbars){
1747 this.el.setStyle("overflow", "hidden");
1749 this.el.setHeight(this.growMin);
1753 onDestroy : function(){
1754 Ext.removeNode(this.textSizeEl);
1755 Ext.form.TextArea.superclass.onDestroy.call(this);
1758 fireKey : function(e){
1759 if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){
1760 this.fireEvent("specialkey", this, e);
1765 doAutoSize : function(e){
1766 return !e.isNavKeyPress() || e.getKey() == e.ENTER;
1770 filterValidation: function(e) {
1771 if(!e.isNavKeyPress() || (!this.enterIsSpecial && e.keyCode == e.ENTER)){
1772 this.validationTask.delay(this.validationDelay);
1777 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
1778 * This only takes effect if grow = true, and fires the {@link #autosize} event if the height changes.
1780 autoSize: function(){
1781 if(!this.grow || !this.textSizeEl){
1785 v = Ext.util.Format.htmlEncode(el.dom.value),
1786 ts = this.textSizeEl,
1789 Ext.fly(ts).setWidth(this.el.getWidth());
1793 v += this.growAppend;
1795 v = v.replace(/\n/g, ' <br />');
1799 h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
1800 if(h != this.lastHeight){
1801 this.lastHeight = h;
1802 this.el.setHeight(h);
1803 this.fireEvent("autosize", this, h);
1807 Ext.reg('textarea', Ext.form.TextArea);/**
1808 * @class Ext.form.NumberField
1809 * @extends Ext.form.TextField
1810 * Numeric text field that provides automatic keystroke filtering and numeric validation.
1812 * Creates a new NumberField
1813 * @param {Object} config Configuration options
1814 * @xtype numberfield
1816 Ext.form.NumberField = Ext.extend(Ext.form.TextField, {
1818 * @cfg {RegExp} stripCharsRe @hide
1821 * @cfg {RegExp} maskRe @hide
1824 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
1826 fieldClass: "x-form-field x-form-num-field",
1829 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
1831 allowDecimals : true,
1834 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
1836 decimalSeparator : ".",
1839 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
1841 decimalPrecision : 2,
1844 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
1846 allowNegative : true,
1849 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
1851 minValue : Number.NEGATIVE_INFINITY,
1854 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
1856 maxValue : Number.MAX_VALUE,
1859 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
1861 minText : "The minimum value for this field is {0}",
1864 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
1866 maxText : "The maximum value for this field is {0}",
1869 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
1870 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
1872 nanText : "{0} is not a valid number",
1875 * @cfg {String} baseChars The base set of characters to evaluate as valid numbers (defaults to '0123456789').
1877 baseChars : "0123456789",
1880 * @cfg {Boolean} autoStripChars True to automatically strip not allowed characters from the field. Defaults to <tt>false</tt>
1882 autoStripChars: false,
1885 initEvents : function() {
1886 var allowed = this.baseChars + '';
1887 if (this.allowDecimals) {
1888 allowed += this.decimalSeparator;
1890 if (this.allowNegative) {
1893 allowed = Ext.escapeRe(allowed);
1894 this.maskRe = new RegExp('[' + allowed + ']');
1895 if (this.autoStripChars) {
1896 this.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
1899 Ext.form.NumberField.superclass.initEvents.call(this);
1903 * Runs all of NumberFields validations and returns an array of any errors. Note that this first
1904 * runs TextField's validations, so the returned array is an amalgamation of all field errors.
1905 * The additional validations run test that the value is a number, and that it is within the
1906 * configured min and max values.
1907 * @param {Mixed} value The value to get errors for (defaults to the current field value)
1908 * @return {Array} All validation errors for this field
1910 getErrors: function(value) {
1911 var errors = Ext.form.NumberField.superclass.getErrors.apply(this, arguments);
1913 value = Ext.isDefined(value) ? value : this.processValue(this.getRawValue());
1915 if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
1919 value = String(value).replace(this.decimalSeparator, ".");
1922 errors.push(String.format(this.nanText, value));
1925 var num = this.parseValue(value);
1927 if (num < this.minValue) {
1928 errors.push(String.format(this.minText, this.minValue));
1931 if (num > this.maxValue) {
1932 errors.push(String.format(this.maxText, this.maxValue));
1938 getValue : function() {
1939 return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this)));
1942 setValue : function(v) {
1943 v = this.fixPrecision(v);
1944 v = Ext.isNumber(v) ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
1945 v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
1946 return Ext.form.NumberField.superclass.setValue.call(this, v);
1950 * Replaces any existing {@link #minValue} with the new value.
1951 * @param {Number} value The minimum value
1953 setMinValue : function(value) {
1954 this.minValue = Ext.num(value, Number.NEGATIVE_INFINITY);
1958 * Replaces any existing {@link #maxValue} with the new value.
1959 * @param {Number} value The maximum value
1961 setMaxValue : function(value) {
1962 this.maxValue = Ext.num(value, Number.MAX_VALUE);
1966 parseValue : function(value) {
1967 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
1968 return isNaN(value) ? '' : value;
1975 fixPrecision : function(value) {
1976 var nan = isNaN(value);
1978 if (!this.allowDecimals || this.decimalPrecision == -1 || nan || !value) {
1979 return nan ? '' : value;
1982 return parseFloat(parseFloat(value).toFixed(this.decimalPrecision));
1985 beforeBlur : function() {
1986 var v = this.parseValue(this.getRawValue());
1988 if (!Ext.isEmpty(v)) {
1994 Ext.reg('numberfield', Ext.form.NumberField);
1996 * @class Ext.form.DateField
1997 * @extends Ext.form.TriggerField
1998 * Provides a date input field with a {@link Ext.DatePicker} dropdown and automatic date validation.
2000 * Create a new DateField
2001 * @param {Object} config
2004 Ext.form.DateField = Ext.extend(Ext.form.TriggerField, {
2006 * @cfg {String} format
2007 * The default date format string which can be overriden for localization support. The format must be
2008 * valid according to {@link Date#parseDate} (defaults to <tt>'m/d/Y'</tt>).
2012 * @cfg {String} altFormats
2013 * Multiple date formats separated by "<tt>|</tt>" to try when parsing a user input value and it
2014 * does not match the defined format (defaults to
2015 * <tt>'m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j'</tt>).
2017 altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j",
2019 * @cfg {String} disabledDaysText
2020 * The tooltip to display when the date falls on a disabled day (defaults to <tt>'Disabled'</tt>)
2022 disabledDaysText : "Disabled",
2024 * @cfg {String} disabledDatesText
2025 * The tooltip text to display when the date falls on a disabled date (defaults to <tt>'Disabled'</tt>)
2027 disabledDatesText : "Disabled",
2029 * @cfg {String} minText
2030 * The error text to display when the date in the cell is before <tt>{@link #minValue}</tt> (defaults to
2031 * <tt>'The date in this field must be after {minValue}'</tt>).
2033 minText : "The date in this field must be equal to or after {0}",
2035 * @cfg {String} maxText
2036 * The error text to display when the date in the cell is after <tt>{@link #maxValue}</tt> (defaults to
2037 * <tt>'The date in this field must be before {maxValue}'</tt>).
2039 maxText : "The date in this field must be equal to or before {0}",
2041 * @cfg {String} invalidText
2042 * The error text to display when the date in the field is invalid (defaults to
2043 * <tt>'{value} is not a valid date - it must be in the format {format}'</tt>).
2045 invalidText : "{0} is not a valid date - it must be in the format {1}",
2047 * @cfg {String} triggerClass
2048 * An additional CSS class used to style the trigger button. The trigger will always get the
2049 * class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
2050 * (defaults to <tt>'x-form-date-trigger'</tt> which displays a calendar icon).
2052 triggerClass : 'x-form-date-trigger',
2054 * @cfg {Boolean} showToday
2055 * <tt>false</tt> to hide the footer area of the DatePicker containing the Today button and disable
2056 * the keyboard handler for spacebar that selects the current date (defaults to <tt>true</tt>).
2061 * @cfg {Number} startDay
2062 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
2067 * @cfg {Date/String} minValue
2068 * The minimum allowed date. Can be either a Javascript date object or a string date in a
2069 * valid format (defaults to null).
2072 * @cfg {Date/String} maxValue
2073 * The maximum allowed date. Can be either a Javascript date object or a string date in a
2074 * valid format (defaults to null).
2077 * @cfg {Array} disabledDays
2078 * An array of days to disable, 0 based (defaults to null). Some examples:<pre><code>
2079 // disable Sunday and Saturday:
2080 disabledDays: [0, 6]
2081 // disable weekdays:
2082 disabledDays: [1,2,3,4,5]
2086 * @cfg {Array} disabledDates
2087 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
2088 * expression so they are very powerful. Some examples:<pre><code>
2089 // disable these exact dates:
2090 disabledDates: ["03/08/2003", "09/16/2003"]
2091 // disable these days for every year:
2092 disabledDates: ["03/08", "09/16"]
2093 // only match the beginning (useful if you are using short years):
2094 disabledDates: ["^03/08"]
2095 // disable every day in March 2006:
2096 disabledDates: ["03/../2006"]
2097 // disable every day in every March:
2098 disabledDates: ["^03"]
2100 * Note that the format of the dates included in the array should exactly match the {@link #format} config.
2101 * In order to support regular expressions, if you are using a {@link #format date format} that has "." in
2102 * it, you will have to escape the dot when restricting dates. For example: <tt>["03\\.08\\.03"]</tt>.
2105 * @cfg {String/Object} autoCreate
2106 * A {@link Ext.DomHelper DomHelper element specification object}, or <tt>true</tt> for the default element
2107 * specification object:<pre><code>
2108 * autoCreate: {tag: "input", type: "text", size: "10", autocomplete: "off"}
2113 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
2115 // in the absence of a time value, a default value of 12 noon will be used
2116 // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
2117 initTime: '12', // 24 hour format
2119 initTimeFormat: 'H',
2121 // PUBLIC -- to be documented
2122 safeParse : function(value, format) {
2123 if (/[gGhH]/.test(format.replace(/(\\.)/g, ''))) {
2124 // if parse format contains hour information, no DST adjustment is necessary
2125 return Date.parseDate(value, format);
2127 // set time to 12 noon, then clear the time
2128 var parsedDate = Date.parseDate(value + ' ' + this.initTime, format + ' ' + this.initTimeFormat);
2131 return parsedDate.clearTime();
2136 initComponent : function(){
2137 Ext.form.DateField.superclass.initComponent.call(this);
2142 * Fires when a date is selected via the date picker.
2143 * @param {Ext.form.DateField} this
2144 * @param {Date} date The date that was selected
2149 if(Ext.isString(this.minValue)){
2150 this.minValue = this.parseDate(this.minValue);
2152 if(Ext.isString(this.maxValue)){
2153 this.maxValue = this.parseDate(this.maxValue);
2155 this.disabledDatesRE = null;
2156 this.initDisabledDays();
2159 initEvents: function() {
2160 Ext.form.DateField.superclass.initEvents.call(this);
2161 this.keyNav = new Ext.KeyNav(this.el, {
2162 "down": function(e) {
2163 this.onTriggerClick();
2172 initDisabledDays : function(){
2173 if(this.disabledDates){
2174 var dd = this.disabledDates,
2175 len = dd.length - 1,
2178 Ext.each(dd, function(d, i){
2179 re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
2184 this.disabledDatesRE = new RegExp(re + ')');
2189 * Replaces any existing disabled dates with new values and refreshes the DatePicker.
2190 * @param {Array} disabledDates An array of date strings (see the <tt>{@link #disabledDates}</tt> config
2191 * for details on supported values) used to disable a pattern of dates.
2193 setDisabledDates : function(dd){
2194 this.disabledDates = dd;
2195 this.initDisabledDays();
2197 this.menu.picker.setDisabledDates(this.disabledDatesRE);
2202 * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
2203 * @param {Array} disabledDays An array of disabled day indexes. See the <tt>{@link #disabledDays}</tt>
2204 * config for details on supported values.
2206 setDisabledDays : function(dd){
2207 this.disabledDays = dd;
2209 this.menu.picker.setDisabledDays(dd);
2214 * Replaces any existing <tt>{@link #minValue}</tt> with the new value and refreshes the DatePicker.
2215 * @param {Date} value The minimum date that can be selected
2217 setMinValue : function(dt){
2218 this.minValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
2220 this.menu.picker.setMinDate(this.minValue);
2225 * Replaces any existing <tt>{@link #maxValue}</tt> with the new value and refreshes the DatePicker.
2226 * @param {Date} value The maximum date that can be selected
2228 setMaxValue : function(dt){
2229 this.maxValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
2231 this.menu.picker.setMaxDate(this.maxValue);
2236 * Runs all of NumberFields validations and returns an array of any errors. Note that this first
2237 * runs TextField's validations, so the returned array is an amalgamation of all field errors.
2238 * The additional validation checks are testing that the date format is valid, that the chosen
2239 * date is within the min and max date constraints set, that the date chosen is not in the disabledDates
2240 * regex and that the day chosed is not one of the disabledDays.
2241 * @param {Mixed} value The value to get errors for (defaults to the current field value)
2242 * @return {Array} All validation errors for this field
2244 getErrors: function(value) {
2245 var errors = Ext.form.DateField.superclass.getErrors.apply(this, arguments);
2247 value = this.formatDate(value || this.processValue(this.getRawValue()));
2249 if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
2254 value = this.parseDate(value);
2256 errors.push(String.format(this.invalidText, svalue, this.format));
2260 var time = value.getTime();
2261 if (this.minValue && time < this.minValue.clearTime().getTime()) {
2262 errors.push(String.format(this.minText, this.formatDate(this.minValue)));
2265 if (this.maxValue && time > this.maxValue.clearTime().getTime()) {
2266 errors.push(String.format(this.maxText, this.formatDate(this.maxValue)));
2269 if (this.disabledDays) {
2270 var day = value.getDay();
2272 for(var i = 0; i < this.disabledDays.length; i++) {
2273 if (day === this.disabledDays[i]) {
2274 errors.push(this.disabledDaysText);
2280 var fvalue = this.formatDate(value);
2281 if (this.disabledDatesRE && this.disabledDatesRE.test(fvalue)) {
2282 errors.push(String.format(this.disabledDatesText, fvalue));
2289 // Provides logic to override the default TriggerField.validateBlur which just returns true
2290 validateBlur : function(){
2291 return !this.menu || !this.menu.isVisible();
2295 * Returns the current date value of the date field.
2296 * @return {Date} The date value
2298 getValue : function(){
2299 return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || "";
2303 * Sets the value of the date field. You can pass a date object or any string that can be
2304 * parsed into a valid date, using <tt>{@link #format}</tt> as the date format, according
2305 * to the same rules as {@link Date#parseDate} (the default format used is <tt>"m/d/Y"</tt>).
2308 //All of these calls set the same date value (May 4, 2006)
2310 //Pass a date object:
2311 var dt = new Date('5/4/2006');
2312 dateField.setValue(dt);
2314 //Pass a date string (default format):
2315 dateField.setValue('05/04/2006');
2317 //Pass a date string (custom format):
2318 dateField.format = 'Y-m-d';
2319 dateField.setValue('2006-05-04');
2321 * @param {String/Date} date The date or valid date string
2322 * @return {Ext.form.Field} this
2324 setValue : function(date){
2325 return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
2329 parseDate : function(value) {
2330 if(!value || Ext.isDate(value)){
2334 var v = this.safeParse(value, this.format),
2335 af = this.altFormats,
2336 afa = this.altFormatsArray;
2339 afa = afa || af.split("|");
2341 for (var i = 0, len = afa.length; i < len && !v; i++) {
2342 v = this.safeParse(value, afa[i]);
2349 onDestroy : function(){
2350 Ext.destroy(this.menu, this.keyNav);
2351 Ext.form.DateField.superclass.onDestroy.call(this);
2355 formatDate : function(date){
2356 return Ext.isDate(date) ? date.dateFormat(this.format) : date;
2360 * @method onTriggerClick
2364 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
2365 onTriggerClick : function(){
2369 if(this.menu == null){
2370 this.menu = new Ext.menu.DateMenu({
2372 focusOnSelect: false
2376 Ext.apply(this.menu.picker, {
2377 minDate : this.minValue,
2378 maxDate : this.maxValue,
2379 disabledDatesRE : this.disabledDatesRE,
2380 disabledDatesText : this.disabledDatesText,
2381 disabledDays : this.disabledDays,
2382 disabledDaysText : this.disabledDaysText,
2383 format : this.format,
2384 showToday : this.showToday,
2385 startDay: this.startDay,
2386 minText : String.format(this.minText, this.formatDate(this.minValue)),
2387 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
2389 this.menu.picker.setValue(this.getValue() || new Date());
2390 this.menu.show(this.el, "tl-bl?");
2391 this.menuEvents('on');
2395 menuEvents: function(method){
2396 this.menu[method]('select', this.onSelect, this);
2397 this.menu[method]('hide', this.onMenuHide, this);
2398 this.menu[method]('show', this.onFocus, this);
2401 onSelect: function(m, d){
2403 this.fireEvent('select', this, d);
2407 onMenuHide: function(){
2408 this.focus(false, 60);
2409 this.menuEvents('un');
2413 beforeBlur : function(){
2414 var v = this.parseDate(this.getRawValue());
2421 * @cfg {Boolean} grow @hide
2424 * @cfg {Number} growMin @hide
2427 * @cfg {Number} growMax @hide
2434 Ext.reg('datefield', Ext.form.DateField);
2436 * @class Ext.form.DisplayField
2437 * @extends Ext.form.Field
2438 * A display-only text field which is not validated and not submitted.
2440 * Creates a new DisplayField.
2441 * @param {Object} config Configuration options
2442 * @xtype displayfield
2444 Ext.form.DisplayField = Ext.extend(Ext.form.Field, {
2445 validationEvent : false,
2446 validateOnBlur : false,
2447 defaultAutoCreate : {tag: "div"},
2449 * @cfg {String} fieldClass The default CSS class for the field (defaults to <tt>"x-form-display-field"</tt>)
2451 fieldClass : "x-form-display-field",
2453 * @cfg {Boolean} htmlEncode <tt>false</tt> to skip HTML-encoding the text when rendering it (defaults to
2454 * <tt>false</tt>). This might be useful if you want to include tags in the field's innerHTML rather than
2455 * rendering them as string literals per the default logic.
2460 initEvents : Ext.emptyFn,
2462 isValid : function(){
2466 validate : function(){
2470 getRawValue : function(){
2471 var v = this.rendered ? this.el.dom.innerHTML : Ext.value(this.value, '');
2472 if(v === this.emptyText){
2475 if(this.htmlEncode){
2476 v = Ext.util.Format.htmlDecode(v);
2481 getValue : function(){
2482 return this.getRawValue();
2485 getName: function() {
2489 setRawValue : function(v){
2490 if(this.htmlEncode){
2491 v = Ext.util.Format.htmlEncode(v);
2493 return this.rendered ? (this.el.dom.innerHTML = (Ext.isEmpty(v) ? '' : v)) : (this.value = v);
2496 setValue : function(v){
2497 this.setRawValue(v);
2501 * @cfg {String} inputType
2505 * @cfg {Boolean} disabled
2509 * @cfg {Boolean} readOnly
2513 * @cfg {Boolean} validateOnBlur
2517 * @cfg {Number} validationDelay
2521 * @cfg {String/Boolean} validationEvent
2526 Ext.reg('displayfield', Ext.form.DisplayField);
2528 * @class Ext.form.ComboBox
2529 * @extends Ext.form.TriggerField
2530 * <p>A combobox control with support for autocomplete, remote-loading, paging and many other features.</p>
2531 * <p>A ComboBox works in a similar manner to a traditional HTML <select> field. The difference is
2532 * that to submit the {@link #valueField}, you must specify a {@link #hiddenName} to create a hidden input
2533 * field to hold the value of the valueField. The <i>{@link #displayField}</i> is shown in the text field
2534 * which is named according to the {@link #name}.</p>
2535 * <p><b><u>Events</u></b></p>
2536 * <p>To do something when something in ComboBox is selected, configure the select event:<pre><code>
2537 var cb = new Ext.form.ComboBox({
2538 // all of your config options
2541 'select': yourFunction
2545 // Alternatively, you can assign events after the object is created:
2546 var cb = new Ext.form.ComboBox(yourOptions);
2547 cb.on('select', yourFunction, yourScope);
2550 * <p><b><u>ComboBox in Grid</u></b></p>
2551 * <p>If using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a {@link Ext.grid.Column#renderer renderer}
2552 * will be needed to show the displayField when the editor is not active. Set up the renderer manually, or implement
2553 * a reusable render, for example:<pre><code>
2554 // create reusable renderer
2555 Ext.util.Format.comboRenderer = function(combo){
2556 return function(value){
2557 var record = combo.findRecord(combo.{@link #valueField}, value);
2558 return record ? record.get(combo.{@link #displayField}) : combo.{@link #valueNotFoundText};
2562 // create the combo instance
2563 var combo = new Ext.form.ComboBox({
2564 {@link #typeAhead}: true,
2565 {@link #triggerAction}: 'all',
2566 {@link #lazyRender}:true,
2567 {@link #mode}: 'local',
2568 {@link #store}: new Ext.data.ArrayStore({
2574 data: [[1, 'item1'], [2, 'item2']]
2576 {@link #valueField}: 'myId',
2577 {@link #displayField}: 'displayText'
2580 // snippet of column model used within grid
2581 var cm = new Ext.grid.ColumnModel([{
2584 header: "Some Header",
2585 dataIndex: 'whatever',
2587 editor: combo, // specify reference to combo instance
2588 renderer: Ext.util.Format.comboRenderer(combo) // pass combo instance to reusable renderer
2594 * <p><b><u>Filtering</u></b></p>
2595 * <p>A ComboBox {@link #doQuery uses filtering itself}, for information about filtering the ComboBox
2596 * store manually see <tt>{@link #lastQuery}</tt>.</p>
2598 * Create a new ComboBox.
2599 * @param {Object} config Configuration options
2602 Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, {
2604 * @cfg {Mixed} transform The id, DOM node or element of an existing HTML SELECT to convert to a ComboBox.
2605 * Note that if you specify this and the combo is going to be in an {@link Ext.form.BasicForm} or
2606 * {@link Ext.form.FormPanel}, you must also set <tt>{@link #lazyRender} = true</tt>.
2609 * @cfg {Boolean} lazyRender <tt>true</tt> to prevent the ComboBox from rendering until requested
2610 * (should always be used when rendering into an {@link Ext.Editor} (e.g. {@link Ext.grid.EditorGridPanel Grids}),
2611 * defaults to <tt>false</tt>).
2614 * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or <tt>true</tt> for a default
2615 * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
2616 * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
2617 * <pre><code>{tag: "input", type: "text", size: "24", autocomplete: "off"}</code></pre>
2620 * @cfg {Ext.data.Store/Array} store The data source to which this combo is bound (defaults to <tt>undefined</tt>).
2621 * Acceptable values for this property are:
2622 * <div class="mdetail-params"><ul>
2623 * <li><b>any {@link Ext.data.Store Store} subclass</b></li>
2624 * <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally,
2625 * automatically generating {@link Ext.data.Field#name field names} to work with all data components.
2626 * <div class="mdetail-params"><ul>
2627 * <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
2628 * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo
2629 * {@link #valueField} and {@link #displayField})</div></li>
2630 * <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
2631 * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
2632 * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}.
2633 * </div></li></ul></div></li></ul></div>
2634 * <p>See also <tt>{@link #mode}</tt>.</p>
2637 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
2638 * the dropdown list (defaults to undefined, with no header element)
2642 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
2644 * @cfg {Number} listWidth The width (used as a parameter to {@link Ext.Element#setWidth}) of the dropdown
2645 * list (defaults to the width of the ComboBox field). See also <tt>{@link #minListWidth}
2648 * @cfg {String} displayField The underlying {@link Ext.data.Field#name data field name} to bind to this
2649 * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field1'</tt> if
2650 * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
2651 * the store configuration}).
2652 * <p>See also <tt>{@link #valueField}</tt>.</p>
2653 * <p><b>Note</b>: if using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a
2654 * {@link Ext.grid.Column#renderer renderer} will be needed to show the displayField when the editor is not
2658 * @cfg {String} valueField The underlying {@link Ext.data.Field#name data value name} to bind to this
2659 * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field2'</tt> if
2660 * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
2661 * the store configuration}).
2662 * <p><b>Note</b>: use of a <tt>valueField</tt> requires the user to make a selection in order for a value to be
2663 * mapped. See also <tt>{@link #hiddenName}</tt>, <tt>{@link #hiddenValue}</tt>, and <tt>{@link #displayField}</tt>.</p>
2666 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
2667 * field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically
2668 * post during a form submission. See also {@link #valueField}.
2671 * @cfg {String} hiddenId If <tt>{@link #hiddenName}</tt> is specified, <tt>hiddenId</tt> can also be provided
2672 * to give the hidden field a unique id. The <tt>hiddenId</tt> and combo {@link Ext.Component#id id} should be
2673 * different, since no two DOM nodes should share the same id.
2676 * @cfg {String} hiddenValue Sets the initial value of the hidden field if {@link #hiddenName} is
2677 * specified to contain the selected {@link #valueField}, from the Store. Defaults to the configured
2678 * <tt>{@link Ext.form.Field#value value}</tt>.
2681 * @cfg {String} listClass The CSS class to add to the predefined <tt>'x-combo-list'</tt> class
2682 * applied the dropdown list element (defaults to '').
2686 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list
2687 * (defaults to <tt>'x-combo-selected'</tt>)
2689 selectedClass : 'x-combo-selected',
2691 * @cfg {String} listEmptyText The empty text to display in the data view if no items are found.
2696 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always
2697 * get the class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
2698 * (defaults to <tt>'x-form-arrow-trigger'</tt> which displays a downward arrow icon).
2700 triggerClass : 'x-form-arrow-trigger',
2702 * @cfg {Boolean/String} shadow <tt>true</tt> or <tt>"sides"</tt> for the default effect, <tt>"frame"</tt> for
2703 * 4-way shadow, and <tt>"drop"</tt> for bottom-right
2707 * @cfg {String/Array} listAlign A valid anchor position value. See <tt>{@link Ext.Element#alignTo}</tt> for details
2708 * on supported anchor positions and offsets. To specify x/y offsets as well, this value
2709 * may be specified as an Array of <tt>{@link Ext.Element#alignTo}</tt> method arguments.</p>
2710 * <pre><code>[ 'tl-bl?', [6,0] ]</code></pre>(defaults to <tt>'tl-bl?'</tt>)
2712 listAlign : 'tl-bl?',
2714 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown
2715 * (defaults to <tt>300</tt>)
2719 * @cfg {Number} minHeight The minimum height in pixels of the dropdown list when the list is constrained by its
2720 * distance to the viewport edges (defaults to <tt>90</tt>)
2724 * @cfg {String} triggerAction The action to execute when the trigger is clicked.
2725 * <div class="mdetail-params"><ul>
2726 * <li><b><tt>'query'</tt></b> : <b>Default</b>
2727 * <p class="sub-desc">{@link #doQuery run the query} using the {@link Ext.form.Field#getRawValue raw value}.</p></li>
2728 * <li><b><tt>'all'</tt></b> :
2729 * <p class="sub-desc">{@link #doQuery run the query} specified by the <tt>{@link #allQuery}</tt> config option</p></li>
2731 * <p>See also <code>{@link #queryParam}</code>.</p>
2733 triggerAction : 'query',
2735 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and
2736 * {@link #typeAhead} activate (defaults to <tt>4</tt> if <tt>{@link #mode} = 'remote'</tt> or <tt>0</tt> if
2737 * <tt>{@link #mode} = 'local'</tt>, does not apply if
2738 * <tt>{@link Ext.form.TriggerField#editable editable} = false</tt>).
2742 * @cfg {Boolean} autoSelect <tt>true</tt> to select the first result gathered by the data store (defaults
2743 * to <tt>true</tt>). A false value would require a manual selection from the dropdown list to set the components value
2744 * unless the value of ({@link #typeAheadDelay}) were true.
2748 * @cfg {Boolean} typeAhead <tt>true</tt> to populate and autoselect the remainder of the text being
2749 * typed after a configurable delay ({@link #typeAheadDelay}) if it matches a known value (defaults
2750 * to <tt>false</tt>)
2754 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and
2755 * sending the query to filter the dropdown list (defaults to <tt>500</tt> if <tt>{@link #mode} = 'remote'</tt>
2756 * or <tt>10</tt> if <tt>{@link #mode} = 'local'</tt>)
2760 * @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.PagingToolbar} is displayed in the
2761 * footer of the dropdown list and the {@link #doQuery filter queries} will execute with page start and
2762 * {@link Ext.PagingToolbar#pageSize limit} parameters. Only applies when <tt>{@link #mode} = 'remote'</tt>
2763 * (defaults to <tt>0</tt>).
2767 * @cfg {Boolean} selectOnFocus <tt>true</tt> to select any existing text in the field immediately on focus.
2768 * Only applies when <tt>{@link Ext.form.TriggerField#editable editable} = true</tt> (defaults to
2771 selectOnFocus : false,
2773 * @cfg {String} queryParam Name of the query ({@link Ext.data.Store#baseParam baseParam} name for the store)
2774 * as it will be passed on the querystring (defaults to <tt>'query'</tt>)
2776 queryParam : 'query',
2778 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
2779 * when <tt>{@link #mode} = 'remote'</tt> (defaults to <tt>'Loading...'</tt>)
2781 loadingText : 'Loading...',
2783 * @cfg {Boolean} resizable <tt>true</tt> to add a resize handle to the bottom of the dropdown list
2784 * (creates an {@link Ext.Resizable} with 'se' {@link Ext.Resizable#pinned pinned} handles).
2785 * Defaults to <tt>false</tt>.
2789 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if
2790 * <tt>{@link #resizable} = true</tt> (defaults to <tt>8</tt>)
2794 * @cfg {String} allQuery The text query to send to the server to return all records for the list
2795 * with no filtering (defaults to '')
2799 * @cfg {String} mode Acceptable values are:
2800 * <div class="mdetail-params"><ul>
2801 * <li><b><tt>'remote'</tt></b> : <b>Default</b>
2802 * <p class="sub-desc">Automatically loads the <tt>{@link #store}</tt> the <b>first</b> time the trigger
2803 * is clicked. If you do not want the store to be automatically loaded the first time the trigger is
2804 * clicked, set to <tt>'local'</tt> and manually load the store. To force a requery of the store
2805 * <b>every</b> time the trigger is clicked see <tt>{@link #lastQuery}</tt>.</p></li>
2806 * <li><b><tt>'local'</tt></b> :
2807 * <p class="sub-desc">ComboBox loads local data</p>
2809 var combo = new Ext.form.ComboBox({
2810 renderTo: document.body,
2812 store: new Ext.data.ArrayStore({
2815 'myId', // numeric value is the key
2818 data: [[1, 'item1'], [2, 'item2']] // data is local
2821 displayField: 'displayText',
2822 triggerAction: 'all'
2824 * </code></pre></li>
2829 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to <tt>70</tt>, will
2830 * be ignored if <tt>{@link #listWidth}</tt> has a higher value)
2834 * @cfg {Boolean} forceSelection <tt>true</tt> to restrict the selected value to one of the values in the list,
2835 * <tt>false</tt> to allow the user to set arbitrary text into the field (defaults to <tt>false</tt>)
2837 forceSelection : false,
2839 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
2840 * if <tt>{@link #typeAhead} = true</tt> (defaults to <tt>250</tt>)
2842 typeAheadDelay : 250,
2844 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
2845 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
2846 * default text is used, it means there is no value set and no validation will occur on this field.
2850 * @cfg {Boolean} lazyInit <tt>true</tt> to not initialize the list for this combo until the field is focused
2851 * (defaults to <tt>true</tt>)
2856 * @cfg {Boolean} clearFilterOnReset <tt>true</tt> to clear any filters on the store (when in local mode) when reset is called
2857 * (defaults to <tt>true</tt>)
2859 clearFilterOnReset : true,
2862 * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
2863 * If a hiddenName is specified, setting this to true will cause both the hidden field and the element to be submitted.
2864 * Defaults to <tt>undefined</tt>.
2866 submitValue: undefined,
2869 * The value of the match string used to filter the store. Delete this property to force a requery.
2872 var combo = new Ext.form.ComboBox({
2877 // delete the previous query in the beforequery event or set
2878 // combo.lastQuery = null (this will reload the store the next time it expands)
2879 beforequery: function(qe){
2880 delete qe.combo.lastQuery;
2885 * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used
2886 * configure the combo with <tt>lastQuery=''</tt>. Example use:
2888 var combo = new Ext.form.ComboBox({
2891 triggerAction: 'all',
2895 * @property lastQuery
2900 initComponent : function(){
2901 Ext.form.ComboBox.superclass.initComponent.call(this);
2905 * Fires when the dropdown list is expanded
2906 * @param {Ext.form.ComboBox} combo This combo box
2911 * Fires when the dropdown list is collapsed
2912 * @param {Ext.form.ComboBox} combo This combo box
2917 * @event beforeselect
2918 * Fires before a list item is selected. Return false to cancel the selection.
2919 * @param {Ext.form.ComboBox} combo This combo box
2920 * @param {Ext.data.Record} record The data record returned from the underlying store
2921 * @param {Number} index The index of the selected item in the dropdown list
2926 * Fires when a list item is selected
2927 * @param {Ext.form.ComboBox} combo This combo box
2928 * @param {Ext.data.Record} record The data record returned from the underlying store
2929 * @param {Number} index The index of the selected item in the dropdown list
2933 * @event beforequery
2934 * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
2935 * cancel property to true.
2936 * @param {Object} queryEvent An object that has these properties:<ul>
2937 * <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">This combo box</div></li>
2938 * <li><code>query</code> : String <div class="sub-desc">The query</div></li>
2939 * <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li>
2940 * <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li>
2946 var s = Ext.getDom(this.transform);
2947 if(!this.hiddenName){
2948 this.hiddenName = s.name;
2951 this.mode = 'local';
2952 var d = [], opts = s.options;
2953 for(var i = 0, len = opts.length;i < len; i++){
2955 value = (o.hasAttribute ? o.hasAttribute('value') : o.getAttributeNode('value').specified) ? o.value : o.text;
2956 if(o.selected && Ext.isEmpty(this.value, true)) {
2959 d.push([value, o.text]);
2961 this.store = new Ext.data.ArrayStore({
2963 fields: ['value', 'text'],
2967 this.valueField = 'value';
2968 this.displayField = 'text';
2970 s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
2971 if(!this.lazyRender){
2973 this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
2974 this.render(this.el.parentNode, s);
2978 //auto-configure store from local array data
2979 else if(this.store){
2980 this.store = Ext.StoreMgr.lookup(this.store);
2981 if(this.store.autoCreated){
2982 this.displayField = this.valueField = 'field1';
2983 if(!this.store.expandData){
2984 this.displayField = 'field2';
2986 this.mode = 'local';
2990 this.selectedIndex = -1;
2991 if(this.mode == 'local'){
2992 if(!Ext.isDefined(this.initialConfig.queryDelay)){
2993 this.queryDelay = 10;
2995 if(!Ext.isDefined(this.initialConfig.minChars)){
3002 onRender : function(ct, position){
3003 if(this.hiddenName && !Ext.isDefined(this.submitValue)){
3004 this.submitValue = false;
3006 Ext.form.ComboBox.superclass.onRender.call(this, ct, position);
3007 if(this.hiddenName){
3008 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
3009 id: (this.hiddenId || Ext.id())}, 'before', true);
3013 this.el.dom.setAttribute('autocomplete', 'off');
3019 this.on('focus', this.initList, this, {single: true});
3024 initValue : function(){
3025 Ext.form.ComboBox.superclass.initValue.call(this);
3026 if(this.hiddenField){
3027 this.hiddenField.value =
3028 Ext.value(Ext.isDefined(this.hiddenValue) ? this.hiddenValue : this.value, '');
3032 getParentZIndex : function(){
3035 this.findParentBy(function(ct){
3036 zindex = parseInt(ct.getPositionEl().getStyle('z-index'), 10);
3043 getZIndex : function(listParent){
3044 listParent = listParent || Ext.getDom(this.getListParent() || Ext.getBody());
3045 var zindex = parseInt(Ext.fly(listParent).getStyle('z-index'), 10);
3047 zindex = this.getParentZIndex();
3049 return (zindex || 12000) + 5;
3053 initList : function(){
3055 var cls = 'x-combo-list',
3056 listParent = Ext.getDom(this.getListParent() || Ext.getBody());
3058 this.list = new Ext.Layer({
3059 parentEl: listParent,
3060 shadow: this.shadow,
3061 cls: [cls, this.listClass].join(' '),
3063 zindex: this.getZIndex(listParent)
3066 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
3067 this.list.setSize(lw, 0);
3068 this.list.swallowEvent('mousewheel');
3069 this.assetHeight = 0;
3070 if(this.syncFont !== false){
3071 this.list.setStyle('font-size', this.el.getStyle('font-size'));
3074 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
3075 this.assetHeight += this.header.getHeight();
3078 this.innerList = this.list.createChild({cls:cls+'-inner'});
3079 this.mon(this.innerList, 'mouseover', this.onViewOver, this);
3080 this.mon(this.innerList, 'mousemove', this.onViewMove, this);
3081 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
3084 this.footer = this.list.createChild({cls:cls+'-ft'});
3085 this.pageTb = new Ext.PagingToolbar({
3087 pageSize: this.pageSize,
3088 renderTo:this.footer
3090 this.assetHeight += this.footer.getHeight();
3095 * @cfg {String/Ext.XTemplate} tpl <p>The template string, or {@link Ext.XTemplate} instance to
3096 * use to display each item in the dropdown list. The dropdown list is displayed in a
3097 * DataView. See {@link #view}.</p>
3098 * <p>The default template string is:</p><pre><code>
3099 '<tpl for="."><div class="x-combo-list-item">{' + this.displayField + '}</div></tpl>'
3101 * <p>Override the default value to create custom UI layouts for items in the list.
3102 * For example:</p><pre><code>
3103 '<tpl for="."><div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}</div></tpl>'
3105 * <p>The template <b>must</b> contain one or more substitution parameters using field
3106 * names from the Combo's</b> {@link #store Store}. In the example above an
3107 * <pre>ext:qtip</pre> attribute is added to display other fields from the Store.</p>
3108 * <p>To preserve the default visual look of list items, add the CSS class name
3109 * <pre>x-combo-list-item</pre> to the template's container element.</p>
3110 * <p>Also see {@link #itemSelector} for additional details.</p>
3112 this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
3114 * @cfg {String} itemSelector
3115 * <p>A simple CSS selector (e.g. div.some-class or span:first-child) that will be
3116 * used to determine what nodes the {@link #view Ext.DataView} which handles the dropdown
3117 * display will be working with.</p>
3118 * <p><b>Note</b>: this setting is <b>required</b> if a custom XTemplate has been
3119 * specified in {@link #tpl} which assigns a class other than <pre>'x-combo-list-item'</pre>
3120 * to dropdown list items</b>
3125 * The {@link Ext.DataView DataView} used to display the ComboBox's options.
3126 * @type Ext.DataView
3128 this.view = new Ext.DataView({
3129 applyTo: this.innerList,
3132 selectedClass: this.selectedClass,
3133 itemSelector: this.itemSelector || '.' + cls + '-item',
3134 emptyText: this.listEmptyText,
3135 deferEmptyText: false
3138 this.mon(this.view, {
3139 containerclick : this.onViewClick,
3140 click : this.onViewClick,
3144 this.bindStore(this.store, true);
3147 this.resizer = new Ext.Resizable(this.list, {
3148 pinned:true, handles:'se'
3150 this.mon(this.resizer, 'resize', function(r, w, h){
3151 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
3153 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
3154 this.restrictHeight();
3157 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
3163 * <p>Returns the element used to house this ComboBox's pop-up list. Defaults to the document body.</p>
3164 * A custom implementation may be provided as a configuration option if the floating list needs to be rendered
3165 * to a different Element. An example might be rendering the list inside a Menu so that clicking
3166 * the list does not hide the Menu:<pre><code>
3167 var store = new Ext.data.ArrayStore({
3169 fields: ['initials', 'fullname'],
3171 ['FF', 'Fred Flintstone'],
3172 ['BR', 'Barney Rubble']
3176 var combo = new Ext.form.ComboBox({
3178 displayField: 'fullname',
3179 emptyText: 'Select a name...',
3180 forceSelection: true,
3181 getListParent: function() {
3182 return this.el.up('.x-menu');
3184 iconCls: 'no-icon', //use iconCls if placing within menu to shift to right side of menu
3186 selectOnFocus: true,
3187 triggerAction: 'all',
3192 var menu = new Ext.menu.Menu({
3195 combo // A Field in a Menu
3200 getListParent : function() {
3201 return document.body;
3205 * Returns the store associated with this combo.
3206 * @return {Ext.data.Store} The store
3208 getStore : function(){
3213 bindStore : function(store, initial){
3214 if(this.store && !initial){
3215 if(this.store !== store && this.store.autoDestroy){
3216 this.store.destroy();
3218 this.store.un('beforeload', this.onBeforeLoad, this);
3219 this.store.un('load', this.onLoad, this);
3220 this.store.un('exception', this.collapse, this);
3225 this.view.bindStore(null);
3228 this.pageTb.bindStore(null);
3234 this.lastQuery = null;
3236 this.pageTb.bindStore(store);
3240 this.store = Ext.StoreMgr.lookup(store);
3243 beforeload: this.onBeforeLoad,
3245 exception: this.collapse
3249 this.view.bindStore(store);
3255 if(this.clearFilterOnReset && this.mode == 'local'){
3256 this.store.clearFilter();
3258 Ext.form.ComboBox.superclass.reset.call(this);
3262 initEvents : function(){
3263 Ext.form.ComboBox.superclass.initEvents.call(this);
3268 * <p>A {@link Ext.KeyNav KeyNav} object which handles navigation keys for this ComboBox. This performs actions
3269 * based on keystrokes typed when the input field is focused.</p>
3270 * <p><b>After the ComboBox has been rendered</b>, you may override existing navigation key functionality,
3271 * or add your own based upon key names as specified in the {@link Ext.KeyNav KeyNav} class.</p>
3272 * <p>The function is executed in the scope (<code>this</code> reference of the ComboBox. Example:</p><pre><code>
3273 myCombo.keyNav.esc = function(e) { // Override ESC handling function
3274 this.collapse(); // Standard behaviour of Ext's ComboBox.
3275 this.setValue(this.startValue); // We reset to starting value on ESC
3277 myCombo.keyNav.tab = function() { // Override TAB handling function
3278 this.onViewClick(false); // Select the currently highlighted row
3282 this.keyNav = new Ext.KeyNav(this.el, {
3284 this.inKeyMode = true;
3288 "down" : function(e){
3289 if(!this.isExpanded()){
3290 this.onTriggerClick();
3292 this.inKeyMode = true;
3297 "enter" : function(e){
3301 "esc" : function(e){
3305 "tab" : function(e){
3306 if (this.forceSelection === true) {
3309 this.onViewClick(false);
3316 doRelay : function(e, h, hname){
3317 if(hname == 'down' || this.scope.isExpanded()){
3318 // this MUST be called before ComboBox#fireKey()
3319 var relay = Ext.KeyNav.prototype.doRelay.apply(this, arguments);
3320 if(!Ext.isIE && Ext.EventManager.useKeydown){
3321 // call Combo#fireKey() for browsers which use keydown event (except IE)
3322 this.scope.fireKey(e);
3329 forceKeyDown : true,
3330 defaultEventAction: 'stopEvent'
3332 this.queryDelay = Math.max(this.queryDelay || 10,
3333 this.mode == 'local' ? 10 : 250);
3334 this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
3336 this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
3338 if(!this.enableKeyEvents){
3339 this.mon(this.el, 'keyup', this.onKeyUp, this);
3345 onDestroy : function(){
3347 this.dqTask.cancel();
3350 this.bindStore(null);
3357 Ext.destroyMembers(this, 'hiddenField');
3358 Ext.form.ComboBox.superclass.onDestroy.call(this);
3362 fireKey : function(e){
3363 if (!this.isExpanded()) {
3364 Ext.form.ComboBox.superclass.fireKey.call(this, e);
3369 onResize : function(w, h){
3370 Ext.form.ComboBox.superclass.onResize.apply(this, arguments);
3371 if(!isNaN(w) && this.isVisible() && this.list){
3374 this.bufferSize = w;
3378 doResize: function(w){
3379 if(!Ext.isDefined(this.listWidth)){
3380 var lw = Math.max(w, this.minListWidth);
3381 this.list.setWidth(lw);
3382 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
3387 onEnable : function(){
3388 Ext.form.ComboBox.superclass.onEnable.apply(this, arguments);
3389 if(this.hiddenField){
3390 this.hiddenField.disabled = false;
3395 onDisable : function(){
3396 Ext.form.ComboBox.superclass.onDisable.apply(this, arguments);
3397 if(this.hiddenField){
3398 this.hiddenField.disabled = true;
3403 onBeforeLoad : function(){
3407 this.innerList.update(this.loadingText ?
3408 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
3409 this.restrictHeight();
3410 this.selectedIndex = -1;
3414 onLoad : function(){
3418 if(this.store.getCount() > 0 || this.listEmptyText){
3420 this.restrictHeight();
3421 if(this.lastQuery == this.allQuery){
3423 this.el.dom.select();
3426 if(this.autoSelect !== false && !this.selectByValue(this.value, true)){
3427 this.select(0, true);
3430 if(this.autoSelect !== false){
3433 if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
3434 this.taTask.delay(this.typeAheadDelay);
3444 onTypeAhead : function(){
3445 if(this.store.getCount() > 0){
3446 var r = this.store.getAt(0);
3447 var newValue = r.data[this.displayField];
3448 var len = newValue.length;
3449 var selStart = this.getRawValue().length;
3450 if(selStart != len){
3451 this.setRawValue(newValue);
3452 this.selectText(selStart, newValue.length);
3458 assertValue : function(){
3459 var val = this.getRawValue(),
3460 rec = this.findRecord(this.displayField, val);
3462 if(!rec && this.forceSelection){
3463 if(val.length > 0 && val != this.emptyText){
3464 this.el.dom.value = Ext.value(this.lastSelectionText, '');
3465 this.applyEmptyText();
3471 // onSelect may have already set the value and by doing so
3472 // set the display field properly. Let's not wipe out the
3473 // valueField here by just sending the displayField.
3474 if (val == rec.get(this.displayField) && this.value == rec.get(this.valueField)){
3477 val = rec.get(this.valueField || this.displayField);
3484 onSelect : function(record, index){
3485 if(this.fireEvent('beforeselect', this, record, index) !== false){
3486 this.setValue(record.data[this.valueField || this.displayField]);
3488 this.fireEvent('select', this, record, index);
3493 getName: function(){
3494 var hf = this.hiddenField;
3495 return hf && hf.name ? hf.name : this.hiddenName || Ext.form.ComboBox.superclass.getName.call(this);
3499 * Returns the currently selected field value or empty string if no value is set.
3500 * @return {String} value The selected value
3502 getValue : function(){
3503 if(this.valueField){
3504 return Ext.isDefined(this.value) ? this.value : '';
3506 return Ext.form.ComboBox.superclass.getValue.call(this);
3511 * Clears any text/value currently set in the field
3513 clearValue : function(){
3514 if(this.hiddenField){
3515 this.hiddenField.value = '';
3517 this.setRawValue('');
3518 this.lastSelectionText = '';
3519 this.applyEmptyText();
3524 * Sets the specified value into the field. If the value finds a match, the corresponding record text
3525 * will be displayed in the field. If the value does not match the data value of an existing item,
3526 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
3527 * Otherwise the field will be blank (although the value will still be set).
3528 * @param {String} value The value to match
3529 * @return {Ext.form.Field} this
3531 setValue : function(v){
3533 if(this.valueField){
3534 var r = this.findRecord(this.valueField, v);
3536 text = r.data[this.displayField];
3537 }else if(Ext.isDefined(this.valueNotFoundText)){
3538 text = this.valueNotFoundText;
3541 this.lastSelectionText = text;
3542 if(this.hiddenField){
3543 this.hiddenField.value = Ext.value(v, '');
3545 Ext.form.ComboBox.superclass.setValue.call(this, text);
3551 findRecord : function(prop, value){
3553 if(this.store.getCount() > 0){
3554 this.store.each(function(r){
3555 if(r.data[prop] == value){
3565 onViewMove : function(e, t){
3566 this.inKeyMode = false;
3570 onViewOver : function(e, t){
3571 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
3574 var item = this.view.findItemFromChild(t);
3576 var index = this.view.indexOf(item);
3577 this.select(index, false);
3582 onViewClick : function(doFocus){
3583 var index = this.view.getSelectedIndexes()[0],
3587 this.onSelect(r, index);
3591 if(doFocus !== false){
3598 restrictHeight : function(){
3599 this.innerList.dom.style.height = '';
3600 var inner = this.innerList.dom,
3601 pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight,
3602 h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight),
3603 ha = this.getPosition()[1]-Ext.getBody().getScroll().top,
3604 hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,
3605 space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
3607 h = Math.min(h, space, this.maxHeight);
3609 this.innerList.setHeight(h);
3610 this.list.beginUpdate();
3611 this.list.setHeight(h+pad);
3612 this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
3613 this.list.endUpdate();
3617 * Returns true if the dropdown list is expanded, else false.
3619 isExpanded : function(){
3620 return this.list && this.list.isVisible();
3624 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
3625 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
3626 * @param {String} value The data value of the item to select
3627 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
3628 * selected item if it is not currently in view (defaults to true)
3629 * @return {Boolean} True if the value matched an item in the list, else false
3631 selectByValue : function(v, scrollIntoView){
3632 if(!Ext.isEmpty(v, true)){
3633 var r = this.findRecord(this.valueField || this.displayField, v);
3635 this.select(this.store.indexOf(r), scrollIntoView);
3643 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
3644 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
3645 * @param {Number} index The zero-based index of the list item to select
3646 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
3647 * selected item if it is not currently in view (defaults to true)
3649 select : function(index, scrollIntoView){
3650 this.selectedIndex = index;
3651 this.view.select(index);
3652 if(scrollIntoView !== false){
3653 var el = this.view.getNode(index);
3655 this.innerList.scrollChildIntoView(el, false);
3662 selectNext : function(){
3663 var ct = this.store.getCount();
3665 if(this.selectedIndex == -1){
3667 }else if(this.selectedIndex < ct-1){
3668 this.select(this.selectedIndex+1);
3674 selectPrev : function(){
3675 var ct = this.store.getCount();
3677 if(this.selectedIndex == -1){
3679 }else if(this.selectedIndex !== 0){
3680 this.select(this.selectedIndex-1);
3686 onKeyUp : function(e){
3688 if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){
3691 this.dqTask.delay(this.queryDelay);
3693 Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
3697 validateBlur : function(){
3698 return !this.list || !this.list.isVisible();
3702 initQuery : function(){
3703 this.doQuery(this.getRawValue());
3707 beforeBlur : function(){
3712 postBlur : function(){
3713 Ext.form.ComboBox.superclass.postBlur.call(this);
3715 this.inKeyMode = false;
3719 * Execute a query to filter the dropdown list. Fires the {@link #beforequery} event prior to performing the
3720 * query allowing the query action to be canceled if needed.
3721 * @param {String} query The SQL query to execute
3722 * @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
3723 * characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option. It
3724 * also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
3726 doQuery : function(q, forceAll){
3727 q = Ext.isEmpty(q) ? '' : q;
3734 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
3738 forceAll = qe.forceAll;
3739 if(forceAll === true || (q.length >= this.minChars)){
3740 if(this.lastQuery !== q){
3742 if(this.mode == 'local'){
3743 this.selectedIndex = -1;
3745 this.store.clearFilter();
3747 this.store.filter(this.displayField, q);
3751 this.store.baseParams[this.queryParam] = q;
3753 params: this.getParams(q)
3758 this.selectedIndex = -1;
3765 getParams : function(q){
3767 paramNames = this.store.paramNames;
3769 params[paramNames.start] = 0;
3770 params[paramNames.limit] = this.pageSize;
3776 * Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
3778 collapse : function(){
3779 if(!this.isExpanded()){
3783 Ext.getDoc().un('mousewheel', this.collapseIf, this);
3784 Ext.getDoc().un('mousedown', this.collapseIf, this);
3785 this.fireEvent('collapse', this);
3789 collapseIf : function(e){
3790 if(!this.isDestroyed && !e.within(this.wrap) && !e.within(this.list)){
3796 * Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
3798 expand : function(){
3799 if(this.isExpanded() || !this.hasFocus){
3803 if(this.title || this.pageSize){
3804 this.assetHeight = 0;
3806 this.assetHeight += this.header.getHeight();
3809 this.assetHeight += this.footer.getHeight();
3813 if(this.bufferSize){
3814 this.doResize(this.bufferSize);
3815 delete this.bufferSize;
3817 this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
3819 // zindex can change, re-check it and set it if necessary
3820 this.list.setZIndex(this.getZIndex());
3823 this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
3825 this.mon(Ext.getDoc(), {
3827 mousewheel: this.collapseIf,
3828 mousedown: this.collapseIf
3830 this.fireEvent('expand', this);
3834 * @method onTriggerClick
3838 // Implements the default empty TriggerField.onTriggerClick function
3839 onTriggerClick : function(){
3840 if(this.readOnly || this.disabled){
3843 if(this.isExpanded()){
3848 if(this.triggerAction == 'all') {
3849 this.doQuery(this.allQuery, true);
3851 this.doQuery(this.getRawValue());
3862 * @cfg {Boolean} grow @hide
3865 * @cfg {Number} growMin @hide
3868 * @cfg {Number} growMax @hide
3872 Ext.reg('combo', Ext.form.ComboBox);
3874 * @class Ext.form.Checkbox
3875 * @extends Ext.form.Field
3876 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
3878 * Creates a new Checkbox
3879 * @param {Object} config Configuration options
3882 Ext.form.Checkbox = Ext.extend(Ext.form.Field, {
3884 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
3886 focusClass : undefined,
3888 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to 'x-form-field')
3890 fieldClass : 'x-form-field',
3892 * @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>)
3896 * @cfg {String} boxLabel The text that appears beside the checkbox
3900 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
3901 * {tag: 'input', type: 'checkbox', autocomplete: 'off'})
3903 defaultAutoCreate : { tag: 'input', type: 'checkbox', autocomplete: 'off'},
3905 * @cfg {String} boxLabel The text that appears beside the checkbox
3908 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
3911 * @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
3912 * handling the check event). The handler is passed the following parameters:
3913 * <div class="mdetail-params"><ul>
3914 * <li><b>checkbox</b> : Ext.form.Checkbox<div class="sub-desc">The Checkbox being toggled.</div></li>
3915 * <li><b>checked</b> : Boolean<div class="sub-desc">The new checked state of the checkbox.</div></li>
3919 * @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
3920 * (defaults to this Checkbox).
3924 actionMode : 'wrap',
3927 initComponent : function(){
3928 Ext.form.Checkbox.superclass.initComponent.call(this);
3932 * Fires when the checkbox is checked or unchecked.
3933 * @param {Ext.form.Checkbox} this This checkbox
3934 * @param {Boolean} checked The new checked value
3941 onResize : function(){
3942 Ext.form.Checkbox.superclass.onResize.apply(this, arguments);
3943 if(!this.boxLabel && !this.fieldLabel){
3944 this.el.alignTo(this.wrap, 'c-c');
3949 initEvents : function(){
3950 Ext.form.Checkbox.superclass.initEvents.call(this);
3953 click: this.onClick,
3954 change: this.onClick
3960 * Overridden and disabled. The editor element does not support standard valid/invalid marking.
3963 markInvalid : Ext.emptyFn,
3966 * Overridden and disabled. The editor element does not support standard valid/invalid marking.
3969 clearInvalid : Ext.emptyFn,
3972 onRender : function(ct, position){
3973 Ext.form.Checkbox.superclass.onRender.call(this, ct, position);
3974 if(this.inputValue !== undefined){
3975 this.el.dom.value = this.inputValue;
3977 this.wrap = this.el.wrap({cls: 'x-form-check-wrap'});
3979 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
3982 this.setValue(true);
3984 this.checked = this.el.dom.checked;
3986 // Need to repaint for IE, otherwise positioning is broken
3987 if (Ext.isIE && !Ext.isStrict) {
3988 this.wrap.repaint();
3990 this.resizeEl = this.positionEl = this.wrap;
3994 onDestroy : function(){
3995 Ext.destroy(this.wrap);
3996 Ext.form.Checkbox.superclass.onDestroy.call(this);
4000 initValue : function() {
4001 this.originalValue = this.getValue();
4005 * Returns the checked state of the checkbox.
4006 * @return {Boolean} True if checked, else false
4008 getValue : function(){
4010 return this.el.dom.checked;
4012 return this.checked;
4016 onClick : function(){
4017 if(this.el.dom.checked != this.checked){
4018 this.setValue(this.el.dom.checked);
4023 * Sets the checked state of the checkbox, fires the 'check' event, and calls a
4024 * <code>{@link #handler}</code> (if configured).
4025 * @param {Boolean/String} checked The following values will check the checkbox:
4026 * <code>true, 'true', '1', or 'on'</code>. Any other value will uncheck the checkbox.
4027 * @return {Ext.form.Field} this
4029 setValue : function(v){
4030 var checked = this.checked,
4031 inputVal = this.inputValue;
4033 this.checked = (v === true || v === 'true' || v == '1' || (inputVal ? v == inputVal : String(v).toLowerCase() == 'on'));
4035 this.el.dom.checked = this.checked;
4036 this.el.dom.defaultChecked = this.checked;
4038 if(checked != this.checked){
4039 this.fireEvent('check', this, this.checked);
4041 this.handler.call(this.scope || this, this, this.checked);
4047 Ext.reg('checkbox', Ext.form.Checkbox);
4049 * @class Ext.form.CheckboxGroup
4050 * @extends Ext.form.Field
4051 * <p>A grouping container for {@link Ext.form.Checkbox} controls.</p>
4052 * <p>Sample usage:</p>
4054 var myCheckboxGroup = new Ext.form.CheckboxGroup({
4056 xtype: 'checkboxgroup',
4057 fieldLabel: 'Single Column',
4058 itemCls: 'x-check-group-alt',
4059 // Put all controls in a single column with width 100%
4062 {boxLabel: 'Item 1', name: 'cb-col-1'},
4063 {boxLabel: 'Item 2', name: 'cb-col-2', checked: true},
4064 {boxLabel: 'Item 3', name: 'cb-col-3'}
4069 * Creates a new CheckboxGroup
4070 * @param {Object} config Configuration options
4071 * @xtype checkboxgroup
4073 Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
4075 * @cfg {Array} items An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects
4076 * to arrange in the group.
4079 * @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped
4080 * checkbox/radio controls using automatic layout. This config can take several types of values:
4081 * <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width
4082 * of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>
4083 * <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be
4084 * created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>
4085 * <li><b>Array</b> : Object<p class="sub-desc">You can also specify an array of column widths, mixing integer
4086 * (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
4087 * be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
4088 * values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
4089 * container you should do so.</p></li></ul>
4093 * @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column
4094 * top to bottom before starting on the next column. The number of controls in each column will be automatically
4095 * calculated to keep columns as even as possible. The default value is false, so that controls will be added
4096 * to columns one at a time, completely filling each row left to right before starting on the next row.
4100 * @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).
4101 * If no items are selected at validation time, {@link @blankText} will be used as the error text.
4105 * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
4106 * select at least one item in this group")
4108 blankText : "You must select at least one item in this group",
4111 defaultType : 'checkbox',
4114 groupCls : 'x-form-check-group',
4117 initComponent: function(){
4121 * Fires when the state of a child checkbox changes.
4122 * @param {Ext.form.CheckboxGroup} this
4123 * @param {Array} checked An array containing the checked boxes.
4127 this.on('change', this.validate, this);
4128 Ext.form.CheckboxGroup.superclass.initComponent.call(this);
4132 onRender : function(ct, position){
4141 bufferResize: false // Default this to false, since it doesn't really have a proper ownerCt.
4145 defaultType: this.defaultType,
4153 if(this.items[0].items){
4155 // The container has standard ColumnLayout configs, so pass them in directly
4157 Ext.apply(panelCfg, {
4158 layoutConfig: {columns: this.items.length},
4159 defaults: this.defaults,
4162 for(var i=0, len=this.items.length; i<len; i++){
4163 Ext.applyIf(this.items[i], colCfg);
4168 // The container has field item configs, so we have to generate the column
4169 // panels first then move the items into the columns as needed.
4171 var numCols, cols = [];
4173 if(typeof this.columns == 'string'){ // 'auto' so create a col per item
4174 this.columns = this.items.length;
4176 if(!Ext.isArray(this.columns)){
4178 for(var i=0; i<this.columns; i++){
4179 cs.push((100/this.columns)*.01); // distribute by even %
4184 numCols = this.columns.length;
4186 // Generate the column configs with the correct width setting
4187 for(var i=0; i<numCols; i++){
4188 var cc = Ext.apply({items:[]}, colCfg);
4189 cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
4191 cc.defaults = Ext.apply(cc.defaults || {}, this.defaults);
4196 // Distribute the original items into the columns
4198 var rows = Math.ceil(this.items.length / numCols), ri = 0;
4199 for(var i=0, len=this.items.length; i<len; i++){
4200 if(i>0 && i%rows==0){
4203 if(this.items[i].fieldLabel){
4204 this.items[i].hideLabel = false;
4206 cols[ri].items.push(this.items[i]);
4209 for(var i=0, len=this.items.length; i<len; i++){
4210 var ci = i % numCols;
4211 if(this.items[i].fieldLabel){
4212 this.items[i].hideLabel = false;
4214 cols[ci].items.push(this.items[i]);
4218 Ext.apply(panelCfg, {
4219 layoutConfig: {columns: numCols},
4224 this.panel = new Ext.Container(panelCfg);
4225 this.panel.ownerCt = this;
4226 this.el = this.panel.getEl();
4228 if(this.forId && this.itemCls){
4229 var l = this.el.up(this.itemCls).child('label', true);
4231 l.setAttribute('htmlFor', this.forId);
4235 var fields = this.panel.findBy(function(c){
4236 return c.isFormField;
4239 this.items = new Ext.util.MixedCollection();
4240 this.items.addAll(fields);
4242 Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
4245 initValue : function(){
4247 this.setValue.apply(this, this.buffered ? this.value : [this.value]);
4248 delete this.buffered;
4253 afterRender : function(){
4254 Ext.form.CheckboxGroup.superclass.afterRender.call(this);
4255 this.eachItem(function(item){
4256 item.on('check', this.fireChecked, this);
4257 item.inGroup = true;
4262 doLayout: function(){
4263 //ugly method required to layout hidden items
4265 this.panel.forceLayout = this.ownerCt.forceLayout;
4266 this.panel.doLayout();
4271 fireChecked: function(){
4273 this.eachItem(function(item){
4278 this.fireEvent('change', this, arr);
4282 * Runs CheckboxGroup's validations and returns an array of any errors. The only error by default
4283 * is if allowBlank is set to true and no items are checked.
4284 * @return {Array} Array of all validation errors
4286 getErrors: function() {
4287 var errors = Ext.form.CheckboxGroup.superclass.getErrors.apply(this, arguments);
4289 if (!this.allowBlank) {
4292 this.eachItem(function(f){
4294 return (blank = false);
4298 if (blank) errors.push(this.blankText);
4305 isDirty: function(){
4306 //override the behaviour to check sub items.
4307 if (this.disabled || !this.rendered) {
4313 this.eachItem(function(item){
4324 setReadOnly : function(readOnly){
4326 this.eachItem(function(item){
4327 item.setReadOnly(readOnly);
4330 this.readOnly = readOnly;
4334 onDisable : function(){
4335 this.eachItem(function(item){
4341 onEnable : function(){
4342 this.eachItem(function(item){
4348 onResize : function(w, h){
4349 this.panel.setSize(w, h);
4350 this.panel.doLayout();
4353 // inherit docs from Field
4355 if (this.originalValue) {
4357 this.eachItem(function(c){
4360 c.originalValue = c.getValue();
4363 // Set items stored in originalValue, ugly - set a flag to reset the originalValue
4364 // during the horrible onSetValue. This will allow trackResetOnLoad to function.
4365 this.resetOriginal = true;
4366 this.setValue(this.originalValue);
4367 delete this.resetOriginal;
4369 this.eachItem(function(c){
4375 // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
4376 // Important because reset is being called on both the group and the individual items.
4378 this.clearInvalid();
4383 * {@link Ext.form.Checkbox#setValue Set the value(s)} of an item or items
4384 * in the group. Examples illustrating how this method may be called:
4386 // call with name and value
4387 myCheckboxGroup.setValue('cb-col-1', true);
4388 // call with an array of boolean values
4389 myCheckboxGroup.setValue([true, false, false]);
4390 // call with an object literal specifying item:value pairs
4391 myCheckboxGroup.setValue({
4395 // use comma separated string to set items with name to true (checked)
4396 myCheckboxGroup.setValue('cb-col-1,cb-col-3');
4398 * See {@link Ext.form.Checkbox#setValue} for additional information.
4399 * @param {Mixed} id The checkbox to check, or as described by example shown.
4400 * @param {Boolean} value (optional) The value to set the item.
4401 * @return {Ext.form.CheckboxGroup} this
4403 setValue: function(){
4405 this.onSetValue.apply(this, arguments);
4407 this.buffered = true;
4408 this.value = arguments;
4415 * Sets the values of one or more of the items within the CheckboxGroup
4416 * @param {String|Array|Object} id Can take multiple forms. Can be optionally:
4418 * <li>An ID string to be used with a second argument</li>
4419 * <li>An array of the form ['some', 'list', 'of', 'ids', 'to', 'mark', 'checked']</li>
4420 * <li>An array in the form [true, true, false, true, false] etc, where each item relates to the check status of
4421 * the checkbox at the same index</li>
4422 * <li>An object containing ids of the checkboxes as keys and check values as properties</li>
4424 * @param {String} value The value to set the field to if the first argument was a string
4426 onSetValue: function(id, value){
4427 if(arguments.length == 1){
4428 if(Ext.isArray(id)){
4429 Ext.each(id, function(val, idx){
4430 if (Ext.isObject(val) && val.setValue){ // array of checkbox components to be checked
4432 if (this.resetOriginal === true) {
4433 val.originalValue = val.getValue();
4435 } else { // an array of boolean values
4436 var item = this.items.itemAt(idx);
4442 }else if(Ext.isObject(id)){
4443 // set of name/value pairs
4445 var f = this.getBox(i);
4451 this.setValueForItem(id);
4454 var f = this.getBox(id);
4462 beforeDestroy: function(){
4463 Ext.destroy(this.panel);
4464 if (!this.rendered) {
4465 Ext.destroy(this.items);
4467 Ext.form.CheckboxGroup.superclass.beforeDestroy.call(this);
4471 setValueForItem : function(val){
4472 val = String(val).split(',');
4473 this.eachItem(function(item){
4474 if(val.indexOf(item.inputValue)> -1){
4475 item.setValue(true);
4481 getBox : function(id){
4483 this.eachItem(function(f){
4484 if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){
4493 * Gets an array of the selected {@link Ext.form.Checkbox} in the group.
4494 * @return {Array} An array of the selected checkboxes.
4496 getValue : function(){
4498 this.eachItem(function(item){
4508 * Convenience function which passes the given function to every item in the composite
4509 * @param {Function} fn The function to call
4510 * @param {Object} scope Optional scope object
4512 eachItem: function(fn, scope) {
4513 if(this.items && this.items.each){
4514 this.items.each(fn, scope || this);
4519 * @cfg {String} name
4524 * @method getRawValue
4527 getRawValue : Ext.emptyFn,
4530 * @method setRawValue
4533 setRawValue : Ext.emptyFn
4537 Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);
4539 * @class Ext.form.CompositeField
4540 * @extends Ext.form.Field
4541 * Composite field allowing a number of form Fields to be rendered on the same row. The fields are rendered
4542 * using an hbox layout internally, so all of the normal HBox layout config items are available. Example usage:
4545 xtype: 'compositefield',
4549 xtype : 'textfield',
4550 fieldLabel: 'Title',
4554 xtype : 'textfield',
4555 fieldLabel: 'First',
4559 xtype : 'textfield',
4566 * In the example above the composite's fieldLabel will be set to 'Title, First, Last' as it groups the fieldLabels
4567 * of each of its children. This can be overridden by setting a fieldLabel on the compositefield itself:
4570 xtype: 'compositefield',
4571 fieldLabel: 'Custom label',
4575 * Any Ext.form.* component can be placed inside a composite field.
4577 Ext.form.CompositeField = Ext.extend(Ext.form.Field, {
4580 * @property defaultMargins
4582 * The margins to apply by default to each field in the composite
4584 defaultMargins: '0 5 0 0',
4587 * @property skipLastItemMargin
4589 * If true, the defaultMargins are not applied to the last item in the composite field set (defaults to true)
4591 skipLastItemMargin: true,
4594 * @property isComposite
4596 * Signifies that this is a Composite field
4601 * @property combineErrors
4603 * True to combine errors from the individual fields into a single error message at the CompositeField level (defaults to true)
4605 combineErrors: true,
4608 * @cfg {String} labelConnector The string to use when joining segments of the built label together (defaults to ', ')
4610 labelConnector: ', ',
4613 * @cfg {Object} defaults Any default properties to assign to the child fields.
4617 //Builds the composite field label
4618 initComponent: function() {
4623 for (var i=0, j = items.length; i < j; i++) {
4626 labels.push(item.fieldLabel);
4628 //apply any defaults
4629 Ext.applyIf(item, this.defaults);
4631 //apply default margins to each item except the last
4632 if (!(i == j - 1 && this.skipLastItemMargin)) {
4633 Ext.applyIf(item, {margins: this.defaultMargins});
4637 this.fieldLabel = this.fieldLabel || this.buildLabel(labels);
4640 * @property fieldErrors
4641 * @type Ext.util.MixedCollection
4642 * MixedCollection of current errors on the Composite's subfields. This is used internally to track when
4643 * to show and hide error messages at the Composite level. Listeners are attached to the MixedCollection's
4644 * add, remove and replace events to update the error icon in the UI as errors are added or removed.
4646 this.fieldErrors = new Ext.util.MixedCollection(true, function(item) {
4650 this.fieldErrors.on({
4652 add : this.updateInvalidMark,
4653 remove : this.updateInvalidMark,
4654 replace: this.updateInvalidMark
4657 Ext.form.CompositeField.superclass.initComponent.apply(this, arguments);
4659 this.innerCt = new Ext.Container({
4662 cls : 'x-form-composite',
4663 defaultMargins: '0 3 0 0'
4666 var fields = this.innerCt.findBy(function(c) {
4667 return c.isFormField;
4672 * @type Ext.util.MixedCollection
4673 * Internal collection of all of the subfields in this Composite
4675 this.items = new Ext.util.MixedCollection();
4676 this.items.addAll(fields);
4682 * Creates an internal container using hbox and renders the fields to it
4684 onRender: function(ct, position) {
4688 * @type Ext.Container
4689 * A container configured with hbox layout which is responsible for laying out the subfields
4691 var innerCt = this.innerCt;
4694 this.el = innerCt.getEl();
4696 //if we're combining subfield errors into a single message, override the markInvalid and clearInvalid
4697 //methods of each subfield and show them at the Composite level instead
4698 if (this.combineErrors) {
4699 this.eachItem(function(field) {
4701 markInvalid : this.onFieldMarkInvalid.createDelegate(this, [field], 0),
4702 clearInvalid: this.onFieldClearInvalid.createDelegate(this, [field], 0)
4707 //set the label 'for' to the first item
4708 var l = this.el.parent().parent().child('label', true);
4710 l.setAttribute('for', this.items.items[0].id);
4714 Ext.form.CompositeField.superclass.onRender.apply(this, arguments);
4718 * Called if combineErrors is true and a subfield's markInvalid method is called.
4719 * By default this just adds the subfield's error to the internal fieldErrors MixedCollection
4720 * @param {Ext.form.Field} field The field that was marked invalid
4721 * @param {String} message The error message
4723 onFieldMarkInvalid: function(field, message) {
4724 var name = field.getName(),
4727 errorName: field.fieldLabel || name,
4731 this.fieldErrors.replace(name, error);
4733 field.el.addClass(field.invalidClass);
4737 * Called if combineErrors is true and a subfield's clearInvalid method is called.
4738 * By default this just updates the internal fieldErrors MixedCollection.
4739 * @param {Ext.form.Field} field The field that was marked invalid
4741 onFieldClearInvalid: function(field) {
4742 this.fieldErrors.removeKey(field.getName());
4744 field.el.removeClass(field.invalidClass);
4749 * Called after a subfield is marked valid or invalid, this checks to see if any of the subfields are
4750 * currently invalid. If any subfields are invalid it builds a combined error message marks the composite
4751 * invalid, otherwise clearInvalid is called
4753 updateInvalidMark: function() {
4754 var ieStrict = Ext.isIE6 && Ext.isStrict;
4756 if (this.fieldErrors.length == 0) {
4757 this.clearInvalid();
4759 //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
4761 this.clearInvalid.defer(50, this);
4764 var message = this.buildCombinedErrorMessage(this.fieldErrors.items);
4767 this.markInvalid(message);
4769 //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
4771 this.markInvalid(message);
4777 * Performs validation checks on each subfield and returns false if any of them fail validation.
4778 * @return {Boolean} False if any subfield failed validation
4780 validateValue: function() {
4783 this.eachItem(function(field) {
4784 if (!field.isValid()) valid = false;
4791 * Takes an object containing error messages for contained fields, returning a combined error
4792 * string (defaults to just placing each item on a new line). This can be overridden to provide
4793 * custom combined error message handling.
4794 * @param {Array} errors Array of errors in format: [{field: 'title', error: 'some error'}]
4795 * @return {String} The combined error message
4797 buildCombinedErrorMessage: function(errors) {
4801 for (var i = 0, j = errors.length; i < j; i++) {
4804 combined.push(String.format("{0}: {1}", error.errorName, error.error));
4807 return combined.join("<br />");
4811 * Sorts the internal fieldErrors MixedCollection by the order in which the fields are defined.
4812 * This is called before displaying errors to ensure that the errors are presented in the expected order.
4813 * This function can be overridden to provide a custom sorting order if needed.
4815 sortErrors: function() {
4816 var fields = this.items;
4818 this.fieldErrors.sort("ASC", function(a, b) {
4819 var findByName = function(key) {
4820 return function(field) {
4821 return field.getName() == key;
4825 var aIndex = fields.findIndexBy(findByName(a.field)),
4826 bIndex = fields.findIndexBy(findByName(b.field));
4828 return aIndex < bIndex ? -1 : 1;
4833 * Resets each field in the composite to their previous value
4836 this.eachItem(function(item) {
4840 // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
4841 // Important because reset is being called on both the group and the individual items.
4843 this.clearInvalid();
4848 * Calls clearInvalid on all child fields. This is a convenience function and should not often need to be called
4849 * as fields usually take care of clearing themselves
4851 clearInvalidChildren: function() {
4852 this.eachItem(function(item) {
4853 item.clearInvalid();
4858 * Builds a label string from an array of subfield labels.
4859 * By default this just joins the labels together with a comma
4860 * @param {Array} segments Array of each of the labels in the composite field's subfields
4861 * @return {String} The built label
4863 buildLabel: function(segments) {
4864 return Ext.clean(segments).join(this.labelConnector);
4868 * Checks each field in the composite and returns true if any is dirty
4869 * @return {Boolean} True if any field is dirty
4871 isDirty: function(){
4872 //override the behaviour to check sub items.
4873 if (this.disabled || !this.rendered) {
4878 this.eachItem(function(item){
4889 * Convenience function which passes the given function to every item in the composite
4890 * @param {Function} fn The function to call
4891 * @param {Object} scope Optional scope object
4893 eachItem: function(fn, scope) {
4894 if(this.items && this.items.each){
4895 this.items.each(fn, scope || this);
4901 * Passes the resize call through to the inner panel
4903 onResize: function(adjWidth, adjHeight, rawWidth, rawHeight) {
4904 var innerCt = this.innerCt;
4906 if (this.rendered && innerCt.rendered) {
4907 innerCt.setSize(adjWidth, adjHeight);
4910 Ext.form.CompositeField.superclass.onResize.apply(this, arguments);
4915 * Forces the internal container to be laid out again
4917 doLayout: function(shallow, force) {
4918 if (this.rendered) {
4919 var innerCt = this.innerCt;
4921 innerCt.forceLayout = this.ownerCt.forceLayout;
4922 innerCt.doLayout(shallow, force);
4929 beforeDestroy: function(){
4930 Ext.destroy(this.innerCt);
4932 Ext.form.CompositeField.superclass.beforeDestroy.call(this);
4935 //override the behaviour to check sub items.
4936 setReadOnly : function(readOnly) {
4937 if (readOnly == undefined) {
4940 readOnly = !!readOnly;
4943 this.eachItem(function(item){
4944 item.setReadOnly(readOnly);
4947 this.readOnly = readOnly;
4950 onShow : function() {
4951 Ext.form.CompositeField.superclass.onShow.call(this);
4955 //override the behaviour to check sub items.
4956 onDisable : function(){
4957 this.eachItem(function(item){
4962 //override the behaviour to check sub items.
4963 onEnable : function(){
4964 this.eachItem(function(item){
4970 Ext.reg('compositefield', Ext.form.CompositeField);/**
4971 * @class Ext.form.Radio
4972 * @extends Ext.form.Checkbox
4973 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
4974 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
4976 * Creates a new Radio
4977 * @param {Object} config Configuration options
4980 Ext.form.Radio = Ext.extend(Ext.form.Checkbox, {
4984 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
4987 markInvalid : Ext.emptyFn,
4989 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
4992 clearInvalid : Ext.emptyFn,
4995 * If this radio is part of a group, it will return the selected value
4998 getGroupValue : function(){
4999 var p = this.el.up('form') || Ext.getBody();
5000 var c = p.child('input[name='+this.el.dom.name+']:checked', true);
5001 return c ? c.value : null;
5005 * Sets either the checked/unchecked status of this Radio, or, if a string value
5006 * is passed, checks a sibling Radio of the same name whose value is the value specified.
5007 * @param value {String/Boolean} Checked value, or the value of the sibling radio button to check.
5008 * @return {Ext.form.Field} this
5010 setValue : function(v){
5014 if (typeof v == 'boolean') {
5015 Ext.form.Radio.superclass.setValue.call(this, v);
5016 } else if (this.rendered) {
5017 checkEl = this.getCheckEl();
5018 radio = checkEl.child('input[name=' + this.el.dom.name + '][value=' + v + ']', true);
5020 Ext.getCmp(radio.id).setValue(true);
5023 if(this.rendered && this.checked){
5024 checkEl = checkEl || this.getCheckEl();
5025 els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
5026 els.each(function(el){
5027 if(el.dom.id != this.id){
5028 Ext.getCmp(el.dom.id).setValue(false);
5036 getCheckEl: function(){
5038 return this.el.up('.x-form-radio-group');
5040 return this.el.up('form') || Ext.getBody();
5043 Ext.reg('radio', Ext.form.Radio);
5045 * @class Ext.form.RadioGroup
5046 * @extends Ext.form.CheckboxGroup
5047 * A grouping container for {@link Ext.form.Radio} controls.
5049 * Creates a new RadioGroup
5050 * @param {Object} config Configuration options
5053 Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, {
5055 * @cfg {Array} items An Array of {@link Ext.form.Radio Radio}s or Radio config objects
5056 * to arrange in the group.
5059 * @cfg {Boolean} allowBlank True to allow every item in the group to be blank (defaults to true).
5060 * If allowBlank = false and no items are selected at validation time, {@link @blankText} will
5061 * be used as the error text.
5065 * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
5066 * (defaults to 'You must select one item in this group')
5068 blankText : 'You must select one item in this group',
5071 defaultType : 'radio',
5074 groupCls : 'x-form-radio-group',
5078 * Fires when the state of a child radio changes.
5079 * @param {Ext.form.RadioGroup} this
5080 * @param {Ext.form.Radio} checked The checked radio
5084 * Gets the selected {@link Ext.form.Radio} in the group, if it exists.
5085 * @return {Ext.form.Radio} The selected radio.
5087 getValue : function(){
5089 this.eachItem(function(item){
5099 * Sets the checked radio in the group.
5100 * @param {String/Ext.form.Radio} id The radio to check.
5101 * @param {Boolean} value The value to set the radio.
5102 * @return {Ext.form.RadioGroup} this
5104 onSetValue : function(id, value){
5105 if(arguments.length > 1){
5106 var f = this.getBox(id);
5110 this.eachItem(function(item){
5112 item.setValue(false);
5118 this.setValueForItem(id);
5122 setValueForItem : function(val){
5123 val = String(val).split(',')[0];
5124 this.eachItem(function(item){
5125 item.setValue(val == item.inputValue);
5130 fireChecked : function(){
5131 if(!this.checkTask){
5132 this.checkTask = new Ext.util.DelayedTask(this.bufferChecked, this);
5134 this.checkTask.delay(10);
5138 bufferChecked : function(){
5140 this.eachItem(function(item){
5146 this.fireEvent('change', this, out);
5149 onDestroy : function(){
5151 this.checkTask.cancel();
5152 this.checkTask = null;
5154 Ext.form.RadioGroup.superclass.onDestroy.call(this);
5159 Ext.reg('radiogroup', Ext.form.RadioGroup);
5161 * @class Ext.form.Hidden
5162 * @extends Ext.form.Field
5163 * A basic hidden field for storing hidden values in forms that need to be passed in the form submit.
5165 * Create a new Hidden field.
5166 * @param {Object} config Configuration options
5169 Ext.form.Hidden = Ext.extend(Ext.form.Field, {
5171 inputType : 'hidden',
5173 shouldLayout: false,
5176 onRender : function(){
5177 Ext.form.Hidden.superclass.onRender.apply(this, arguments);
5181 initEvents : function(){
5182 this.originalValue = this.getValue();
5185 // These are all private overrides
5186 setSize : Ext.emptyFn,
5187 setWidth : Ext.emptyFn,
5188 setHeight : Ext.emptyFn,
5189 setPosition : Ext.emptyFn,
5190 setPagePosition : Ext.emptyFn,
5191 markInvalid : Ext.emptyFn,
5192 clearInvalid : Ext.emptyFn
5194 Ext.reg('hidden', Ext.form.Hidden);/**
5195 * @class Ext.form.BasicForm
5196 * @extends Ext.util.Observable
5197 * <p>Encapsulates the DOM <form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides
5198 * input field management, validation, submission, and form loading services.</p>
5199 * <p>By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}.
5200 * To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.</p>
5201 * <p><b><u>File Uploads</u></b></p>
5202 * <p>{@link #fileUpload File uploads} are not performed using Ajax submission, that
5203 * is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
5204 * manner with the DOM <tt><form></tt> element temporarily modified to have its
5205 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
5206 * to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
5207 * but removed after the return data has been gathered.</p>
5208 * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
5209 * server is using JSON to send the return object, then the
5210 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
5211 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
5212 * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
5213 * "<" as "&lt;", "&" as "&amp;" etc.</p>
5214 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
5215 * is created containing a <tt>responseText</tt> property in order to conform to the
5216 * requirements of event handlers and callbacks.</p>
5217 * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
5218 * and some server technologies (notably JEE) may require some custom processing in order to
5219 * retrieve parameter names and parameter values from the packet content.</p>
5221 * @param {Mixed} el The form element or its id
5222 * @param {Object} config Configuration options
5224 Ext.form.BasicForm = Ext.extend(Ext.util.Observable, {
5226 constructor: function(el, config){
5227 Ext.apply(this, config);
5228 if(Ext.isString(this.paramOrder)){
5229 this.paramOrder = this.paramOrder.split(/[\s,|]/);
5232 * A {@link Ext.util.MixedCollection MixedCollection} containing all the Ext.form.Fields in this form.
5233 * @type MixedCollection
5236 this.items = new Ext.util.MixedCollection(false, function(o){
5237 return o.getItemId();
5241 * @event beforeaction
5242 * Fires before any action is performed. Return false to cancel the action.
5243 * @param {Form} this
5244 * @param {Action} action The {@link Ext.form.Action} to be performed
5248 * @event actionfailed
5249 * Fires when an action fails.
5250 * @param {Form} this
5251 * @param {Action} action The {@link Ext.form.Action} that failed
5255 * @event actioncomplete
5256 * Fires when an action is completed.
5257 * @param {Form} this
5258 * @param {Action} action The {@link Ext.form.Action} that completed
5266 Ext.form.BasicForm.superclass.constructor.call(this);
5270 * @cfg {String} method
5271 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
5274 * @cfg {DataReader} reader
5275 * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read
5276 * data when executing 'load' actions. This is optional as there is built-in
5277 * support for processing JSON. For additional information on using an XMLReader
5278 * see the example provided in examples/form/xml-form.html.
5281 * @cfg {DataReader} errorReader
5282 * <p>An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to
5283 * read field error messages returned from 'submit' actions. This is optional
5284 * as there is built-in support for processing JSON.</p>
5285 * <p>The Records which provide messages for the invalid Fields must use the
5286 * Field name (or id) as the Record ID, and must contain a field called 'msg'
5287 * which contains the error message.</p>
5288 * <p>The errorReader does not have to be a full-blown implementation of a
5289 * DataReader. It simply needs to implement a <tt>read(xhr)</tt> function
5290 * which returns an Array of Records in an object with the following
5291 * structure:</p><pre><code>
5293 records: recordArray
5299 * The URL to use for form actions if one isn't supplied in the
5300 * <code>{@link #doAction doAction} options</code>.
5303 * @cfg {Boolean} fileUpload
5304 * Set to true if this form is a file upload.
5305 * <p>File uploads are not performed using normal 'Ajax' techniques, that is they are <b>not</b>
5306 * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
5307 * DOM <tt><form></tt> element temporarily modified to have its
5308 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
5309 * to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
5310 * but removed after the return data has been gathered.</p>
5311 * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
5312 * server is using JSON to send the return object, then the
5313 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
5314 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
5315 * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
5316 * "<" as "&lt;", "&" as "&amp;" etc.</p>
5317 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
5318 * is created containing a <tt>responseText</tt> property in order to conform to the
5319 * requirements of event handlers and callbacks.</p>
5320 * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
5321 * and some server technologies (notably JEE) may require some custom processing in order to
5322 * retrieve parameter names and parameter values from the packet content.</p>
5325 * @cfg {Object} baseParams
5326 * <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
5327 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
5330 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
5335 * @cfg {Object} api (Optional) If specified load and submit actions will be handled
5336 * with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}.
5337 * Methods which have been imported by Ext.Direct can be specified here to load and submit
5339 * Such as the following:<pre><code>
5341 load: App.ss.MyProfile.load,
5342 submit: App.ss.MyProfile.submit
5345 * <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
5346 * to customize how the load method is invoked.
5347 * Submit actions will always use a standard form submit. The formHandler configuration must
5348 * be set on the associated server-side method which has been imported by Ext.Direct</p>
5352 * @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
5353 * Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
5354 * <code>load</code> configuration.</p>
5355 * <br><p>Specify the params in the order in which they must be executed on the
5356 * server-side as either (1) an Array of String values, or (2) a String of params
5357 * delimited by either whitespace, comma, or pipe. For example,
5358 * any of the following would be acceptable:</p><pre><code>
5359 paramOrder: ['param1','param2','param3']
5360 paramOrder: 'param1 param2 param3'
5361 paramOrder: 'param1,param2,param3'
5362 paramOrder: 'param1|param2|param'
5365 paramOrder: undefined,
5368 * @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
5369 * <code>load</code> configuration. Send parameters as a collection of named
5370 * arguments (defaults to <tt>false</tt>). Providing a
5371 * <tt>{@link #paramOrder}</tt> nullifies this configuration.
5373 paramsAsHash: false,
5376 * @cfg {String} waitTitle
5377 * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
5379 waitTitle: 'Please Wait...',
5382 activeAction : null,
5385 * @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
5386 * or {@link #setValues}() data instead of when the form was first created. Defaults to <tt>false</tt>.
5388 trackResetOnLoad : false,
5391 * @cfg {Boolean} standardSubmit
5392 * <p>If set to <tt>true</tt>, standard HTML form submits are used instead
5393 * of XHR (Ajax) style form submissions. Defaults to <tt>false</tt>.</p>
5394 * <br><p><b>Note:</b> When using <code>standardSubmit</code>, the
5395 * <code>options</code> to <code>{@link #submit}</code> are ignored because
5396 * Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g.
5397 * <code>baseParams</code> and <code>params</code>), utilize hidden fields
5398 * to submit extra data, for example:</p>
5401 standardSubmit: true,
5405 {@link url}: 'myProcess.php',
5412 handler: function(){
5413 var fp = this.ownerCt.ownerCt,
5414 form = fp.getForm();
5415 if (form.isValid()) {
5416 // check if there are baseParams and if
5417 // hiddent items have been added already
5418 if (fp.baseParams && !fp.paramsAdded) {
5419 // add hidden items for all baseParams
5420 for (i in fp.baseParams) {
5424 value: fp.baseParams[i]
5428 // set a custom flag to prevent re-adding
5429 fp.paramsAdded = true;
5431 form.{@link #submit}();
5439 * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
5440 * element by passing it or its id or mask the form itself by passing in true.
5442 * @property waitMsgTarget
5446 initEl : function(el){
5447 this.el = Ext.get(el);
5448 this.id = this.el.id || Ext.id();
5449 if(!this.standardSubmit){
5450 this.el.on('submit', this.onSubmit, this);
5452 this.el.addClass('x-form');
5456 * Get the HTML form Element
5457 * @return Ext.Element
5464 onSubmit : function(e){
5469 * Destroys this object.
5471 * @param {Boolean} bound true if the object is bound to a form panel. If this is the case
5472 * the FormPanel will take care of destroying certain things, so we're just doubling up.
5474 destroy: function(bound){
5476 this.items.each(function(f){
5479 Ext.destroy(this.el);
5482 this.purgeListeners();
5486 * Returns true if client-side validation on the form is successful.
5489 isValid : function(){
5491 this.items.each(function(f){
5500 * <p>Returns true if any fields in this form have changed from their original values.</p>
5501 * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
5502 * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
5503 * or {@link #loadRecord}.</p>
5506 isDirty : function(){
5508 this.items.each(function(f){
5518 * Performs a predefined action ({@link Ext.form.Action.Submit} or
5519 * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
5520 * to perform application-specific processing.
5521 * @param {String/Object} actionName The name of the predefined action type,
5522 * or instance of {@link Ext.form.Action} to perform.
5523 * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
5524 * All of the config options listed below are supported by both the
5525 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
5526 * actions unless otherwise noted (custom actions could also accept
5527 * other config options):<ul>
5529 * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
5530 * to the form's {@link #url}.)</div></li>
5532 * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
5533 * to the form's method, or POST if not defined)</div></li>
5535 * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
5536 * (defaults to the form's baseParams, or none if not defined)</p>
5537 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
5539 * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
5540 * (defaults to the form's default headers)</div></li>
5542 * <li><b>success</b> : Function<div class="sub-desc">The callback that will
5543 * be invoked after a successful response (see top of
5544 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
5545 * for a description of what constitutes a successful response).
5546 * The function is passed the following parameters:<ul>
5547 * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
5548 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
5549 * <div class="sub-desc">The action object contains these properties of interest:<ul>
5550 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
5551 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
5552 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
5553 * </ul></div></li></ul></div></li>
5555 * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
5556 * failed transaction attempt. The function is passed the following parameters:<ul>
5557 * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
5558 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
5559 * <div class="sub-desc">The action object contains these properties of interest:<ul>
5560 * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
5561 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
5562 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
5563 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
5564 * </ul></div></li></ul></div></li>
5566 * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
5567 * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
5569 * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
5570 * Determines whether a Form's fields are validated in a final call to
5571 * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
5572 * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
5574 * @return {BasicForm} this
5576 doAction : function(action, options){
5577 if(Ext.isString(action)){
5578 action = new Ext.form.Action.ACTION_TYPES[action](this, options);
5580 if(this.fireEvent('beforeaction', this, action) !== false){
5581 this.beforeAction(action);
5582 action.run.defer(100, action);
5588 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
5589 * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
5590 * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
5591 * <p>The following code:</p><pre><code>
5592 myFormPanel.getForm().submit({
5593 clientValidation: true,
5594 url: 'updateConsignment.php',
5596 newStatus: 'delivered'
5598 success: function(form, action) {
5599 Ext.Msg.alert('Success', action.result.msg);
5601 failure: function(form, action) {
5602 switch (action.failureType) {
5603 case Ext.form.Action.CLIENT_INVALID:
5604 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
5606 case Ext.form.Action.CONNECT_FAILURE:
5607 Ext.Msg.alert('Failure', 'Ajax communication failed');
5609 case Ext.form.Action.SERVER_INVALID:
5610 Ext.Msg.alert('Failure', action.result.msg);
5615 * would process the following server response for a successful submission:<pre><code>
5617 "success":true, // note this is Boolean, not string
5618 "msg":"Consignment updated"
5621 * and the following server response for a failed submission:<pre><code>
5623 "success":false, // note this is Boolean, not string
5624 "msg":"You do not have permission to perform this operation"
5627 * @return {BasicForm} this
5629 submit : function(options){
5630 options = options || {};
5631 if(this.standardSubmit){
5632 var v = options.clientValidation === false || this.isValid();
5634 var el = this.el.dom;
5635 if(this.url && Ext.isEmpty(el.action)){
5636 el.action = this.url;
5642 var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
5643 this.doAction(submitAction, options);
5648 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
5649 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
5650 * @return {BasicForm} this
5652 load : function(options){
5653 var loadAction = String.format('{0}load', this.api ? 'direct' : '');
5654 this.doAction(loadAction, options);
5659 * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
5660 * @param {Record} record The record to edit
5661 * @return {BasicForm} this
5663 updateRecord : function(record){
5665 var fs = record.fields;
5666 fs.each(function(f){
5667 var field = this.findField(f.name);
5669 var value = field.getValue();
5670 if ( value.getGroupValue ) {
5671 value = value.getGroupValue();
5672 } else if ( field.eachItem ) {
5674 field.eachItem(function(item){
5675 value.push(item.getValue());
5678 record.set(f.name, value);
5686 * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
5687 * {@link Ext.data.Record#data record data}.
5688 * See also {@link #trackResetOnLoad}.
5689 * @param {Record} record The record to load
5690 * @return {BasicForm} this
5692 loadRecord : function(record){
5693 this.setValues(record.data);
5698 beforeAction : function(action){
5699 // Call HtmlEditor's syncValue before actions
5700 this.items.each(function(f){
5701 if(f.isFormField && f.syncValue){
5705 var o = action.options;
5707 if(this.waitMsgTarget === true){
5708 this.el.mask(o.waitMsg, 'x-mask-loading');
5709 }else if(this.waitMsgTarget){
5710 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
5711 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
5713 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
5719 afterAction : function(action, success){
5720 this.activeAction = null;
5721 var o = action.options;
5723 if(this.waitMsgTarget === true){
5725 }else if(this.waitMsgTarget){
5726 this.waitMsgTarget.unmask();
5728 Ext.MessageBox.updateProgress(1);
5729 Ext.MessageBox.hide();
5736 Ext.callback(o.success, o.scope, [this, action]);
5737 this.fireEvent('actioncomplete', this, action);
5739 Ext.callback(o.failure, o.scope, [this, action]);
5740 this.fireEvent('actionfailed', this, action);
5745 * Find a {@link Ext.form.Field} in this form.
5746 * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
5747 * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
5750 findField : function(id) {
5751 var field = this.items.get(id);
5753 if (!Ext.isObject(field)) {
5754 //searches for the field corresponding to the given id. Used recursively for composite fields
5755 var findMatchingField = function(f) {
5756 if (f.isFormField) {
5757 if (f.dataIndex == id || f.id == id || f.getName() == id) {
5760 } else if (f.isComposite) {
5761 return f.items.each(findMatchingField);
5762 } else if (f instanceof Ext.form.CheckboxGroup && f.rendered) {
5763 return f.eachItem(findMatchingField);
5768 this.items.each(findMatchingField);
5770 return field || null;
5775 * Mark fields in this form invalid in bulk.
5776 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
5777 * @return {BasicForm} this
5779 markInvalid : function(errors){
5780 if (Ext.isArray(errors)) {
5781 for(var i = 0, len = errors.length; i < len; i++){
5782 var fieldError = errors[i];
5783 var f = this.findField(fieldError.id);
5785 f.markInvalid(fieldError.msg);
5791 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
5792 field.markInvalid(errors[id]);
5801 * Set values for fields in this form in bulk.
5802 * @param {Array/Object} values Either an array in the form:<pre><code>
5803 [{id:'clientName', value:'Fred. Olsen Lines'},
5804 {id:'portOfLoading', value:'FXT'},
5805 {id:'portOfDischarge', value:'OSL'} ]</code></pre>
5806 * or an object hash of the form:<pre><code>
5808 clientName: 'Fred. Olsen Lines',
5809 portOfLoading: 'FXT',
5810 portOfDischarge: 'OSL'
5812 * @return {BasicForm} this
5814 setValues : function(values){
5815 if(Ext.isArray(values)){ // array of objects
5816 for(var i = 0, len = values.length; i < len; i++){
5818 var f = this.findField(v.id);
5820 f.setValue(v.value);
5821 if(this.trackResetOnLoad){
5822 f.originalValue = f.getValue();
5826 }else{ // object hash
5829 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
5830 field.setValue(values[id]);
5831 if(this.trackResetOnLoad){
5832 field.originalValue = field.getValue();
5841 * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
5842 * If multiple fields exist with the same name they are returned as an array.</p>
5843 * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
5844 * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
5845 * value can potentially be the emptyText of a field.</p>
5846 * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
5847 * @return {String/Object}
5849 getValues : function(asString){
5850 var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
5851 if(asString === true){
5854 return Ext.urlDecode(fs);
5858 * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
5859 * If multiple fields exist with the same name they are returned as an array.
5860 * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
5861 * @return {Object} The values in the form
5863 getFieldValues : function(dirtyOnly){
5868 this.items.each(function(f) {
5869 if (!f.disabled && (dirtyOnly !== true || f.isDirty())) {
5874 if(Ext.isDefined(key)){
5875 if(Ext.isArray(key)){
5889 * Clears all invalid messages in this form.
5890 * @return {BasicForm} this
5892 clearInvalid : function(){
5893 this.items.each(function(f){
5901 * @return {BasicForm} this
5904 this.items.each(function(f){
5911 * Add Ext.form Components to this form's Collection. This does not result in rendering of
5912 * the passed Component, it just enables the form to validate Fields, and distribute values to
5914 * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
5915 * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
5916 * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
5917 * collection.</b></p>
5918 * @param {Field} field1
5919 * @param {Field} field2 (optional)
5920 * @param {Field} etc (optional)
5921 * @return {BasicForm} this
5924 this.items.addAll(Array.prototype.slice.call(arguments, 0));
5929 * Removes a field from the items collection (does NOT remove its markup).
5930 * @param {Field} field
5931 * @return {BasicForm} this
5933 remove : function(field){
5934 this.items.remove(field);
5939 * Removes all fields from the collection that have been destroyed.
5941 cleanDestroyed : function() {
5942 this.items.filterBy(function(o) { return !!o.isDestroyed; }).each(this.remove, this);
5946 * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
5947 * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
5948 * @return {BasicForm} this
5950 render : function(){
5951 this.items.each(function(f){
5952 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
5953 f.applyToMarkup(f.id);
5960 * Calls {@link Ext#apply} for all fields in this form with the passed object.
5961 * @param {Object} values
5962 * @return {BasicForm} this
5964 applyToFields : function(o){
5965 this.items.each(function(f){
5972 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
5973 * @param {Object} values
5974 * @return {BasicForm} this
5976 applyIfToFields : function(o){
5977 this.items.each(function(f){
5983 callFieldMethod : function(fnName, args){
5985 this.items.each(function(f){
5986 if(Ext.isFunction(f[fnName])){
5987 f[fnName].apply(f, args);
5995 Ext.BasicForm = Ext.form.BasicForm;
5997 * @class Ext.form.FormPanel
5998 * @extends Ext.Panel
5999 * <p>Standard form container.</p>
6001 * <p><b><u>Layout</u></b></p>
6002 * <p>By default, FormPanel is configured with <tt>layout:'form'</tt> to use an {@link Ext.layout.FormLayout}
6003 * layout manager, which styles and renders fields and labels correctly. When nesting additional Containers
6004 * within a FormPanel, you should ensure that any descendant Containers which host input Fields use the
6005 * {@link Ext.layout.FormLayout} layout manager.</p>
6007 * <p><b><u>BasicForm</u></b></p>
6008 * <p>Although <b>not listed</b> as configuration options of FormPanel, the FormPanel class accepts all
6009 * of the config options required to configure its internal {@link Ext.form.BasicForm} for:
6010 * <div class="mdetail-params"><ul>
6011 * <li>{@link Ext.form.BasicForm#fileUpload file uploads}</li>
6012 * <li>functionality for {@link Ext.form.BasicForm#doAction loading, validating and submitting} the form</li>
6015 * <p><b>Note</b>: If subclassing FormPanel, any configuration options for the BasicForm must be applied to
6016 * the <tt><b>initialConfig</b></tt> property of the FormPanel. Applying {@link Ext.form.BasicForm BasicForm}
6017 * configuration settings to <b><tt>this</tt></b> will <b>not</b> affect the BasicForm's configuration.</p>
6019 * <p><b><u>Form Validation</u></b></p>
6020 * <p>For information on form validation see the following:</p>
6021 * <div class="mdetail-params"><ul>
6022 * <li>{@link Ext.form.TextField}</li>
6023 * <li>{@link Ext.form.VTypes}</li>
6024 * <li>{@link Ext.form.BasicForm#doAction BasicForm.doAction <b>clientValidation</b> notes}</li>
6025 * <li><tt>{@link Ext.form.FormPanel#monitorValid monitorValid}</tt></li>
6028 * <p><b><u>Form Submission</u></b></p>
6029 * <p>By default, Ext Forms are submitted through Ajax, using {@link Ext.form.Action}. To enable normal browser
6030 * submission of the {@link Ext.form.BasicForm BasicForm} contained in this FormPanel, see the
6031 * <tt><b>{@link Ext.form.BasicForm#standardSubmit standardSubmit}</b></tt> option.</p>
6034 * @param {Object} config Configuration options
6037 Ext.FormPanel = Ext.extend(Ext.Panel, {
6039 * @cfg {String} formId (optional) The id of the FORM tag (defaults to an auto-generated id).
6042 * @cfg {Boolean} hideLabels
6043 * <p><tt>true</tt> to hide field labels by default (sets <tt>display:none</tt>). Defaults to
6044 * <tt>false</tt>.</p>
6045 * <p>Also see {@link Ext.Component}.<tt>{@link Ext.Component#hideLabel hideLabel}</tt>.
6048 * @cfg {Number} labelPad
6049 * The default padding in pixels for field labels (defaults to <tt>5</tt>). <tt>labelPad</tt> only
6050 * applies if <tt>{@link #labelWidth}</tt> is also specified, otherwise it will be ignored.
6053 * @cfg {String} labelSeparator
6054 * See {@link Ext.Component}.<tt>{@link Ext.Component#labelSeparator labelSeparator}</tt>
6057 * @cfg {Number} labelWidth The width of labels in pixels. This property cascades to child containers
6058 * and can be overridden on any child container (e.g., a fieldset can specify a different <tt>labelWidth</tt>
6059 * for its fields) (defaults to <tt>100</tt>).
6062 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
6065 * @cfg {Array} buttons
6066 * An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this FormPanel.<br>
6067 * <p>Buttons in the footer of a FormPanel may be configured with the option <tt>formBind: true</tt>. This causes
6068 * the form's {@link #monitorValid valid state monitor task} to enable/disable those Buttons depending on
6069 * the form's valid/invalid state.</p>
6074 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to <tt>75</tt>).
6076 minButtonWidth : 75,
6079 * @cfg {String} labelAlign The label alignment value used for the <tt>text-align</tt> specification
6080 * for the <b>container</b>. Valid values are <tt>"left</tt>", <tt>"top"</tt> or <tt>"right"</tt>
6081 * (defaults to <tt>"left"</tt>). This property cascades to child <b>containers</b> and can be
6082 * overridden on any child <b>container</b> (e.g., a fieldset can specify a different <tt>labelAlign</tt>
6085 labelAlign : 'left',
6088 * @cfg {Boolean} monitorValid If <tt>true</tt>, the form monitors its valid state <b>client-side</b> and
6089 * regularly fires the {@link #clientvalidation} event passing that state.<br>
6090 * <p>When monitoring valid state, the FormPanel enables/disables any of its configured
6091 * {@link #buttons} which have been configured with <code>formBind: true</code> depending
6092 * on whether the {@link Ext.form.BasicForm#isValid form is valid} or not. Defaults to <tt>false</tt></p>
6094 monitorValid : false,
6097 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
6102 * @cfg {String} layout Defaults to <tt>'form'</tt>. Normally this configuration property should not be altered.
6103 * For additional details see {@link Ext.layout.FormLayout} and {@link Ext.Container#layout Ext.Container.layout}.
6108 initComponent : function(){
6109 this.form = this.createForm();
6110 Ext.FormPanel.superclass.initComponent.call(this);
6114 cls: this.baseCls + '-body',
6115 method : this.method || 'POST',
6116 id : this.formId || Ext.id()
6118 if(this.fileUpload) {
6119 this.bodyCfg.enctype = 'multipart/form-data';
6125 * @event clientvalidation
6126 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
6127 * @param {Ext.form.FormPanel} this
6128 * @param {Boolean} valid true if the form has passed client-side validation
6133 this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']);
6137 createForm : function(){
6138 var config = Ext.applyIf({listeners: {}}, this.initialConfig);
6139 return new Ext.form.BasicForm(null, config);
6143 initFields : function(){
6145 var formPanel = this;
6146 var fn = function(c){
6147 if(formPanel.isField(c)){
6149 }else if(c.findBy && c != formPanel){
6150 formPanel.applySettings(c);
6151 //each check required for check/radio groups.
6152 if(c.items && c.items.each){
6153 c.items.each(fn, this);
6157 this.items.each(fn, this);
6161 applySettings: function(c){
6164 labelAlign: ct.labelAlign,
6165 labelWidth: ct.labelWidth,
6171 getLayoutTarget : function(){
6172 return this.form.el;
6176 * Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains.
6177 * @return {Ext.form.BasicForm} The {@link Ext.form.BasicForm Form} which this Panel contains.
6179 getForm : function(){
6184 onRender : function(ct, position){
6186 Ext.FormPanel.superclass.onRender.call(this, ct, position);
6187 this.form.initEl(this.body);
6191 beforeDestroy : function(){
6192 this.stopMonitoring();
6193 this.form.destroy(true);
6194 Ext.FormPanel.superclass.beforeDestroy.call(this);
6197 // Determine if a Component is usable as a form Field.
6198 isField : function(c) {
6199 return !!c.setValue && !!c.getValue && !!c.markInvalid && !!c.clearInvalid;
6203 initEvents : function(){
6204 Ext.FormPanel.superclass.initEvents.call(this);
6205 // Listeners are required here to catch bubbling events from children.
6208 add: this.onAddEvent,
6209 remove: this.onRemoveEvent
6211 if(this.monitorValid){ // initialize after render
6212 this.startMonitoring();
6218 Ext.FormPanel.superclass.onAdd.call(this, c);
6223 onAddEvent: function(ct, c){
6230 processAdd : function(c){
6231 // If a single form Field, add it
6232 if(this.isField(c)){
6234 // If a Container, add any Fields it might contain
6236 this.applySettings(c);
6237 this.form.add.apply(this.form, c.findBy(this.isField));
6242 onRemove: function(c){
6243 Ext.FormPanel.superclass.onRemove.call(this, c);
6244 this.processRemove(c);
6247 onRemoveEvent: function(ct, c){
6249 this.processRemove(c);
6254 processRemove: function(c){
6255 if(!this.destroying){
6256 // If a single form Field, remove it
6257 if(this.isField(c)){
6258 this.form.remove(c);
6259 // If a Container, its already destroyed by the time it gets here. Remove any references to destroyed fields.
6260 }else if (c.findBy){
6261 Ext.each(c.findBy(this.isField), this.form.remove, this.form);
6263 * This isn't the most efficient way of getting rid of the items, however it's the most
6264 * correct, which in this case is most important.
6266 this.form.cleanDestroyed();
6272 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
6273 * option "monitorValid"
6275 startMonitoring : function(){
6276 if(!this.validTask){
6277 this.validTask = new Ext.util.TaskRunner();
6278 this.validTask.start({
6279 run : this.bindHandler,
6280 interval : this.monitorPoll || 200,
6287 * Stops monitoring of the valid state of this form
6289 stopMonitoring : function(){
6291 this.validTask.stopAll();
6292 this.validTask = null;
6297 * This is a proxy for the underlying BasicForm's {@link Ext.form.BasicForm#load} call.
6298 * @param {Object} options The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details)
6301 this.form.load.apply(this.form, arguments);
6305 onDisable : function(){
6306 Ext.FormPanel.superclass.onDisable.call(this);
6308 this.form.items.each(function(){
6315 onEnable : function(){
6316 Ext.FormPanel.superclass.onEnable.call(this);
6318 this.form.items.each(function(){
6325 bindHandler : function(){
6327 this.form.items.each(function(f){
6328 if(!f.isValid(true)){
6334 var fitems = this.fbar.items.items;
6335 for(var i = 0, len = fitems.length; i < len; i++){
6336 var btn = fitems[i];
6337 if(btn.formBind === true && btn.disabled === valid){
6338 btn.setDisabled(!valid);
6342 this.fireEvent('clientvalidation', this, valid);
6345 Ext.reg('form', Ext.FormPanel);
6347 Ext.form.FormPanel = Ext.FormPanel;
6349 * @class Ext.form.FieldSet
6350 * @extends Ext.Panel
6351 * Standard container used for grouping items within a {@link Ext.form.FormPanel form}.
6353 var form = new Ext.FormPanel({
6354 title: 'Simple Form with FieldSets',
6355 labelWidth: 75, // label settings here cascade unless overridden
6356 url: 'save-form.php',
6358 bodyStyle:'padding:5px 5px 0',
6360 renderTo: document.body,
6361 layout:'column', // arrange items in columns
6362 defaults: { // defaults applied to items
6365 bodyStyle: 'padding:4px'
6368 // Fieldset in Column 1
6371 title: 'Fieldset 1',
6375 anchor: '-20' // leave room for error icon
6377 defaultType: 'textfield',
6379 fieldLabel: 'Field 1'
6381 fieldLabel: 'Field 2'
6383 fieldLabel: 'Field 3'
6387 // Fieldset in Column 2 - Panel inside
6389 title: 'Show Panel', // title, header, or checkboxToggle creates fieldset header
6392 checkboxToggle: true,
6393 collapsed: true, // fieldset initially collapsed
6398 title: 'Panel inside a fieldset',
6406 * @param {Object} config Configuration options
6409 Ext.form.FieldSet = Ext.extend(Ext.Panel, {
6411 * @cfg {Mixed} checkboxToggle <tt>true</tt> to render a checkbox into the fieldset frame just
6412 * in front of the legend to expand/collapse the fieldset when the checkbox is toggled. (defaults
6413 * to <tt>false</tt>).
6414 * <p>A {@link Ext.DomHelper DomHelper} element spec may also be specified to create the checkbox.
6415 * If <tt>true</tt> is specified, the default DomHelper config object used to create the element
6416 * is:</p><pre><code>
6417 * {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}
6421 * @cfg {String} checkboxName The name to assign to the fieldset's checkbox if <tt>{@link #checkboxToggle} = true</tt>
6422 * (defaults to <tt>'[checkbox id]-checkbox'</tt>).
6425 * @cfg {Boolean} collapsible
6426 * <tt>true</tt> to make the fieldset collapsible and have the expand/collapse toggle button automatically
6427 * rendered into the legend element, <tt>false</tt> to keep the fieldset statically sized with no collapse
6428 * button (defaults to <tt>false</tt>). Another option is to configure <tt>{@link #checkboxToggle}</tt>.
6431 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
6434 * @cfg {String} itemCls A css class to apply to the <tt>x-form-item</tt> of fields (see
6435 * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} for details).
6436 * This property cascades to child containers.
6439 * @cfg {String} baseCls The base CSS class applied to the fieldset (defaults to <tt>'x-fieldset'</tt>).
6441 baseCls : 'x-fieldset',
6443 * @cfg {String} layout The {@link Ext.Container#layout} to use inside the fieldset (defaults to <tt>'form'</tt>).
6447 * @cfg {Boolean} animCollapse
6448 * <tt>true</tt> to animate the transition when the panel is collapsed, <tt>false</tt> to skip the
6449 * animation (defaults to <tt>false</tt>).
6451 animCollapse : false,
6454 onRender : function(ct, position){
6456 this.el = document.createElement('fieldset');
6457 this.el.id = this.id;
6458 if (this.title || this.header || this.checkboxToggle) {
6459 this.el.appendChild(document.createElement('legend')).className = this.baseCls + '-header';
6463 Ext.form.FieldSet.superclass.onRender.call(this, ct, position);
6465 if(this.checkboxToggle){
6466 var o = typeof this.checkboxToggle == 'object' ?
6467 this.checkboxToggle :
6468 {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'};
6469 this.checkbox = this.header.insertFirst(o);
6470 this.checkbox.dom.checked = !this.collapsed;
6471 this.mon(this.checkbox, 'click', this.onCheckClick, this);
6476 onCollapse : function(doAnim, animArg){
6478 this.checkbox.dom.checked = false;
6480 Ext.form.FieldSet.superclass.onCollapse.call(this, doAnim, animArg);
6485 onExpand : function(doAnim, animArg){
6487 this.checkbox.dom.checked = true;
6489 Ext.form.FieldSet.superclass.onExpand.call(this, doAnim, animArg);
6493 * This function is called by the fieldset's checkbox when it is toggled (only applies when
6494 * checkboxToggle = true). This method should never be called externally, but can be
6495 * overridden to provide custom behavior when the checkbox is toggled if needed.
6497 onCheckClick : function(){
6498 this[this.checkbox.dom.checked ? 'expand' : 'collapse']();
6502 * @cfg {String/Number} activeItem
6506 * @cfg {Mixed} applyTo
6510 * @cfg {Boolean} bodyBorder
6514 * @cfg {Boolean} border
6518 * @cfg {Boolean/Number} bufferResize
6522 * @cfg {Boolean} collapseFirst
6526 * @cfg {String} defaultType
6530 * @cfg {String} disabledClass
6534 * @cfg {String} elements
6538 * @cfg {Boolean} floating
6542 * @cfg {Boolean} footer
6546 * @cfg {Boolean} frame
6550 * @cfg {Boolean} header
6554 * @cfg {Boolean} headerAsText
6558 * @cfg {Boolean} hideCollapseTool
6562 * @cfg {String} iconCls
6566 * @cfg {Boolean/String} shadow
6570 * @cfg {Number} shadowOffset
6574 * @cfg {Boolean} shim
6578 * @cfg {Object/Array} tbar
6582 * @cfg {Array} tools
6586 * @cfg {Ext.Template/Ext.XTemplate} toolTemplate
6590 * @cfg {String} xtype
6606 * @method getBottomToolbar
6610 * @method getTopToolbar
6614 * @method setIconClass
6622 * @event beforeclose
6638 Ext.reg('fieldset', Ext.form.FieldSet);/**
6639 * @class Ext.form.HtmlEditor
6640 * @extends Ext.form.Field
6641 * Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be
6642 * automatically hidden when needed. These are noted in the config options where appropriate.
6643 * <br><br>The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not
6644 * enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}.
6645 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
6646 * supported by this editor.</b>
6647 * <br><br>An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
6648 * any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs.
6649 * <br><br>Example usage:
6651 // Simple example rendered with default options:
6652 Ext.QuickTips.init(); // enable tooltips
6653 new Ext.form.HtmlEditor({
6654 renderTo: Ext.getBody(),
6659 // Passed via xtype into a container and with custom options:
6660 Ext.QuickTips.init(); // enable tooltips
6662 title: 'HTML Editor',
6663 renderTo: Ext.getBody(),
6669 xtype: 'htmleditor',
6670 enableColors: false,
6671 enableAlignments: false
6676 * Create a new HtmlEditor
6677 * @param {Object} config
6681 Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, {
6683 * @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true)
6685 enableFormat : true,
6687 * @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true)
6689 enableFontSize : true,
6691 * @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true)
6693 enableColors : true,
6695 * @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true)
6697 enableAlignments : true,
6699 * @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true)
6703 * @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true)
6705 enableSourceEdit : true,
6707 * @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true)
6711 * @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true)
6715 * @cfg {String} createLinkText The default text for the create link prompt
6717 createLinkText : 'Please enter the URL for the link:',
6719 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
6721 defaultLinkValue : 'http:/'+'/',
6723 * @cfg {Array} fontFamilies An array of available font families
6732 defaultFont: 'tahoma',
6734 * @cfg {String} defaultValue A default value to be put into the editor to resolve focus issues (defaults to   (Non-breaking space) in Opera and IE6, ​ (Zero-width space) in all other browsers).
6736 defaultValue: (Ext.isOpera || Ext.isIE6) ? ' ' : '​',
6738 // private properties
6740 validationEvent : false,
6742 initialized : false,
6744 sourceEditMode : false,
6745 onFocus : Ext.emptyFn,
6748 defaultAutoCreate : {
6750 style:"width:500px;height:300px;",
6755 initComponent : function(){
6759 * Fires when the editor is fully initialized (including the iframe)
6760 * @param {HtmlEditor} this
6765 * Fires when the editor is first receives the focus. Any insertion must wait
6766 * until after this event.
6767 * @param {HtmlEditor} this
6772 * Fires before the textarea is updated with content from the editor iframe. Return false
6773 * to cancel the sync.
6774 * @param {HtmlEditor} this
6775 * @param {String} html
6780 * Fires before the iframe editor is updated with content from the textarea. Return false
6781 * to cancel the push.
6782 * @param {HtmlEditor} this
6783 * @param {String} html
6788 * Fires when the textarea is updated with content from the editor iframe.
6789 * @param {HtmlEditor} this
6790 * @param {String} html
6795 * Fires when the iframe editor is updated with content from the textarea.
6796 * @param {HtmlEditor} this
6797 * @param {String} html
6801 * @event editmodechange
6802 * Fires when the editor switches edit modes
6803 * @param {HtmlEditor} this
6804 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
6808 Ext.form.HtmlEditor.superclass.initComponent.call(this);
6812 createFontOptions : function(){
6813 var buf = [], fs = this.fontFamilies, ff, lc;
6814 for(var i = 0, len = fs.length; i< len; i++){
6816 lc = ff.toLowerCase();
6818 '<option value="',lc,'" style="font-family:',ff,';"',
6819 (this.defaultFont == lc ? ' selected="true">' : '>'),
6824 return buf.join('');
6828 * Protected method that will not generally be called directly. It
6829 * is called when the editor creates its toolbar. Override this method if you need to
6830 * add custom toolbar buttons.
6831 * @param {HtmlEditor} editor
6833 createToolbar : function(editor){
6835 var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled();
6838 function btn(id, toggle, handler){
6842 iconCls: 'x-edit-'+id,
6843 enableToggle:toggle !== false,
6845 handler:handler||editor.relayBtnCmd,
6846 clickEvent:'mousedown',
6847 tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined,
6848 overflowText: editor.buttonTips[id].title || undefined,
6854 if(this.enableFont && !Ext.isSafari2){
6855 var fontSelectItem = new Ext.Toolbar.Item({
6858 cls:'x-font-select',
6859 html: this.createFontOptions()
6869 if(this.enableFormat){
6877 if(this.enableFontSize){
6880 btn('increasefontsize', false, this.adjustFont),
6881 btn('decreasefontsize', false, this.adjustFont)
6885 if(this.enableColors){
6890 iconCls: 'x-edit-forecolor',
6891 clickEvent:'mousedown',
6892 tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined,
6894 menu : new Ext.menu.ColorMenu({
6895 allowReselect: true,
6901 select: function(cp, color){
6902 this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
6906 clickEvent:'mousedown'
6911 iconCls: 'x-edit-backcolor',
6912 clickEvent:'mousedown',
6913 tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined,
6915 menu : new Ext.menu.ColorMenu({
6919 allowReselect: true,
6922 select: function(cp, color){
6924 this.execCmd('useCSS', false);
6925 this.execCmd('hilitecolor', color);
6926 this.execCmd('useCSS', true);
6929 this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
6934 clickEvent:'mousedown'
6940 if(this.enableAlignments){
6944 btn('justifycenter'),
6950 if(this.enableLinks){
6953 btn('createlink', false, this.createLink)
6957 if(this.enableLists){
6960 btn('insertorderedlist'),
6961 btn('insertunorderedlist')
6964 if(this.enableSourceEdit){
6967 btn('sourceedit', true, function(btn){
6968 this.toggleSourceEdit(!this.sourceEditMode);
6974 // build the toolbar
6975 var tb = new Ext.Toolbar({
6976 renderTo: this.wrap.dom.firstChild,
6980 if (fontSelectItem) {
6981 this.fontSelect = fontSelectItem.el;
6983 this.mon(this.fontSelect, 'change', function(){
6984 var font = this.fontSelect.dom.value;
6985 this.relayCmd('fontname', font);
6990 // stop form submits
6991 this.mon(tb.el, 'click', function(e){
6999 onDisable: function(){
7001 Ext.form.HtmlEditor.superclass.onDisable.call(this);
7004 onEnable: function(){
7006 Ext.form.HtmlEditor.superclass.onEnable.call(this);
7009 setReadOnly: function(readOnly){
7011 Ext.form.HtmlEditor.superclass.setReadOnly.call(this, readOnly);
7012 if(this.initialized){
7014 this.getEditorBody().contentEditable = !readOnly;
7016 this.setDesignMode(!readOnly);
7018 var bd = this.getEditorBody();
7020 bd.style.cursor = this.readOnly ? 'default' : 'text';
7022 this.disableItems(readOnly);
7027 * Protected method that will not generally be called directly. It
7028 * is called when the editor initializes the iframe with HTML contents. Override this method if you
7029 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
7031 * Note: IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility
7033 getDocMarkup : function(){
7034 var h = Ext.fly(this.iframe).getHeight() - this.iframePad * 2;
7035 return String.format('<html><head><style type="text/css">body{border: 0; margin: 0; padding: {0}px; height: {1}px; cursor: text}</style></head><body></body></html>', this.iframePad, h);
7039 getEditorBody : function(){
7040 var doc = this.getDoc();
7041 return doc.body || doc.documentElement;
7045 getDoc : function(){
7046 return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document);
7050 getWin : function(){
7051 return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name];
7055 onRender : function(ct, position){
7056 Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position);
7057 this.el.dom.style.border = '0 none';
7058 this.el.dom.setAttribute('tabIndex', -1);
7059 this.el.addClass('x-hidden');
7060 if(Ext.isIE){ // fix IE 1px bogus margin
7061 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;');
7063 this.wrap = this.el.wrap({
7064 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
7067 this.createToolbar(this);
7069 this.disableItems(true);
7073 this.createIFrame();
7076 var sz = this.el.getSize();
7077 this.setSize(sz.width, this.height || sz.height);
7079 this.resizeEl = this.positionEl = this.wrap;
7082 createIFrame: function(){
7083 var iframe = document.createElement('iframe');
7084 iframe.name = Ext.id();
7085 iframe.frameBorder = '0';
7086 iframe.style.overflow = 'auto';
7087 iframe.src = Ext.SSL_SECURE_URL;
7089 this.wrap.dom.appendChild(iframe);
7090 this.iframe = iframe;
7092 this.monitorTask = Ext.TaskMgr.start({
7093 run: this.checkDesignMode,
7099 initFrame : function(){
7100 Ext.TaskMgr.stop(this.monitorTask);
7101 var doc = this.getDoc();
7102 this.win = this.getWin();
7105 doc.write(this.getDocMarkup());
7108 var task = { // must defer to wait for browser to be ready
7110 var doc = this.getDoc();
7111 if(doc.body || doc.readyState == 'complete'){
7112 Ext.TaskMgr.stop(task);
7113 this.setDesignMode(true);
7114 this.initEditor.defer(10, this);
7121 Ext.TaskMgr.start(task);
7125 checkDesignMode : function(){
7126 if(this.wrap && this.wrap.dom.offsetWidth){
7127 var doc = this.getDoc();
7131 if(!doc.editorInitialized || this.getDesignMode() != 'on'){
7138 * set current design mode. To enable, mode can be true or 'on', off otherwise
7140 setDesignMode : function(mode){
7141 var doc = this.getDoc();
7146 doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off';
7152 getDesignMode : function(){
7153 var doc = this.getDoc();
7154 if(!doc){ return ''; }
7155 return String(doc.designMode).toLowerCase();
7159 disableItems: function(disabled){
7160 if(this.fontSelect){
7161 this.fontSelect.dom.disabled = disabled;
7163 this.tb.items.each(function(item){
7164 if(item.getItemId() != 'sourceedit'){
7165 item.setDisabled(disabled);
7171 onResize : function(w, h){
7172 Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments);
7173 if(this.el && this.iframe){
7174 if(Ext.isNumber(w)){
7175 var aw = w - this.wrap.getFrameWidth('lr');
7176 this.el.setWidth(aw);
7177 this.tb.setWidth(aw);
7178 this.iframe.style.width = Math.max(aw, 0) + 'px';
7180 if(Ext.isNumber(h)){
7181 var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight();
7182 this.el.setHeight(ah);
7183 this.iframe.style.height = Math.max(ah, 0) + 'px';
7184 var bd = this.getEditorBody();
7186 bd.style.height = Math.max((ah - (this.iframePad*2)), 0) + 'px';
7193 * Toggles the editor between standard and source edit mode.
7194 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
7196 toggleSourceEdit : function(sourceEditMode){
7200 if (sourceEditMode === undefined) {
7201 sourceEditMode = !this.sourceEditMode;
7203 this.sourceEditMode = sourceEditMode === true;
7204 var btn = this.tb.getComponent('sourceedit');
7206 if (btn.pressed !== this.sourceEditMode) {
7207 btn.toggle(this.sourceEditMode);
7208 if (!btn.xtbHidden) {
7212 if (this.sourceEditMode) {
7213 // grab the height of the containing panel before we hide the iframe
7214 this.previousSize = this.getSize();
7216 iframeHeight = Ext.get(this.iframe).getHeight();
7218 this.disableItems(true);
7220 this.iframe.className = 'x-hidden';
7221 this.el.removeClass('x-hidden');
7222 this.el.dom.removeAttribute('tabIndex');
7224 this.el.dom.style.height = iframeHeight + 'px';
7227 elHeight = parseInt(this.el.dom.style.height, 10);
7228 if (this.initialized) {
7229 this.disableItems(this.readOnly);
7232 this.iframe.className = '';
7233 this.el.addClass('x-hidden');
7234 this.el.dom.setAttribute('tabIndex', -1);
7237 this.setSize(this.previousSize);
7238 delete this.previousSize;
7239 this.iframe.style.height = elHeight + 'px';
7241 this.fireEvent('editmodechange', this, this.sourceEditMode);
7244 // private used internally
7245 createLink : function() {
7246 var url = prompt(this.createLinkText, this.defaultLinkValue);
7247 if(url && url != 'http:/'+'/'){
7248 this.relayCmd('createlink', url);
7253 initEvents : function(){
7254 this.originalValue = this.getValue();
7258 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
7261 markInvalid : Ext.emptyFn,
7264 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
7267 clearInvalid : Ext.emptyFn,
7269 // docs inherit from Field
7270 setValue : function(v){
7271 Ext.form.HtmlEditor.superclass.setValue.call(this, v);
7277 * Protected method that will not generally be called directly. If you need/want
7278 * custom HTML cleanup, this is the method you should override.
7279 * @param {String} html The HTML to be cleaned
7280 * @return {String} The cleaned HTML
7282 cleanHtml: function(html) {
7283 html = String(html);
7284 if(Ext.isWebKit){ // strip safari nonsense
7285 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
7289 * Neat little hack. Strips out all the non-digit characters from the default
7290 * value and compares it to the character code of the first character in the string
7291 * because it can cause encoding issues when posted to the server.
7293 if(html.charCodeAt(0) == this.defaultValue.replace(/\D/g, '')){
7294 html = html.substring(1);
7300 * Protected method that will not generally be called directly. Syncs the contents
7301 * of the editor iframe with the textarea.
7303 syncValue : function(){
7304 if(this.initialized){
7305 var bd = this.getEditorBody();
7306 var html = bd.innerHTML;
7308 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
7309 var m = bs.match(/text-align:(.*?);/i);
7311 html = '<div style="'+m[0]+'">' + html + '</div>';
7314 html = this.cleanHtml(html);
7315 if(this.fireEvent('beforesync', this, html) !== false){
7316 this.el.dom.value = html;
7317 this.fireEvent('sync', this, html);
7322 //docs inherit from Field
7323 getValue : function() {
7324 this[this.sourceEditMode ? 'pushValue' : 'syncValue']();
7325 return Ext.form.HtmlEditor.superclass.getValue.call(this);
7329 * Protected method that will not generally be called directly. Pushes the value of the textarea
7330 * into the iframe editor.
7332 pushValue : function(){
7333 if(this.initialized){
7334 var v = this.el.dom.value;
7335 if(!this.activated && v.length < 1){
7336 v = this.defaultValue;
7338 if(this.fireEvent('beforepush', this, v) !== false){
7339 this.getEditorBody().innerHTML = v;
7341 // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8
7342 this.setDesignMode(false); //toggle off first
7343 this.setDesignMode(true);
7345 this.fireEvent('push', this, v);
7352 deferFocus : function(){
7353 this.focus.defer(10, this);
7356 // docs inherit from Field
7358 if(this.win && !this.sourceEditMode){
7366 initEditor : function(){
7367 //Destroying the component during/before initEditor can cause issues.
7369 var dbody = this.getEditorBody(),
7370 ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat', 'background-color', 'color'),
7374 ss['background-attachment'] = 'fixed'; // w3c
7375 dbody.bgProperties = 'fixed'; // ie
7377 Ext.DomHelper.applyStyles(dbody, ss);
7379 doc = this.getDoc();
7383 Ext.EventManager.removeAll(doc);
7388 * We need to use createDelegate here, because when using buffer, the delayed task is added
7389 * as a property to the function. When the listener is removed, the task is deleted from the function.
7390 * Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors
7391 * is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function.
7393 fn = this.onEditorEvent.createDelegate(this);
7394 Ext.EventManager.on(doc, {
7403 Ext.EventManager.on(doc, 'keypress', this.applyCommand, this);
7405 if(Ext.isIE || Ext.isWebKit || Ext.isOpera){
7406 Ext.EventManager.on(doc, 'keydown', this.fixKeys, this);
7408 doc.editorInitialized = true;
7409 this.initialized = true;
7411 this.setReadOnly(this.readOnly);
7412 this.fireEvent('initialize', this);
7417 beforeDestroy : function(){
7418 if(this.monitorTask){
7419 Ext.TaskMgr.stop(this.monitorTask);
7422 Ext.destroy(this.tb);
7423 var doc = this.getDoc();
7426 Ext.EventManager.removeAll(doc);
7427 for (var prop in doc){
7433 this.wrap.dom.innerHTML = '';
7437 Ext.form.HtmlEditor.superclass.beforeDestroy.call(this);
7441 onFirstFocus : function(){
7442 this.activated = true;
7443 this.disableItems(this.readOnly);
7444 if(Ext.isGecko){ // prevent silly gecko errors
7446 var s = this.win.getSelection();
7447 if(!s.focusNode || s.focusNode.nodeType != 3){
7448 var r = s.getRangeAt(0);
7449 r.selectNodeContents(this.getEditorBody());
7454 this.execCmd('useCSS', true);
7455 this.execCmd('styleWithCSS', false);
7458 this.fireEvent('activate', this);
7462 adjustFont: function(btn){
7463 var adjust = btn.getItemId() == 'increasefontsize' ? 1 : -1,
7464 doc = this.getDoc(),
7465 v = parseInt(doc.queryCommandValue('FontSize') || 2, 10);
7466 if((Ext.isSafari && !Ext.isSafari2) || Ext.isChrome || Ext.isAir){
7468 // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px
7482 v = v.constrain(1, 6);
7484 if(Ext.isSafari){ // safari
7487 v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0);
7489 this.execCmd('FontSize', v);
7493 onEditorEvent : function(e){
7494 this.updateToolbar();
7499 * Protected method that will not generally be called directly. It triggers
7500 * a toolbar update by reading the markup state of the current selection in the editor.
7502 updateToolbar: function(){
7508 if(!this.activated){
7509 this.onFirstFocus();
7513 var btns = this.tb.items.map,
7514 doc = this.getDoc();
7516 if(this.enableFont && !Ext.isSafari2){
7517 var name = (doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase();
7518 if(name != this.fontSelect.dom.value){
7519 this.fontSelect.dom.value = name;
7522 if(this.enableFormat){
7523 btns.bold.toggle(doc.queryCommandState('bold'));
7524 btns.italic.toggle(doc.queryCommandState('italic'));
7525 btns.underline.toggle(doc.queryCommandState('underline'));
7527 if(this.enableAlignments){
7528 btns.justifyleft.toggle(doc.queryCommandState('justifyleft'));
7529 btns.justifycenter.toggle(doc.queryCommandState('justifycenter'));
7530 btns.justifyright.toggle(doc.queryCommandState('justifyright'));
7532 if(!Ext.isSafari2 && this.enableLists){
7533 btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist'));
7534 btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist'));
7537 Ext.menu.MenuMgr.hideAll();
7543 relayBtnCmd : function(btn){
7544 this.relayCmd(btn.getItemId());
7548 * Executes a Midas editor command on the editor document and performs necessary focus and
7549 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
7550 * @param {String} cmd The Midas command
7551 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
7553 relayCmd : function(cmd, value){
7556 this.execCmd(cmd, value);
7557 this.updateToolbar();
7562 * Executes a Midas editor command directly on the editor document.
7563 * For visual commands, you should use {@link #relayCmd} instead.
7564 * <b>This should only be called after the editor is initialized.</b>
7565 * @param {String} cmd The Midas command
7566 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
7568 execCmd : function(cmd, value){
7569 var doc = this.getDoc();
7570 doc.execCommand(cmd, false, value === undefined ? null : value);
7575 applyCommand : function(e){
7577 var c = e.getCharCode(), cmd;
7579 c = String.fromCharCode(c);
7602 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
7604 * @param {String} text
7606 insertAtCursor : function(text){
7607 if(!this.activated){
7612 var doc = this.getDoc(),
7613 r = doc.selection.createRange();
7621 this.execCmd('InsertHTML', text);
7627 fixKeys : function(){ // load time branching for fastest keydown performance
7631 doc = this.getDoc(),
7635 r = doc.selection.createRange();
7638 r.pasteHTML(' ');
7641 }else if(k == e.ENTER){
7642 r = doc.selection.createRange();
7644 var target = r.parentElement();
7645 if(!target || target.tagName.toLowerCase() != 'li'){
7647 r.pasteHTML('<br />');
7654 }else if(Ext.isOpera){
7660 this.execCmd('InsertHTML',' ');
7664 }else if(Ext.isWebKit){
7669 this.execCmd('InsertText','\t');
7671 }else if(k == e.ENTER){
7673 this.execCmd('InsertHtml','<br /><br />');
7681 * Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b>
7682 * @return {Ext.Toolbar}
7684 getToolbar : function(){
7689 * Object collection of toolbar tooltips for the buttons in the editor. The key
7690 * is the command id associated with that button and the value is a valid QuickTips object.
7695 title: 'Bold (Ctrl+B)',
7696 text: 'Make the selected text bold.',
7697 cls: 'x-html-editor-tip'
7700 title: 'Italic (Ctrl+I)',
7701 text: 'Make the selected text italic.',
7702 cls: 'x-html-editor-tip'
7710 title: 'Bold (Ctrl+B)',
7711 text: 'Make the selected text bold.',
7712 cls: 'x-html-editor-tip'
7715 title: 'Italic (Ctrl+I)',
7716 text: 'Make the selected text italic.',
7717 cls: 'x-html-editor-tip'
7720 title: 'Underline (Ctrl+U)',
7721 text: 'Underline the selected text.',
7722 cls: 'x-html-editor-tip'
7724 increasefontsize : {
7726 text: 'Increase the font size.',
7727 cls: 'x-html-editor-tip'
7729 decreasefontsize : {
7730 title: 'Shrink Text',
7731 text: 'Decrease the font size.',
7732 cls: 'x-html-editor-tip'
7735 title: 'Text Highlight Color',
7736 text: 'Change the background color of the selected text.',
7737 cls: 'x-html-editor-tip'
7740 title: 'Font Color',
7741 text: 'Change the color of the selected text.',
7742 cls: 'x-html-editor-tip'
7745 title: 'Align Text Left',
7746 text: 'Align text to the left.',
7747 cls: 'x-html-editor-tip'
7750 title: 'Center Text',
7751 text: 'Center text in the editor.',
7752 cls: 'x-html-editor-tip'
7755 title: 'Align Text Right',
7756 text: 'Align text to the right.',
7757 cls: 'x-html-editor-tip'
7759 insertunorderedlist : {
7760 title: 'Bullet List',
7761 text: 'Start a bulleted list.',
7762 cls: 'x-html-editor-tip'
7764 insertorderedlist : {
7765 title: 'Numbered List',
7766 text: 'Start a numbered list.',
7767 cls: 'x-html-editor-tip'
7771 text: 'Make the selected text a hyperlink.',
7772 cls: 'x-html-editor-tip'
7775 title: 'Source Edit',
7776 text: 'Switch to source editing mode.',
7777 cls: 'x-html-editor-tip'
7781 // hide stuff that is not compatible
7799 * @cfg {String} fieldClass @hide
7802 * @cfg {String} focusClass @hide
7805 * @cfg {String} autoCreate @hide
7808 * @cfg {String} inputType @hide
7811 * @cfg {String} invalidClass @hide
7814 * @cfg {String} invalidText @hide
7817 * @cfg {String} msgFx @hide
7820 * @cfg {String} validateOnBlur @hide
7823 * @cfg {Boolean} allowDomMove @hide
7826 * @cfg {String} applyTo @hide
7829 * @cfg {String} autoHeight @hide
7832 * @cfg {String} autoWidth @hide
7835 * @cfg {String} cls @hide
7838 * @cfg {String} disabled @hide
7841 * @cfg {String} disabledClass @hide
7844 * @cfg {String} msgTarget @hide
7847 * @cfg {String} readOnly @hide
7850 * @cfg {String} style @hide
7853 * @cfg {String} validationDelay @hide
7856 * @cfg {String} validationEvent @hide
7859 * @cfg {String} tabIndex @hide
7862 * @property disabled
7866 * @method applyToMarkup
7886 * @method setDisabled
7894 Ext.reg('htmleditor', Ext.form.HtmlEditor);
7896 * @class Ext.form.TimeField
7897 * @extends Ext.form.ComboBox
7898 * Provides a time input field with a time dropdown and automatic time validation. Example usage:
7900 new Ext.form.TimeField({
7901 minValue: '9:00 AM',
7902 maxValue: '6:00 PM',
7907 * Create a new TimeField
7908 * @param {Object} config
7911 Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, {
7913 * @cfg {Date/String} minValue
7914 * The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
7915 * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
7917 minValue : undefined,
7919 * @cfg {Date/String} maxValue
7920 * The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
7921 * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
7923 maxValue : undefined,
7925 * @cfg {String} minText
7926 * The error text to display when the date in the cell is before minValue (defaults to
7927 * 'The time in this field must be equal to or after {0}').
7929 minText : "The time in this field must be equal to or after {0}",
7931 * @cfg {String} maxText
7932 * The error text to display when the time is after maxValue (defaults to
7933 * 'The time in this field must be equal to or before {0}').
7935 maxText : "The time in this field must be equal to or before {0}",
7937 * @cfg {String} invalidText
7938 * The error text to display when the time in the field is invalid (defaults to
7939 * '{value} is not a valid time').
7941 invalidText : "{0} is not a valid time",
7943 * @cfg {String} format
7944 * The default time format string which can be overriden for localization support. The format must be
7945 * valid according to {@link Date#parseDate} (defaults to 'g:i A', e.g., '3:15 PM'). For 24-hour time
7946 * format try 'H:i' instead.
7950 * @cfg {String} altFormats
7951 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
7952 * format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A').
7954 altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A",
7956 * @cfg {Number} increment
7957 * The number of minutes between each time value in the list (defaults to 15).
7964 triggerAction: 'all',
7968 // private - This is the date to use when generating time values in the absence of either minValue
7969 // or maxValue. Using the current date causes DST issues on DST boundary dates, so this is an
7970 // arbitrary "safe" date that can be any date aside from DST boundary dates.
7971 initDate: '1/1/2008',
7973 initDateFormat: 'j/n/Y',
7976 initComponent : function(){
7977 if(Ext.isDefined(this.minValue)){
7978 this.setMinValue(this.minValue, true);
7980 if(Ext.isDefined(this.maxValue)){
7981 this.setMaxValue(this.maxValue, true);
7984 this.generateStore(true);
7986 Ext.form.TimeField.superclass.initComponent.call(this);
7990 * Replaces any existing {@link #minValue} with the new time and refreshes the store.
7991 * @param {Date/String} value The minimum time that can be selected
7993 setMinValue: function(value, /* private */ initial){
7994 this.setLimit(value, true, initial);
7999 * Replaces any existing {@link #maxValue} with the new time and refreshes the store.
8000 * @param {Date/String} value The maximum time that can be selected
8002 setMaxValue: function(value, /* private */ initial){
8003 this.setLimit(value, false, initial);
8008 generateStore: function(initial){
8009 var min = this.minValue || new Date(this.initDate).clearTime(),
8010 max = this.maxValue || new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1),
8014 times.push(min.dateFormat(this.format));
8015 min = min.add('mi', this.increment);
8017 this.bindStore(times, initial);
8021 setLimit: function(value, isMin, initial){
8023 if(Ext.isString(value)){
8024 d = this.parseDate(value);
8025 }else if(Ext.isDate(value)){
8029 var val = new Date(this.initDate).clearTime();
8030 val.setHours(d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
8031 this[isMin ? 'minValue' : 'maxValue'] = val;
8033 this.generateStore();
8039 getValue : function(){
8040 var v = Ext.form.TimeField.superclass.getValue.call(this);
8041 return this.formatDate(this.parseDate(v)) || '';
8045 setValue : function(value){
8046 return Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value)));
8049 // private overrides
8050 validateValue : Ext.form.DateField.prototype.validateValue,
8052 formatDate : Ext.form.DateField.prototype.formatDate,
8054 parseDate: function(value) {
8055 if (!value || Ext.isDate(value)) {
8059 var id = this.initDate + ' ',
8060 idf = this.initDateFormat + ' ',
8061 v = Date.parseDate(id + value, idf + this.format), // *** handle DST. note: this.format is a TIME-only format
8062 af = this.altFormats;
8065 if (!this.altFormatsArray) {
8066 this.altFormatsArray = af.split("|");
8068 for (var i = 0, afa = this.altFormatsArray, len = afa.length; i < len && !v; i++) {
8069 v = Date.parseDate(id + value, idf + afa[i]);
8076 Ext.reg('timefield', Ext.form.TimeField);/**
8077 * @class Ext.form.SliderField
8078 * @extends Ext.form.Field
8079 * Wraps a {@link Ext.slider.MultiSlider Slider} so it can be used as a form field.
8081 * Creates a new SliderField
8082 * @param {Object} config Configuration options. Note that you can pass in any slider configuration options, as well as
8083 * as any field configuration options.
8084 * @xtype sliderfield
8086 Ext.form.SliderField = Ext.extend(Ext.form.Field, {
8089 * @cfg {Boolean} useTips
8090 * True to use an Ext.slider.Tip to display tips for the value. Defaults to <tt>true</tt>.
8095 * @cfg {Function} tipText
8096 * A function used to display custom text for the slider tip. Defaults to <tt>null</tt>, which will
8097 * use the default on the plugin.
8105 * Initialize the component.
8108 initComponent : function() {
8109 var cfg = Ext.copyTo({
8110 id: this.id + '-slider'
8111 }, this.initialConfig, ['vertical', 'minValue', 'maxValue', 'decimalPrecision', 'keyIncrement', 'increment', 'clickToChange', 'animate']);
8113 // only can use it if it exists.
8115 var plug = this.tipText ? {getText: this.tipText} : {};
8116 cfg.plugins = [new Ext.slider.Tip(plug)];
8118 this.slider = new Ext.Slider(cfg);
8119 Ext.form.SliderField.superclass.initComponent.call(this);
8123 * Set up the hidden field
8124 * @param {Object} ct The container to render to.
8125 * @param {Object} position The position in the container to render to.
8128 onRender : function(ct, position){
8135 Ext.form.SliderField.superclass.onRender.call(this, ct, position);
8136 this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
8137 this.resizeEl = this.positionEl = this.wrap;
8138 this.slider.render(this.wrap);
8142 * Ensure that the slider size is set automatically when the field resizes.
8143 * @param {Object} w The width
8144 * @param {Object} h The height
8145 * @param {Object} aw The adjusted width
8146 * @param {Object} ah The adjusted height
8149 onResize : function(w, h, aw, ah){
8150 Ext.form.SliderField.superclass.onResize.call(this, w, h, aw, ah);
8151 this.slider.setSize(w, h);
8155 * Initialize any events for this class.
8158 initEvents : function(){
8159 Ext.form.SliderField.superclass.initEvents.call(this);
8160 this.slider.on('change', this.onChange, this);
8164 * Utility method to set the value of the field when the slider changes.
8165 * @param {Object} slider The slider object.
8166 * @param {Object} v The new value.
8169 onChange : function(slider, v){
8170 this.setValue(v, undefined, true);
8174 * Enable the slider when the field is enabled.
8177 onEnable : function(){
8178 Ext.form.SliderField.superclass.onEnable.call(this);
8179 this.slider.enable();
8183 * Disable the slider when the field is disabled.
8186 onDisable : function(){
8187 Ext.form.SliderField.superclass.onDisable.call(this);
8188 this.slider.disable();
8192 * Ensure the slider is destroyed when the field is destroyed.
8195 beforeDestroy : function(){
8196 Ext.destroy(this.slider);
8197 Ext.form.SliderField.superclass.beforeDestroy.call(this);
8201 * If a side icon is shown, do alignment to the slider
8204 alignErrorIcon : function(){
8205 this.errorIcon.alignTo(this.slider.el, 'tl-tr', [2, 0]);
8209 * Sets the minimum field value.
8210 * @param {Number} v The new minimum value.
8211 * @return {Ext.form.SliderField} this
8213 setMinValue : function(v){
8214 this.slider.setMinValue(v);
8219 * Sets the maximum field value.
8220 * @param {Number} v The new maximum value.
8221 * @return {Ext.form.SliderField} this
8223 setMaxValue : function(v){
8224 this.slider.setMaxValue(v);
8229 * Sets the value for this field.
8230 * @param {Number} v The new value.
8231 * @param {Boolean} animate (optional) Whether to animate the transition. If not specified, it will default to the animate config.
8232 * @return {Ext.form.SliderField} this
8234 setValue : function(v, animate, /* private */ silent){
8235 // silent is used if the setValue method is invoked by the slider
8236 // which means we don't need to set the value on the slider.
8238 this.slider.setValue(v, animate);
8240 return Ext.form.SliderField.superclass.setValue.call(this, this.slider.getValue());
8244 * Gets the current value for this field.
8245 * @return {Number} The current value.
8247 getValue : function(){
8248 return this.slider.getValue();
8252 Ext.reg('sliderfield', Ext.form.SliderField);/**
8253 * @class Ext.form.Label
8254 * @extends Ext.BoxComponent
8255 * Basic Label field.
8257 * Creates a new Label
8258 * @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
8259 * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
8260 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
8263 Ext.form.Label = Ext.extend(Ext.BoxComponent, {
8265 * @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML
8266 * tags within the label's innerHTML, use the {@link #html} config instead.
8269 * @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for'
8270 * attribute. If not specified, the attribute will not be added to the label.
8273 * @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to '').
8274 * Note that if {@link #text} is specified it will take precedence and this value will be ignored.
8278 onRender : function(ct, position){
8280 this.el = document.createElement('label');
8281 this.el.id = this.getId();
8282 this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || '');
8284 this.el.setAttribute('for', this.forId);
8287 Ext.form.Label.superclass.onRender.call(this, ct, position);
8291 * Updates the label's innerHTML with the specified string.
8292 * @param {String} text The new label text
8293 * @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it
8294 * to the label (defaults to true which encodes the value). This might be useful if you want to include
8295 * tags in the label's innerHTML rather than rendering them as string literals per the default logic.
8296 * @return {Label} this
8298 setText : function(t, encode){
8299 var e = encode === false;
8300 this[!e ? 'text' : 'html'] = t;
8301 delete this[e ? 'text' : 'html'];
8303 this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t;
8309 Ext.reg('label', Ext.form.Label);/**
8310 * @class Ext.form.Action
8311 * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>
8312 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8313 * the Form needs to perform an action such as submit or load. The Configuration options
8314 * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},
8315 * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>
8316 * <p>The instance of Action which performed the action is passed to the success
8317 * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},
8318 * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),
8319 * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and
8320 * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>
8322 Ext.form.Action = function(form, options){
8324 this.options = options || {};
8328 * Failure type returned when client side validation of the Form fails
8329 * thus aborting a submit action. Client side validation is performed unless
8330 * {@link #clientValidation} is explicitly set to <tt>false</tt>.
8334 Ext.form.Action.CLIENT_INVALID = 'client';
8336 * <p>Failure type returned when server side processing fails and the {@link #result}'s
8337 * <tt style="font-weight:bold">success</tt> property is set to <tt>false</tt>.</p>
8338 * <p>In the case of a form submission, field-specific error messages may be returned in the
8339 * {@link #result}'s <tt style="font-weight:bold">errors</tt> property.</p>
8343 Ext.form.Action.SERVER_INVALID = 'server';
8345 * Failure type returned when a communication error happens when attempting
8346 * to send a request to the remote server. The {@link #response} may be examined to
8347 * provide further information.
8351 Ext.form.Action.CONNECT_FAILURE = 'connect';
8353 * Failure type returned when the response's <tt style="font-weight:bold">success</tt>
8354 * property is set to <tt>false</tt>, or no field values are returned in the response's
8355 * <tt style="font-weight:bold">data</tt> property.
8359 Ext.form.Action.LOAD_FAILURE = 'load';
8361 Ext.form.Action.prototype = {
8363 * @cfg {String} url The URL that the Action is to invoke.
8366 * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be
8367 * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens
8368 * <b>before</b> the {@link #success} callback is called and before the Form's
8369 * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.
8372 * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the
8373 * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.
8376 * @cfg {Mixed} params <p>Extra parameter values to pass. These are added to the Form's
8377 * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's
8379 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
8382 * @cfg {Number} timeout The number of seconds to wait for a server response before
8383 * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. If not specified,
8384 * defaults to the configured <tt>{@link Ext.form.BasicForm#timeout timeout}</tt> of the
8385 * {@link Ext.form.BasicForm form}.
8388 * @cfg {Function} success The function to call when a valid success return packet is recieved.
8389 * The function is passed the following parameters:<ul class="mdetail-params">
8390 * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
8391 * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result}
8392 * property of this object may be examined to perform custom postprocessing.</div></li>
8396 * @cfg {Function} failure The function to call when a failure packet was recieved, or when an
8397 * error ocurred in the Ajax communication.
8398 * The function is passed the following parameters:<ul class="mdetail-params">
8399 * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
8400 * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax
8401 * error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
8402 * property of this object may be examined to perform custom postprocessing.</div></li>
8406 * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference
8407 * for the callback functions).
8410 * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait}
8411 * during the time the action is being processed.
8414 * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait}
8415 * during the time the action is being processed.
8419 * @cfg {Boolean} submitEmptyText If set to <tt>true</tt>, the emptyText value will be sent with the form
8420 * when it is submitted. Defaults to <tt>true</tt>.
8424 * The type of action this Action instance performs.
8425 * Currently only "submit" and "load" are supported.
8430 * The type of failure detected will be one of these: {@link #CLIENT_INVALID},
8431 * {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}. Usage:
8433 var fp = new Ext.form.FormPanel({
8438 handler: function(){
8439 if(fp.getForm().isValid()){
8440 fp.getForm().submit({
8441 url: 'form-submit.php',
8442 waitMsg: 'Submitting your data...',
8443 success: function(form, action){
8444 // server responded with success = true
8445 var result = action.{@link #result};
8447 failure: function(form, action){
8448 if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
8449 Ext.Msg.alert('Error',
8450 'Status:'+action.{@link #response}.status+': '+
8451 action.{@link #response}.statusText);
8453 if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
8454 // server responded with success = false
8455 Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
8463 handler: function(){
8464 fp.getForm().reset();
8468 * @property failureType
8472 * The XMLHttpRequest object used to perform the action.
8473 * @property response
8477 * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
8478 * other, action-specific properties.
8484 run : function(options){
8489 success : function(response){
8494 handleResponse : function(response){
8498 // default connection failure
8499 failure : function(response){
8500 this.response = response;
8501 this.failureType = Ext.form.Action.CONNECT_FAILURE;
8502 this.form.afterAction(this, false);
8506 // shared code among all Actions to validate that there was a response
8507 // with either responseText or responseXml
8508 processResponse : function(response){
8509 this.response = response;
8510 if(!response.responseText && !response.responseXML){
8513 this.result = this.handleResponse(response);
8517 // utility functions used internally
8518 getUrl : function(appendParams){
8519 var url = this.options.url || this.form.url || this.form.el.dom.action;
8521 var p = this.getParams();
8523 url = Ext.urlAppend(url, p);
8530 getMethod : function(){
8531 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
8535 getParams : function(){
8536 var bp = this.form.baseParams;
8537 var p = this.options.params;
8539 if(typeof p == "object"){
8540 p = Ext.urlEncode(Ext.applyIf(p, bp));
8541 }else if(typeof p == 'string' && bp){
8542 p += '&' + Ext.urlEncode(bp);
8545 p = Ext.urlEncode(bp);
8551 createCallback : function(opts){
8552 var opts = opts || {};
8554 success: this.success,
8555 failure: this.failure,
8557 timeout: (opts.timeout*1000) || (this.form.timeout*1000),
8558 upload: this.form.fileUpload ? this.success : undefined
8564 * @class Ext.form.Action.Submit
8565 * @extends Ext.form.Action
8566 * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s
8567 * and processes the returned response.</p>
8568 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8569 * {@link Ext.form.BasicForm#submit submit}ting.</p>
8570 * <p><u><b>Response Packet Criteria</b></u></p>
8571 * <p>A response packet may contain:
8572 * <div class="mdetail-params"><ul>
8573 * <li><b><code>success</code></b> property : Boolean
8574 * <div class="sub-desc">The <code>success</code> property is required.</div></li>
8575 * <li><b><code>errors</code></b> property : Object
8576 * <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
8577 * which is optional, contains error messages for invalid fields.</div></li>
8579 * <p><u><b>JSON Packets</b></u></p>
8580 * <p>By default, response packets are assumed to be JSON, so a typical response
8581 * packet may look like this:</p><pre><code>
8585 clientCode: "Client not found",
8586 portOfLoading: "This field must not be null"
8589 * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback
8590 * or event handler methods. The object decoded from this JSON is available in the
8591 * {@link Ext.form.Action#result result} property.</p>
8592 * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
8593 errorReader: new Ext.data.XmlReader({
8601 * <p>then the results may be sent back in XML format:</p><pre><code>
8602 <?xml version="1.0" encoding="UTF-8"?>
8603 <message success="false">
8606 <id>clientCode</id>
8607 <msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
8610 <id>portOfLoading</id>
8611 <msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
8616 * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
8617 * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
8619 Ext.form.Action.Submit = function(form, options){
8620 Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
8623 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
8625 * @cfg {Ext.data.DataReader} errorReader <p><b>Optional. JSON is interpreted with
8626 * no need for an errorReader.</b></p>
8627 * <p>A Reader which reads a single record from the returned data. The DataReader's
8628 * <b>success</b> property specifies how submission success is determined. The Record's
8629 * data provides the error messages to apply to any invalid form Fields.</p>
8632 * @cfg {boolean} clientValidation Determines whether a Form's fields are validated
8633 * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
8634 * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation
8641 var o = this.options,
8642 method = this.getMethod(),
8643 isGet = method == 'GET';
8644 if(o.clientValidation === false || this.form.isValid()){
8645 if (o.submitEmptyText === false) {
8646 var fields = this.form.items,
8648 setupEmptyFields = function(f){
8649 if (f.el.getValue() == f.emptyText) {
8650 emptyFields.push(f);
8651 f.el.dom.value = "";
8653 if(f.isComposite && f.rendered){
8654 f.items.each(setupEmptyFields);
8658 fields.each(setupEmptyFields);
8660 Ext.Ajax.request(Ext.apply(this.createCallback(o), {
8661 form:this.form.el.dom,
8662 url:this.getUrl(isGet),
8665 params:!isGet ? this.getParams() : null,
8666 isUpload: this.form.fileUpload
8668 if (o.submitEmptyText === false) {
8669 Ext.each(emptyFields, function(f) {
8670 if (f.applyEmptyText) {
8675 }else if (o.clientValidation !== false){ // client validation failed
8676 this.failureType = Ext.form.Action.CLIENT_INVALID;
8677 this.form.afterAction(this, false);
8682 success : function(response){
8683 var result = this.processResponse(response);
8684 if(result === true || result.success){
8685 this.form.afterAction(this, true);
8689 this.form.markInvalid(result.errors);
8691 this.failureType = Ext.form.Action.SERVER_INVALID;
8692 this.form.afterAction(this, false);
8696 handleResponse : function(response){
8697 if(this.form.errorReader){
8698 var rs = this.form.errorReader.read(response);
8701 for(var i = 0, len = rs.records.length; i < len; i++) {
8702 var r = rs.records[i];
8706 if(errors.length < 1){
8710 success : rs.success,
8714 return Ext.decode(response.responseText);
8720 * @class Ext.form.Action.Load
8721 * @extends Ext.form.Action
8722 * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
8723 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8724 * {@link Ext.form.BasicForm#load load}ing.</p>
8725 * <p><u><b>Response Packet Criteria</b></u></p>
8726 * <p>A response packet <b>must</b> contain:
8727 * <div class="mdetail-params"><ul>
8728 * <li><b><code>success</code></b> property : Boolean</li>
8729 * <li><b><code>data</code></b> property : Object</li>
8730 * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
8731 * The individual value object for each Field is passed to the Field's
8732 * {@link Ext.form.Field#setValue setValue} method.</div></li>
8734 * <p><u><b>JSON Packets</b></u></p>
8735 * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
8736 var myFormPanel = new Ext.form.FormPanel({
8737 title: 'Client and routing info',
8739 fieldLabel: 'Client',
8742 fieldLabel: 'Port of loading',
8743 name: 'portOfLoading'
8745 fieldLabel: 'Port of discharge',
8746 name: 'portOfDischarge'
8749 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
8750 url: '/getRoutingInfo.php',
8752 consignmentRef: myConsignmentRef
8754 failure: function(form, action) {
8755 Ext.Msg.alert("Load failed", action.result.errorMessage);
8759 * a <b>success response</b> packet may look like this:</p><pre><code>
8763 clientName: "Fred. Olsen Lines",
8764 portOfLoading: "FXT",
8765 portOfDischarge: "OSL"
8768 * while a <b>failure response</b> packet may look like this:</p><pre><code>
8771 errorMessage: "Consignment reference not found"
8773 * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
8774 * callback or event handler methods. The object decoded from this JSON is available in the
8775 * {@link Ext.form.Action#result result} property.</p>
8777 Ext.form.Action.Load = function(form, options){
8778 Ext.form.Action.Load.superclass.constructor.call(this, form, options);
8779 this.reader = this.form.reader;
8782 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
8788 Ext.Ajax.request(Ext.apply(
8789 this.createCallback(this.options), {
8790 method:this.getMethod(),
8791 url:this.getUrl(false),
8792 headers: this.options.headers,
8793 params:this.getParams()
8798 success : function(response){
8799 var result = this.processResponse(response);
8800 if(result === true || !result.success || !result.data){
8801 this.failureType = Ext.form.Action.LOAD_FAILURE;
8802 this.form.afterAction(this, false);
8805 this.form.clearInvalid();
8806 this.form.setValues(result.data);
8807 this.form.afterAction(this, true);
8811 handleResponse : function(response){
8812 if(this.form.reader){
8813 var rs = this.form.reader.read(response);
8814 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
8816 success : rs.success,
8820 return Ext.decode(response.responseText);
8827 * @class Ext.form.Action.DirectLoad
8828 * @extends Ext.form.Action.Load
8829 * <p>Provides Ext.direct support for loading form data.</p>
8830 * <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
8832 var myFormPanel = new Ext.form.FormPanel({
8833 // configs for FormPanel
8834 title: 'Basic Information',
8835 renderTo: document.body,
8836 width: 300, height: 160,
8839 // configs apply to child items
8840 defaults: {anchor: '100%'},
8841 defaultType: 'textfield',
8846 fieldLabel: 'Email',
8849 fieldLabel: 'Company',
8853 // configs for BasicForm
8855 // The server-side method to call for load() requests
8856 load: Profile.getBasicInfo,
8857 // The server-side must mark the submit handler as a 'formHandler'
8858 submit: Profile.updateBasicInfo
8860 // specify the order for the passed params
8861 paramOrder: ['uid', 'foo']
8865 myFormPanel.getForm().load({
8866 // pass 2 arguments to server side getBasicInfo method (len=2)
8873 * The data packet sent to the server will resemble something like:
8877 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
8878 "data":[34,"bar"] // note the order of the params
8882 * The form will process a data packet returned by the server that is similar
8883 * to the following format:
8887 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
8891 "name":"Fred Flintstone",
8892 "company":"Slate Rock and Gravel",
8893 "email":"fred.flintstone@slaterg.com"
8900 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
8901 constructor: function(form, opts) {
8902 Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
8904 type : 'directload',
8907 var args = this.getParams();
8908 args.push(this.success, this);
8909 this.form.api.load.apply(window, args);
8912 getParams : function() {
8913 var buf = [], o = {};
8914 var bp = this.form.baseParams;
8915 var p = this.options.params;
8916 Ext.apply(o, p, bp);
8917 var paramOrder = this.form.paramOrder;
8919 for(var i = 0, len = paramOrder.length; i < len; i++){
8920 buf.push(o[paramOrder[i]]);
8922 }else if(this.form.paramsAsHash){
8927 // Direct actions have already been processed and therefore
8928 // we can directly set the result; Direct Actions do not have
8929 // a this.response property.
8930 processResponse : function(result) {
8931 this.result = result;
8935 success : function(response, trans){
8936 if(trans.type == Ext.Direct.exceptions.SERVER){
8939 Ext.form.Action.DirectLoad.superclass.success.call(this, response);
8944 * @class Ext.form.Action.DirectSubmit
8945 * @extends Ext.form.Action.Submit
8946 * <p>Provides Ext.direct support for submitting form data.</p>
8947 * <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
8949 var myFormPanel = new Ext.form.FormPanel({
8950 // configs for FormPanel
8951 title: 'Basic Information',
8952 renderTo: document.body,
8953 width: 300, height: 160,
8957 handler: function(){
8958 myFormPanel.getForm().submit({
8967 // configs apply to child items
8968 defaults: {anchor: '100%'},
8969 defaultType: 'textfield',
8974 fieldLabel: 'Email',
8977 fieldLabel: 'Company',
8981 // configs for BasicForm
8983 // The server-side method to call for load() requests
8984 load: Profile.getBasicInfo,
8985 // The server-side must mark the submit handler as a 'formHandler'
8986 submit: Profile.updateBasicInfo
8988 // specify the order for the passed params
8989 paramOrder: ['uid', 'foo']
8992 * The data packet sent to the server will resemble something like:
8995 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
8999 "extAction":"Profile","extMethod":"updateBasicInfo",
9000 "extType":"rpc","extTID":"6","extUpload":"false",
9001 "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
9006 * The form will process a data packet returned by the server that is similar
9009 // sample success packet (batched requests)
9012 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
9019 // sample failure packet (one request)
9021 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
9024 "email":"already taken"
9031 * Also see the discussion in {@link Ext.form.Action.DirectLoad}.
9033 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
9034 constructor : function(form, opts) {
9035 Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
9037 type : 'directsubmit',
9038 // override of Submit
9040 var o = this.options;
9041 if(o.clientValidation === false || this.form.isValid()){
9042 // tag on any additional params to be posted in the
9044 this.success.params = this.getParams();
9045 this.form.api.submit(this.form.el.dom, this.success, this);
9046 }else if (o.clientValidation !== false){ // client validation failed
9047 this.failureType = Ext.form.Action.CLIENT_INVALID;
9048 this.form.afterAction(this, false);
9052 getParams : function() {
9054 var bp = this.form.baseParams;
9055 var p = this.options.params;
9056 Ext.apply(o, p, bp);
9059 // Direct actions have already been processed and therefore
9060 // we can directly set the result; Direct Actions do not have
9061 // a this.response property.
9062 processResponse : function(result) {
9063 this.result = result;
9067 success : function(response, trans){
9068 if(trans.type == Ext.Direct.exceptions.SERVER){
9071 Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
9075 Ext.form.Action.ACTION_TYPES = {
9076 'load' : Ext.form.Action.Load,
9077 'submit' : Ext.form.Action.Submit,
9078 'directload' : Ext.form.Action.DirectLoad,
9079 'directsubmit' : Ext.form.Action.DirectSubmit
9082 * @class Ext.form.VTypes
9083 * <p>This is a singleton object which contains a set of commonly used field validation functions.
9084 * The validations provided are basic and intended to be easily customizable and extended.</p>
9085 * <p>To add custom VTypes specify the <code>{@link Ext.form.TextField#vtype vtype}</code> validation
9086 * test function, and optionally specify any corresponding error text to display and any keystroke
9087 * filtering mask to apply. For example:</p>
9089 // custom Vtype for vtype:'time'
9090 var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
9091 Ext.apply(Ext.form.VTypes, {
9092 // vtype validation function
9093 time: function(val, field) {
9094 return timeTest.test(val);
9096 // vtype Text property: The error text to display when the validation function returns false
9097 timeText: 'Not a valid time. Must be in the format "12:34 PM".',
9098 // vtype Mask property: The keystroke filter mask
9099 timeMask: /[\d\s:amp]/i
9104 // custom Vtype for vtype:'IPAddress'
9105 Ext.apply(Ext.form.VTypes, {
9106 IPAddress: function(v) {
9107 return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
9109 IPAddressText: 'Must be a numeric IP address',
9110 IPAddressMask: /[\d\.]/i
9115 Ext.form.VTypes = function(){
9116 // closure these in so they are only created once.
9117 var alpha = /^[a-zA-Z_]+$/,
9118 alphanum = /^[a-zA-Z0-9_]+$/,
9119 email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,
9120 url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
9122 // All these messages and functions are configurable
9125 * The function used to validate email addresses. Note that this is a very basic validation -- complete
9126 * validation per the email RFC specifications is very complex and beyond the scope of this class, although
9127 * this function can be overridden if a more comprehensive validation scheme is desired. See the validation
9128 * section of the <a href="http://en.wikipedia.org/wiki/E-mail_address">Wikipedia article on email addresses</a>
9129 * for additional information. This implementation is intended to validate the following emails:<tt>
9130 * 'barney@example.de', 'barney.rubble@example.com', 'barney-rubble@example.coop', 'barney+rubble@example.com'
9132 * @param {String} value The email address
9133 * @return {Boolean} true if the RegExp test passed, and false if not.
9135 'email' : function(v){
9136 return email.test(v);
9139 * The error text to display when the email validation function returns false. Defaults to:
9140 * <tt>'This field should be an e-mail address in the format "user@example.com"'</tt>
9143 'emailText' : 'This field should be an e-mail address in the format "user@example.com"',
9145 * The keystroke filter mask to be applied on email input. See the {@link #email} method for
9146 * information about more complex email validation. Defaults to:
9147 * <tt>/[a-z0-9_\.\-@]/i</tt>
9150 'emailMask' : /[a-z0-9_\.\-@\+]/i,
9153 * The function used to validate URLs
9154 * @param {String} value The URL
9155 * @return {Boolean} true if the RegExp test passed, and false if not.
9157 'url' : function(v){
9161 * The error text to display when the url validation function returns false. Defaults to:
9162 * <tt>'This field should be a URL in the format "http:/'+'/www.example.com"'</tt>
9165 'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"',
9168 * The function used to validate alpha values
9169 * @param {String} value The value
9170 * @return {Boolean} true if the RegExp test passed, and false if not.
9172 'alpha' : function(v){
9173 return alpha.test(v);
9176 * The error text to display when the alpha validation function returns false. Defaults to:
9177 * <tt>'This field should only contain letters and _'</tt>
9180 'alphaText' : 'This field should only contain letters and _',
9182 * The keystroke filter mask to be applied on alpha input. Defaults to:
9183 * <tt>/[a-z_]/i</tt>
9186 'alphaMask' : /[a-z_]/i,
9189 * The function used to validate alphanumeric values
9190 * @param {String} value The value
9191 * @return {Boolean} true if the RegExp test passed, and false if not.
9193 'alphanum' : function(v){
9194 return alphanum.test(v);
9197 * The error text to display when the alphanumeric validation function returns false. Defaults to:
9198 * <tt>'This field should only contain letters, numbers and _'</tt>
9201 'alphanumText' : 'This field should only contain letters, numbers and _',
9203 * The keystroke filter mask to be applied on alphanumeric input. Defaults to:
9204 * <tt>/[a-z0-9_]/i</tt>
9207 'alphanumMask' : /[a-z0-9_]/i