3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.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(),
3462 if(this.valueField && Ext.isDefined(this.value)){
3463 rec = this.findRecord(this.valueField, this.value);
3465 if(!rec || rec.get(this.displayField) != val){
3466 rec = this.findRecord(this.displayField, val);
3468 if(!rec && this.forceSelection){
3469 if(val.length > 0 && val != this.emptyText){
3470 this.el.dom.value = Ext.value(this.lastSelectionText, '');
3471 this.applyEmptyText();
3476 if(rec && this.valueField){
3477 // onSelect may have already set the value and by doing so
3478 // set the display field properly. Let's not wipe out the
3479 // valueField here by just sending the displayField.
3480 if (this.value == val){
3483 val = rec.get(this.valueField || this.displayField);
3490 onSelect : function(record, index){
3491 if(this.fireEvent('beforeselect', this, record, index) !== false){
3492 this.setValue(record.data[this.valueField || this.displayField]);
3494 this.fireEvent('select', this, record, index);
3499 getName: function(){
3500 var hf = this.hiddenField;
3501 return hf && hf.name ? hf.name : this.hiddenName || Ext.form.ComboBox.superclass.getName.call(this);
3505 * Returns the currently selected field value or empty string if no value is set.
3506 * @return {String} value The selected value
3508 getValue : function(){
3509 if(this.valueField){
3510 return Ext.isDefined(this.value) ? this.value : '';
3512 return Ext.form.ComboBox.superclass.getValue.call(this);
3517 * Clears any text/value currently set in the field
3519 clearValue : function(){
3520 if(this.hiddenField){
3521 this.hiddenField.value = '';
3523 this.setRawValue('');
3524 this.lastSelectionText = '';
3525 this.applyEmptyText();
3530 * Sets the specified value into the field. If the value finds a match, the corresponding record text
3531 * will be displayed in the field. If the value does not match the data value of an existing item,
3532 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
3533 * Otherwise the field will be blank (although the value will still be set).
3534 * @param {String} value The value to match
3535 * @return {Ext.form.Field} this
3537 setValue : function(v){
3539 if(this.valueField){
3540 var r = this.findRecord(this.valueField, v);
3542 text = r.data[this.displayField];
3543 }else if(Ext.isDefined(this.valueNotFoundText)){
3544 text = this.valueNotFoundText;
3547 this.lastSelectionText = text;
3548 if(this.hiddenField){
3549 this.hiddenField.value = Ext.value(v, '');
3551 Ext.form.ComboBox.superclass.setValue.call(this, text);
3557 findRecord : function(prop, value){
3559 if(this.store.getCount() > 0){
3560 this.store.each(function(r){
3561 if(r.data[prop] == value){
3571 onViewMove : function(e, t){
3572 this.inKeyMode = false;
3576 onViewOver : function(e, t){
3577 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
3580 var item = this.view.findItemFromChild(t);
3582 var index = this.view.indexOf(item);
3583 this.select(index, false);
3588 onViewClick : function(doFocus){
3589 var index = this.view.getSelectedIndexes()[0],
3593 this.onSelect(r, index);
3597 if(doFocus !== false){
3604 restrictHeight : function(){
3605 this.innerList.dom.style.height = '';
3606 var inner = this.innerList.dom,
3607 pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight,
3608 h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight),
3609 ha = this.getPosition()[1]-Ext.getBody().getScroll().top,
3610 hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,
3611 space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
3613 h = Math.min(h, space, this.maxHeight);
3615 this.innerList.setHeight(h);
3616 this.list.beginUpdate();
3617 this.list.setHeight(h+pad);
3618 this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
3619 this.list.endUpdate();
3623 * Returns true if the dropdown list is expanded, else false.
3625 isExpanded : function(){
3626 return this.list && this.list.isVisible();
3630 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
3631 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
3632 * @param {String} value The data value of the item to select
3633 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
3634 * selected item if it is not currently in view (defaults to true)
3635 * @return {Boolean} True if the value matched an item in the list, else false
3637 selectByValue : function(v, scrollIntoView){
3638 if(!Ext.isEmpty(v, true)){
3639 var r = this.findRecord(this.valueField || this.displayField, v);
3641 this.select(this.store.indexOf(r), scrollIntoView);
3649 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
3650 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
3651 * @param {Number} index The zero-based index of the list item to select
3652 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
3653 * selected item if it is not currently in view (defaults to true)
3655 select : function(index, scrollIntoView){
3656 this.selectedIndex = index;
3657 this.view.select(index);
3658 if(scrollIntoView !== false){
3659 var el = this.view.getNode(index);
3661 this.innerList.scrollChildIntoView(el, false);
3668 selectNext : function(){
3669 var ct = this.store.getCount();
3671 if(this.selectedIndex == -1){
3673 }else if(this.selectedIndex < ct-1){
3674 this.select(this.selectedIndex+1);
3680 selectPrev : function(){
3681 var ct = this.store.getCount();
3683 if(this.selectedIndex == -1){
3685 }else if(this.selectedIndex !== 0){
3686 this.select(this.selectedIndex-1);
3692 onKeyUp : function(e){
3694 if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){
3697 this.dqTask.delay(this.queryDelay);
3699 Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
3703 validateBlur : function(){
3704 return !this.list || !this.list.isVisible();
3708 initQuery : function(){
3709 this.doQuery(this.getRawValue());
3713 beforeBlur : function(){
3718 postBlur : function(){
3719 Ext.form.ComboBox.superclass.postBlur.call(this);
3721 this.inKeyMode = false;
3725 * Execute a query to filter the dropdown list. Fires the {@link #beforequery} event prior to performing the
3726 * query allowing the query action to be canceled if needed.
3727 * @param {String} query The SQL query to execute
3728 * @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
3729 * characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option. It
3730 * also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
3732 doQuery : function(q, forceAll){
3733 q = Ext.isEmpty(q) ? '' : q;
3740 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
3744 forceAll = qe.forceAll;
3745 if(forceAll === true || (q.length >= this.minChars)){
3746 if(this.lastQuery !== q){
3748 if(this.mode == 'local'){
3749 this.selectedIndex = -1;
3751 this.store.clearFilter();
3753 this.store.filter(this.displayField, q);
3757 this.store.baseParams[this.queryParam] = q;
3759 params: this.getParams(q)
3764 this.selectedIndex = -1;
3771 getParams : function(q){
3773 paramNames = this.store.paramNames;
3775 params[paramNames.start] = 0;
3776 params[paramNames.limit] = this.pageSize;
3782 * Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
3784 collapse : function(){
3785 if(!this.isExpanded()){
3789 Ext.getDoc().un('mousewheel', this.collapseIf, this);
3790 Ext.getDoc().un('mousedown', this.collapseIf, this);
3791 this.fireEvent('collapse', this);
3795 collapseIf : function(e){
3796 if(!this.isDestroyed && !e.within(this.wrap) && !e.within(this.list)){
3802 * Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
3804 expand : function(){
3805 if(this.isExpanded() || !this.hasFocus){
3809 if(this.title || this.pageSize){
3810 this.assetHeight = 0;
3812 this.assetHeight += this.header.getHeight();
3815 this.assetHeight += this.footer.getHeight();
3819 if(this.bufferSize){
3820 this.doResize(this.bufferSize);
3821 delete this.bufferSize;
3823 this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
3825 // zindex can change, re-check it and set it if necessary
3826 this.list.setZIndex(this.getZIndex());
3829 this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
3831 this.mon(Ext.getDoc(), {
3833 mousewheel: this.collapseIf,
3834 mousedown: this.collapseIf
3836 this.fireEvent('expand', this);
3840 * @method onTriggerClick
3844 // Implements the default empty TriggerField.onTriggerClick function
3845 onTriggerClick : function(){
3846 if(this.readOnly || this.disabled){
3849 if(this.isExpanded()){
3854 if(this.triggerAction == 'all') {
3855 this.doQuery(this.allQuery, true);
3857 this.doQuery(this.getRawValue());
3868 * @cfg {Boolean} grow @hide
3871 * @cfg {Number} growMin @hide
3874 * @cfg {Number} growMax @hide
3878 Ext.reg('combo', Ext.form.ComboBox);
3880 * @class Ext.form.Checkbox
3881 * @extends Ext.form.Field
3882 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
3884 * Creates a new Checkbox
3885 * @param {Object} config Configuration options
3888 Ext.form.Checkbox = Ext.extend(Ext.form.Field, {
3890 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
3892 focusClass : undefined,
3894 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to 'x-form-field')
3896 fieldClass : 'x-form-field',
3898 * @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>)
3902 * @cfg {String} boxLabel The text that appears beside the checkbox
3906 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
3907 * {tag: 'input', type: 'checkbox', autocomplete: 'off'})
3909 defaultAutoCreate : { tag: 'input', type: 'checkbox', autocomplete: 'off'},
3911 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
3914 * @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
3915 * handling the check event). The handler is passed the following parameters:
3916 * <div class="mdetail-params"><ul>
3917 * <li><b>checkbox</b> : Ext.form.Checkbox<div class="sub-desc">The Checkbox being toggled.</div></li>
3918 * <li><b>checked</b> : Boolean<div class="sub-desc">The new checked state of the checkbox.</div></li>
3922 * @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
3923 * (defaults to this Checkbox).
3927 actionMode : 'wrap',
3930 initComponent : function(){
3931 Ext.form.Checkbox.superclass.initComponent.call(this);
3935 * Fires when the checkbox is checked or unchecked.
3936 * @param {Ext.form.Checkbox} this This checkbox
3937 * @param {Boolean} checked The new checked value
3944 onResize : function(){
3945 Ext.form.Checkbox.superclass.onResize.apply(this, arguments);
3946 if(!this.boxLabel && !this.fieldLabel){
3947 this.el.alignTo(this.wrap, 'c-c');
3952 initEvents : function(){
3953 Ext.form.Checkbox.superclass.initEvents.call(this);
3956 click: this.onClick,
3957 change: this.onClick
3963 * Overridden and disabled. The editor element does not support standard valid/invalid marking.
3966 markInvalid : Ext.emptyFn,
3969 * Overridden and disabled. The editor element does not support standard valid/invalid marking.
3972 clearInvalid : Ext.emptyFn,
3975 onRender : function(ct, position){
3976 Ext.form.Checkbox.superclass.onRender.call(this, ct, position);
3977 if(this.inputValue !== undefined){
3978 this.el.dom.value = this.inputValue;
3980 this.wrap = this.el.wrap({cls: 'x-form-check-wrap'});
3982 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
3985 this.setValue(true);
3987 this.checked = this.el.dom.checked;
3989 // Need to repaint for IE, otherwise positioning is broken
3990 if (Ext.isIE && !Ext.isStrict) {
3991 this.wrap.repaint();
3993 this.resizeEl = this.positionEl = this.wrap;
3997 onDestroy : function(){
3998 Ext.destroy(this.wrap);
3999 Ext.form.Checkbox.superclass.onDestroy.call(this);
4003 initValue : function() {
4004 this.originalValue = this.getValue();
4008 * Returns the checked state of the checkbox.
4009 * @return {Boolean} True if checked, else false
4011 getValue : function(){
4013 return this.el.dom.checked;
4015 return this.checked;
4019 onClick : function(){
4020 if(this.el.dom.checked != this.checked){
4021 this.setValue(this.el.dom.checked);
4026 * Sets the checked state of the checkbox, fires the 'check' event, and calls a
4027 * <code>{@link #handler}</code> (if configured).
4028 * @param {Boolean/String} checked The following values will check the checkbox:
4029 * <code>true, 'true', '1', or 'on'</code>. Any other value will uncheck the checkbox.
4030 * @return {Ext.form.Field} this
4032 setValue : function(v){
4033 var checked = this.checked,
4034 inputVal = this.inputValue;
4036 this.checked = (v === true || v === 'true' || v == '1' || (inputVal ? v == inputVal : String(v).toLowerCase() == 'on'));
4038 this.el.dom.checked = this.checked;
4039 this.el.dom.defaultChecked = this.checked;
4041 if(checked != this.checked){
4042 this.fireEvent('check', this, this.checked);
4044 this.handler.call(this.scope || this, this, this.checked);
4050 Ext.reg('checkbox', Ext.form.Checkbox);
4052 * @class Ext.form.CheckboxGroup
4053 * @extends Ext.form.Field
4054 * <p>A grouping container for {@link Ext.form.Checkbox} controls.</p>
4055 * <p>Sample usage:</p>
4057 var myCheckboxGroup = new Ext.form.CheckboxGroup({
4059 xtype: 'checkboxgroup',
4060 fieldLabel: 'Single Column',
4061 itemCls: 'x-check-group-alt',
4062 // Put all controls in a single column with width 100%
4065 {boxLabel: 'Item 1', name: 'cb-col-1'},
4066 {boxLabel: 'Item 2', name: 'cb-col-2', checked: true},
4067 {boxLabel: 'Item 3', name: 'cb-col-3'}
4072 * Creates a new CheckboxGroup
4073 * @param {Object} config Configuration options
4074 * @xtype checkboxgroup
4076 Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
4078 * @cfg {Array} items An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects
4079 * to arrange in the group.
4082 * @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped
4083 * checkbox/radio controls using automatic layout. This config can take several types of values:
4084 * <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width
4085 * of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>
4086 * <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be
4087 * created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>
4088 * <li><b>Array</b> : Object<p class="sub-desc">You can also specify an array of column widths, mixing integer
4089 * (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
4090 * be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
4091 * values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
4092 * container you should do so.</p></li></ul>
4096 * @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column
4097 * top to bottom before starting on the next column. The number of controls in each column will be automatically
4098 * calculated to keep columns as even as possible. The default value is false, so that controls will be added
4099 * to columns one at a time, completely filling each row left to right before starting on the next row.
4103 * @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).
4104 * If no items are selected at validation time, {@link @blankText} will be used as the error text.
4108 * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
4109 * select at least one item in this group")
4111 blankText : "You must select at least one item in this group",
4114 defaultType : 'checkbox',
4117 groupCls : 'x-form-check-group',
4120 initComponent: function(){
4124 * Fires when the state of a child checkbox changes.
4125 * @param {Ext.form.CheckboxGroup} this
4126 * @param {Array} checked An array containing the checked boxes.
4130 this.on('change', this.validate, this);
4131 Ext.form.CheckboxGroup.superclass.initComponent.call(this);
4135 onRender : function(ct, position){
4144 bufferResize: false // Default this to false, since it doesn't really have a proper ownerCt.
4148 defaultType: this.defaultType,
4156 if(this.items[0].items){
4158 // The container has standard ColumnLayout configs, so pass them in directly
4160 Ext.apply(panelCfg, {
4161 layoutConfig: {columns: this.items.length},
4162 defaults: this.defaults,
4165 for(var i=0, len=this.items.length; i<len; i++){
4166 Ext.applyIf(this.items[i], colCfg);
4171 // The container has field item configs, so we have to generate the column
4172 // panels first then move the items into the columns as needed.
4174 var numCols, cols = [];
4176 if(typeof this.columns == 'string'){ // 'auto' so create a col per item
4177 this.columns = this.items.length;
4179 if(!Ext.isArray(this.columns)){
4181 for(var i=0; i<this.columns; i++){
4182 cs.push((100/this.columns)*.01); // distribute by even %
4187 numCols = this.columns.length;
4189 // Generate the column configs with the correct width setting
4190 for(var i=0; i<numCols; i++){
4191 var cc = Ext.apply({items:[]}, colCfg);
4192 cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
4194 cc.defaults = Ext.apply(cc.defaults || {}, this.defaults);
4199 // Distribute the original items into the columns
4201 var rows = Math.ceil(this.items.length / numCols), ri = 0;
4202 for(var i=0, len=this.items.length; i<len; i++){
4203 if(i>0 && i%rows==0){
4206 if(this.items[i].fieldLabel){
4207 this.items[i].hideLabel = false;
4209 cols[ri].items.push(this.items[i]);
4212 for(var i=0, len=this.items.length; i<len; i++){
4213 var ci = i % numCols;
4214 if(this.items[i].fieldLabel){
4215 this.items[i].hideLabel = false;
4217 cols[ci].items.push(this.items[i]);
4221 Ext.apply(panelCfg, {
4222 layoutConfig: {columns: numCols},
4227 this.panel = new Ext.Container(panelCfg);
4228 this.panel.ownerCt = this;
4229 this.el = this.panel.getEl();
4231 if(this.forId && this.itemCls){
4232 var l = this.el.up(this.itemCls).child('label', true);
4234 l.setAttribute('htmlFor', this.forId);
4238 var fields = this.panel.findBy(function(c){
4239 return c.isFormField;
4242 this.items = new Ext.util.MixedCollection();
4243 this.items.addAll(fields);
4245 Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
4248 initValue : function(){
4250 this.setValue.apply(this, this.buffered ? this.value : [this.value]);
4251 delete this.buffered;
4256 afterRender : function(){
4257 Ext.form.CheckboxGroup.superclass.afterRender.call(this);
4258 this.eachItem(function(item){
4259 item.on('check', this.fireChecked, this);
4260 item.inGroup = true;
4265 doLayout: function(){
4266 //ugly method required to layout hidden items
4268 this.panel.forceLayout = this.ownerCt.forceLayout;
4269 this.panel.doLayout();
4274 fireChecked: function(){
4276 this.eachItem(function(item){
4281 this.fireEvent('change', this, arr);
4285 * Runs CheckboxGroup's validations and returns an array of any errors. The only error by default
4286 * is if allowBlank is set to true and no items are checked.
4287 * @return {Array} Array of all validation errors
4289 getErrors: function() {
4290 var errors = Ext.form.CheckboxGroup.superclass.getErrors.apply(this, arguments);
4292 if (!this.allowBlank) {
4295 this.eachItem(function(f){
4297 return (blank = false);
4301 if (blank) errors.push(this.blankText);
4308 isDirty: function(){
4309 //override the behaviour to check sub items.
4310 if (this.disabled || !this.rendered) {
4316 this.eachItem(function(item){
4327 setReadOnly : function(readOnly){
4329 this.eachItem(function(item){
4330 item.setReadOnly(readOnly);
4333 this.readOnly = readOnly;
4337 onDisable : function(){
4338 this.eachItem(function(item){
4344 onEnable : function(){
4345 this.eachItem(function(item){
4351 onResize : function(w, h){
4352 this.panel.setSize(w, h);
4353 this.panel.doLayout();
4356 // inherit docs from Field
4358 if (this.originalValue) {
4360 this.eachItem(function(c){
4363 c.originalValue = c.getValue();
4366 // Set items stored in originalValue, ugly - set a flag to reset the originalValue
4367 // during the horrible onSetValue. This will allow trackResetOnLoad to function.
4368 this.resetOriginal = true;
4369 this.setValue(this.originalValue);
4370 delete this.resetOriginal;
4372 this.eachItem(function(c){
4378 // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
4379 // Important because reset is being called on both the group and the individual items.
4381 this.clearInvalid();
4386 * {@link Ext.form.Checkbox#setValue Set the value(s)} of an item or items
4387 * in the group. Examples illustrating how this method may be called:
4389 // call with name and value
4390 myCheckboxGroup.setValue('cb-col-1', true);
4391 // call with an array of boolean values
4392 myCheckboxGroup.setValue([true, false, false]);
4393 // call with an object literal specifying item:value pairs
4394 myCheckboxGroup.setValue({
4398 // use comma separated string to set items with name to true (checked)
4399 myCheckboxGroup.setValue('cb-col-1,cb-col-3');
4401 * See {@link Ext.form.Checkbox#setValue} for additional information.
4402 * @param {Mixed} id The checkbox to check, or as described by example shown.
4403 * @param {Boolean} value (optional) The value to set the item.
4404 * @return {Ext.form.CheckboxGroup} this
4406 setValue: function(){
4408 this.onSetValue.apply(this, arguments);
4410 this.buffered = true;
4411 this.value = arguments;
4418 * Sets the values of one or more of the items within the CheckboxGroup
4419 * @param {String|Array|Object} id Can take multiple forms. Can be optionally:
4421 * <li>An ID string to be used with a second argument</li>
4422 * <li>An array of the form ['some', 'list', 'of', 'ids', 'to', 'mark', 'checked']</li>
4423 * <li>An array in the form [true, true, false, true, false] etc, where each item relates to the check status of
4424 * the checkbox at the same index</li>
4425 * <li>An object containing ids of the checkboxes as keys and check values as properties</li>
4427 * @param {String} value The value to set the field to if the first argument was a string
4429 onSetValue: function(id, value){
4430 if(arguments.length == 1){
4431 if(Ext.isArray(id)){
4432 Ext.each(id, function(val, idx){
4433 if (Ext.isObject(val) && val.setValue){ // array of checkbox components to be checked
4435 if (this.resetOriginal === true) {
4436 val.originalValue = val.getValue();
4438 } else { // an array of boolean values
4439 var item = this.items.itemAt(idx);
4445 }else if(Ext.isObject(id)){
4446 // set of name/value pairs
4448 var f = this.getBox(i);
4454 this.setValueForItem(id);
4457 var f = this.getBox(id);
4465 beforeDestroy: function(){
4466 Ext.destroy(this.panel);
4467 if (!this.rendered) {
4468 Ext.destroy(this.items);
4470 Ext.form.CheckboxGroup.superclass.beforeDestroy.call(this);
4474 setValueForItem : function(val){
4475 val = String(val).split(',');
4476 this.eachItem(function(item){
4477 if(val.indexOf(item.inputValue)> -1){
4478 item.setValue(true);
4484 getBox : function(id){
4486 this.eachItem(function(f){
4487 if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){
4496 * Gets an array of the selected {@link Ext.form.Checkbox} in the group.
4497 * @return {Array} An array of the selected checkboxes.
4499 getValue : function(){
4501 this.eachItem(function(item){
4511 * Convenience function which passes the given function to every item in the composite
4512 * @param {Function} fn The function to call
4513 * @param {Object} scope Optional scope object
4515 eachItem: function(fn, scope) {
4516 if(this.items && this.items.each){
4517 this.items.each(fn, scope || this);
4522 * @cfg {String} name
4527 * @method getRawValue
4530 getRawValue : Ext.emptyFn,
4533 * @method setRawValue
4536 setRawValue : Ext.emptyFn
4540 Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);
4542 * @class Ext.form.CompositeField
4543 * @extends Ext.form.Field
4544 * Composite field allowing a number of form Fields to be rendered on the same row. The fields are rendered
4545 * using an hbox layout internally, so all of the normal HBox layout config items are available. Example usage:
4548 xtype: 'compositefield',
4552 xtype : 'textfield',
4553 fieldLabel: 'Title',
4557 xtype : 'textfield',
4558 fieldLabel: 'First',
4562 xtype : 'textfield',
4569 * In the example above the composite's fieldLabel will be set to 'Title, First, Last' as it groups the fieldLabels
4570 * of each of its children. This can be overridden by setting a fieldLabel on the compositefield itself:
4573 xtype: 'compositefield',
4574 fieldLabel: 'Custom label',
4578 * Any Ext.form.* component can be placed inside a composite field.
4580 Ext.form.CompositeField = Ext.extend(Ext.form.Field, {
4583 * @property defaultMargins
4585 * The margins to apply by default to each field in the composite
4587 defaultMargins: '0 5 0 0',
4590 * @property skipLastItemMargin
4592 * If true, the defaultMargins are not applied to the last item in the composite field set (defaults to true)
4594 skipLastItemMargin: true,
4597 * @property isComposite
4599 * Signifies that this is a Composite field
4604 * @property combineErrors
4606 * True to combine errors from the individual fields into a single error message at the CompositeField level (defaults to true)
4608 combineErrors: true,
4611 * @cfg {String} labelConnector The string to use when joining segments of the built label together (defaults to ', ')
4613 labelConnector: ', ',
4616 * @cfg {Object} defaults Any default properties to assign to the child fields.
4620 //Builds the composite field label
4621 initComponent: function() {
4626 for (var i=0, j = items.length; i < j; i++) {
4629 if (!Ext.isEmpty(item.ref)){
4630 item.ref = '../' + item.ref;
4633 labels.push(item.fieldLabel);
4635 //apply any defaults
4636 Ext.applyIf(item, this.defaults);
4638 //apply default margins to each item except the last
4639 if (!(i == j - 1 && this.skipLastItemMargin)) {
4640 Ext.applyIf(item, {margins: this.defaultMargins});
4644 this.fieldLabel = this.fieldLabel || this.buildLabel(labels);
4647 * @property fieldErrors
4648 * @type Ext.util.MixedCollection
4649 * MixedCollection of current errors on the Composite's subfields. This is used internally to track when
4650 * to show and hide error messages at the Composite level. Listeners are attached to the MixedCollection's
4651 * add, remove and replace events to update the error icon in the UI as errors are added or removed.
4653 this.fieldErrors = new Ext.util.MixedCollection(true, function(item) {
4657 this.fieldErrors.on({
4659 add : this.updateInvalidMark,
4660 remove : this.updateInvalidMark,
4661 replace: this.updateInvalidMark
4664 Ext.form.CompositeField.superclass.initComponent.apply(this, arguments);
4666 this.innerCt = new Ext.Container({
4669 cls : 'x-form-composite',
4670 defaultMargins: '0 3 0 0',
4673 this.innerCt.ownerCt = undefined;
4675 var fields = this.innerCt.findBy(function(c) {
4676 return c.isFormField;
4681 * @type Ext.util.MixedCollection
4682 * Internal collection of all of the subfields in this Composite
4684 this.items = new Ext.util.MixedCollection();
4685 this.items.addAll(fields);
4691 * Creates an internal container using hbox and renders the fields to it
4693 onRender: function(ct, position) {
4697 * @type Ext.Container
4698 * A container configured with hbox layout which is responsible for laying out the subfields
4700 var innerCt = this.innerCt;
4703 this.el = innerCt.getEl();
4705 //if we're combining subfield errors into a single message, override the markInvalid and clearInvalid
4706 //methods of each subfield and show them at the Composite level instead
4707 if (this.combineErrors) {
4708 this.eachItem(function(field) {
4710 markInvalid : this.onFieldMarkInvalid.createDelegate(this, [field], 0),
4711 clearInvalid: this.onFieldClearInvalid.createDelegate(this, [field], 0)
4716 //set the label 'for' to the first item
4717 var l = this.el.parent().parent().child('label', true);
4719 l.setAttribute('for', this.items.items[0].id);
4723 Ext.form.CompositeField.superclass.onRender.apply(this, arguments);
4727 * Called if combineErrors is true and a subfield's markInvalid method is called.
4728 * By default this just adds the subfield's error to the internal fieldErrors MixedCollection
4729 * @param {Ext.form.Field} field The field that was marked invalid
4730 * @param {String} message The error message
4732 onFieldMarkInvalid: function(field, message) {
4733 var name = field.getName(),
4736 errorName: field.fieldLabel || name,
4740 this.fieldErrors.replace(name, error);
4742 field.el.addClass(field.invalidClass);
4746 * Called if combineErrors is true and a subfield's clearInvalid method is called.
4747 * By default this just updates the internal fieldErrors MixedCollection.
4748 * @param {Ext.form.Field} field The field that was marked invalid
4750 onFieldClearInvalid: function(field) {
4751 this.fieldErrors.removeKey(field.getName());
4753 field.el.removeClass(field.invalidClass);
4758 * Called after a subfield is marked valid or invalid, this checks to see if any of the subfields are
4759 * currently invalid. If any subfields are invalid it builds a combined error message marks the composite
4760 * invalid, otherwise clearInvalid is called
4762 updateInvalidMark: function() {
4763 var ieStrict = Ext.isIE6 && Ext.isStrict;
4765 if (this.fieldErrors.length == 0) {
4766 this.clearInvalid();
4768 //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
4770 this.clearInvalid.defer(50, this);
4773 var message = this.buildCombinedErrorMessage(this.fieldErrors.items);
4776 this.markInvalid(message);
4778 //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
4780 this.markInvalid(message);
4786 * Performs validation checks on each subfield and returns false if any of them fail validation.
4787 * @return {Boolean} False if any subfield failed validation
4789 validateValue: function() {
4792 this.eachItem(function(field) {
4793 if (!field.isValid()) valid = false;
4800 * Takes an object containing error messages for contained fields, returning a combined error
4801 * string (defaults to just placing each item on a new line). This can be overridden to provide
4802 * custom combined error message handling.
4803 * @param {Array} errors Array of errors in format: [{field: 'title', error: 'some error'}]
4804 * @return {String} The combined error message
4806 buildCombinedErrorMessage: function(errors) {
4810 for (var i = 0, j = errors.length; i < j; i++) {
4813 combined.push(String.format("{0}: {1}", error.errorName, error.error));
4816 return combined.join("<br />");
4820 * Sorts the internal fieldErrors MixedCollection by the order in which the fields are defined.
4821 * This is called before displaying errors to ensure that the errors are presented in the expected order.
4822 * This function can be overridden to provide a custom sorting order if needed.
4824 sortErrors: function() {
4825 var fields = this.items;
4827 this.fieldErrors.sort("ASC", function(a, b) {
4828 var findByName = function(key) {
4829 return function(field) {
4830 return field.getName() == key;
4834 var aIndex = fields.findIndexBy(findByName(a.field)),
4835 bIndex = fields.findIndexBy(findByName(b.field));
4837 return aIndex < bIndex ? -1 : 1;
4842 * Resets each field in the composite to their previous value
4845 this.eachItem(function(item) {
4849 // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
4850 // Important because reset is being called on both the group and the individual items.
4852 this.clearInvalid();
4857 * Calls clearInvalid on all child fields. This is a convenience function and should not often need to be called
4858 * as fields usually take care of clearing themselves
4860 clearInvalidChildren: function() {
4861 this.eachItem(function(item) {
4862 item.clearInvalid();
4867 * Builds a label string from an array of subfield labels.
4868 * By default this just joins the labels together with a comma
4869 * @param {Array} segments Array of each of the labels in the composite field's subfields
4870 * @return {String} The built label
4872 buildLabel: function(segments) {
4873 return Ext.clean(segments).join(this.labelConnector);
4877 * Checks each field in the composite and returns true if any is dirty
4878 * @return {Boolean} True if any field is dirty
4880 isDirty: function(){
4881 //override the behaviour to check sub items.
4882 if (this.disabled || !this.rendered) {
4887 this.eachItem(function(item){
4898 * Convenience function which passes the given function to every item in the composite
4899 * @param {Function} fn The function to call
4900 * @param {Object} scope Optional scope object
4902 eachItem: function(fn, scope) {
4903 if(this.items && this.items.each){
4904 this.items.each(fn, scope || this);
4910 * Passes the resize call through to the inner panel
4912 onResize: function(adjWidth, adjHeight, rawWidth, rawHeight) {
4913 var innerCt = this.innerCt;
4915 if (this.rendered && innerCt.rendered) {
4916 innerCt.setSize(adjWidth, adjHeight);
4919 Ext.form.CompositeField.superclass.onResize.apply(this, arguments);
4924 * Forces the internal container to be laid out again
4926 doLayout: function(shallow, force) {
4927 if (this.rendered) {
4928 var innerCt = this.innerCt;
4930 innerCt.forceLayout = this.ownerCt.forceLayout;
4931 innerCt.doLayout(shallow, force);
4938 beforeDestroy: function(){
4939 Ext.destroy(this.innerCt);
4941 Ext.form.CompositeField.superclass.beforeDestroy.call(this);
4944 //override the behaviour to check sub items.
4945 setReadOnly : function(readOnly) {
4946 if (readOnly == undefined) {
4949 readOnly = !!readOnly;
4952 this.eachItem(function(item){
4953 item.setReadOnly(readOnly);
4956 this.readOnly = readOnly;
4959 onShow : function() {
4960 Ext.form.CompositeField.superclass.onShow.call(this);
4964 //override the behaviour to check sub items.
4965 onDisable : function(){
4966 this.eachItem(function(item){
4971 //override the behaviour to check sub items.
4972 onEnable : function(){
4973 this.eachItem(function(item){
4979 Ext.reg('compositefield', Ext.form.CompositeField);/**
4980 * @class Ext.form.Radio
4981 * @extends Ext.form.Checkbox
4982 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
4983 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
4985 * Creates a new Radio
4986 * @param {Object} config Configuration options
4989 Ext.form.Radio = Ext.extend(Ext.form.Checkbox, {
4993 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
4996 markInvalid : Ext.emptyFn,
4998 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
5001 clearInvalid : Ext.emptyFn,
5004 * If this radio is part of a group, it will return the selected value
5007 getGroupValue : function(){
5008 var p = this.el.up('form') || Ext.getBody();
5009 var c = p.child('input[name='+this.el.dom.name+']:checked', true);
5010 return c ? c.value : null;
5014 * Sets either the checked/unchecked status of this Radio, or, if a string value
5015 * is passed, checks a sibling Radio of the same name whose value is the value specified.
5016 * @param value {String/Boolean} Checked value, or the value of the sibling radio button to check.
5017 * @return {Ext.form.Field} this
5019 setValue : function(v){
5023 if (typeof v == 'boolean') {
5024 Ext.form.Radio.superclass.setValue.call(this, v);
5025 } else if (this.rendered) {
5026 checkEl = this.getCheckEl();
5027 radio = checkEl.child('input[name=' + this.el.dom.name + '][value=' + v + ']', true);
5029 Ext.getCmp(radio.id).setValue(true);
5032 if(this.rendered && this.checked){
5033 checkEl = checkEl || this.getCheckEl();
5034 els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
5035 els.each(function(el){
5036 if(el.dom.id != this.id){
5037 Ext.getCmp(el.dom.id).setValue(false);
5045 getCheckEl: function(){
5047 return this.el.up('.x-form-radio-group');
5049 return this.el.up('form') || Ext.getBody();
5052 Ext.reg('radio', Ext.form.Radio);
5054 * @class Ext.form.RadioGroup
5055 * @extends Ext.form.CheckboxGroup
5056 * A grouping container for {@link Ext.form.Radio} controls.
5058 * Creates a new RadioGroup
5059 * @param {Object} config Configuration options
5062 Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, {
5064 * @cfg {Array} items An Array of {@link Ext.form.Radio Radio}s or Radio config objects
5065 * to arrange in the group.
5068 * @cfg {Boolean} allowBlank True to allow every item in the group to be blank (defaults to true).
5069 * If allowBlank = false and no items are selected at validation time, {@link @blankText} will
5070 * be used as the error text.
5074 * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
5075 * (defaults to 'You must select one item in this group')
5077 blankText : 'You must select one item in this group',
5080 defaultType : 'radio',
5083 groupCls : 'x-form-radio-group',
5087 * Fires when the state of a child radio changes.
5088 * @param {Ext.form.RadioGroup} this
5089 * @param {Ext.form.Radio} checked The checked radio
5093 * Gets the selected {@link Ext.form.Radio} in the group, if it exists.
5094 * @return {Ext.form.Radio} The selected radio.
5096 getValue : function(){
5098 this.eachItem(function(item){
5108 * Sets the checked radio in the group.
5109 * @param {String/Ext.form.Radio} id The radio to check.
5110 * @param {Boolean} value The value to set the radio.
5111 * @return {Ext.form.RadioGroup} this
5113 onSetValue : function(id, value){
5114 if(arguments.length > 1){
5115 var f = this.getBox(id);
5119 this.eachItem(function(item){
5121 item.setValue(false);
5127 this.setValueForItem(id);
5131 setValueForItem : function(val){
5132 val = String(val).split(',')[0];
5133 this.eachItem(function(item){
5134 item.setValue(val == item.inputValue);
5139 fireChecked : function(){
5140 if(!this.checkTask){
5141 this.checkTask = new Ext.util.DelayedTask(this.bufferChecked, this);
5143 this.checkTask.delay(10);
5147 bufferChecked : function(){
5149 this.eachItem(function(item){
5155 this.fireEvent('change', this, out);
5158 onDestroy : function(){
5160 this.checkTask.cancel();
5161 this.checkTask = null;
5163 Ext.form.RadioGroup.superclass.onDestroy.call(this);
5168 Ext.reg('radiogroup', Ext.form.RadioGroup);
5170 * @class Ext.form.Hidden
5171 * @extends Ext.form.Field
5172 * A basic hidden field for storing hidden values in forms that need to be passed in the form submit.
5174 * Create a new Hidden field.
5175 * @param {Object} config Configuration options
5178 Ext.form.Hidden = Ext.extend(Ext.form.Field, {
5180 inputType : 'hidden',
5182 shouldLayout: false,
5185 onRender : function(){
5186 Ext.form.Hidden.superclass.onRender.apply(this, arguments);
5190 initEvents : function(){
5191 this.originalValue = this.getValue();
5194 // These are all private overrides
5195 setSize : Ext.emptyFn,
5196 setWidth : Ext.emptyFn,
5197 setHeight : Ext.emptyFn,
5198 setPosition : Ext.emptyFn,
5199 setPagePosition : Ext.emptyFn,
5200 markInvalid : Ext.emptyFn,
5201 clearInvalid : Ext.emptyFn
5203 Ext.reg('hidden', Ext.form.Hidden);/**
5204 * @class Ext.form.BasicForm
5205 * @extends Ext.util.Observable
5206 * <p>Encapsulates the DOM <form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides
5207 * input field management, validation, submission, and form loading services.</p>
5208 * <p>By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}.
5209 * To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.</p>
5210 * <p><b><u>File Uploads</u></b></p>
5211 * <p>{@link #fileUpload File uploads} are not performed using Ajax submission, that
5212 * is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
5213 * manner with the DOM <tt><form></tt> element temporarily modified to have its
5214 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
5215 * to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
5216 * but removed after the return data has been gathered.</p>
5217 * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
5218 * server is using JSON to send the return object, then the
5219 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
5220 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
5221 * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
5222 * "<" as "&lt;", "&" as "&amp;" etc.</p>
5223 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
5224 * is created containing a <tt>responseText</tt> property in order to conform to the
5225 * requirements of event handlers and callbacks.</p>
5226 * <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>
5227 * and some server technologies (notably JEE) may require some custom processing in order to
5228 * retrieve parameter names and parameter values from the packet content.</p>
5230 * @param {Mixed} el The form element or its id
5231 * @param {Object} config Configuration options
5233 Ext.form.BasicForm = Ext.extend(Ext.util.Observable, {
5235 constructor: function(el, config){
5236 Ext.apply(this, config);
5237 if(Ext.isString(this.paramOrder)){
5238 this.paramOrder = this.paramOrder.split(/[\s,|]/);
5241 * A {@link Ext.util.MixedCollection MixedCollection} containing all the Ext.form.Fields in this form.
5242 * @type MixedCollection
5245 this.items = new Ext.util.MixedCollection(false, function(o){
5246 return o.getItemId();
5250 * @event beforeaction
5251 * Fires before any action is performed. Return false to cancel the action.
5252 * @param {Form} this
5253 * @param {Action} action The {@link Ext.form.Action} to be performed
5257 * @event actionfailed
5258 * Fires when an action fails.
5259 * @param {Form} this
5260 * @param {Action} action The {@link Ext.form.Action} that failed
5264 * @event actioncomplete
5265 * Fires when an action is completed.
5266 * @param {Form} this
5267 * @param {Action} action The {@link Ext.form.Action} that completed
5275 Ext.form.BasicForm.superclass.constructor.call(this);
5279 * @cfg {String} method
5280 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
5283 * @cfg {DataReader} reader
5284 * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read
5285 * data when executing 'load' actions. This is optional as there is built-in
5286 * support for processing JSON. For additional information on using an XMLReader
5287 * see the example provided in examples/form/xml-form.html.
5290 * @cfg {DataReader} errorReader
5291 * <p>An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to
5292 * read field error messages returned from 'submit' actions. This is optional
5293 * as there is built-in support for processing JSON.</p>
5294 * <p>The Records which provide messages for the invalid Fields must use the
5295 * Field name (or id) as the Record ID, and must contain a field called 'msg'
5296 * which contains the error message.</p>
5297 * <p>The errorReader does not have to be a full-blown implementation of a
5298 * DataReader. It simply needs to implement a <tt>read(xhr)</tt> function
5299 * which returns an Array of Records in an object with the following
5300 * structure:</p><pre><code>
5302 records: recordArray
5308 * The URL to use for form actions if one isn't supplied in the
5309 * <code>{@link #doAction doAction} options</code>.
5312 * @cfg {Boolean} fileUpload
5313 * Set to true if this form is a file upload.
5314 * <p>File uploads are not performed using normal 'Ajax' techniques, that is they are <b>not</b>
5315 * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
5316 * DOM <tt><form></tt> element temporarily modified to have its
5317 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
5318 * to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
5319 * but removed after the return data has been gathered.</p>
5320 * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
5321 * server is using JSON to send the return object, then the
5322 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
5323 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
5324 * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
5325 * "<" as "&lt;", "&" as "&amp;" etc.</p>
5326 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
5327 * is created containing a <tt>responseText</tt> property in order to conform to the
5328 * requirements of event handlers and callbacks.</p>
5329 * <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>
5330 * and some server technologies (notably JEE) may require some custom processing in order to
5331 * retrieve parameter names and parameter values from the packet content.</p>
5334 * @cfg {Object} baseParams
5335 * <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
5336 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
5339 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
5344 * @cfg {Object} api (Optional) If specified load and submit actions will be handled
5345 * with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}.
5346 * Methods which have been imported by Ext.Direct can be specified here to load and submit
5348 * Such as the following:<pre><code>
5350 load: App.ss.MyProfile.load,
5351 submit: App.ss.MyProfile.submit
5354 * <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
5355 * to customize how the load method is invoked.
5356 * Submit actions will always use a standard form submit. The formHandler configuration must
5357 * be set on the associated server-side method which has been imported by Ext.Direct</p>
5361 * @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
5362 * Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
5363 * <code>load</code> configuration.</p>
5364 * <br><p>Specify the params in the order in which they must be executed on the
5365 * server-side as either (1) an Array of String values, or (2) a String of params
5366 * delimited by either whitespace, comma, or pipe. For example,
5367 * any of the following would be acceptable:</p><pre><code>
5368 paramOrder: ['param1','param2','param3']
5369 paramOrder: 'param1 param2 param3'
5370 paramOrder: 'param1,param2,param3'
5371 paramOrder: 'param1|param2|param'
5374 paramOrder: undefined,
5377 * @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
5378 * <code>load</code> configuration. Send parameters as a collection of named
5379 * arguments (defaults to <tt>false</tt>). Providing a
5380 * <tt>{@link #paramOrder}</tt> nullifies this configuration.
5382 paramsAsHash: false,
5385 * @cfg {String} waitTitle
5386 * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
5388 waitTitle: 'Please Wait...',
5391 activeAction : null,
5394 * @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
5395 * or {@link #setValues}() data instead of when the form was first created. Defaults to <tt>false</tt>.
5397 trackResetOnLoad : false,
5400 * @cfg {Boolean} standardSubmit
5401 * <p>If set to <tt>true</tt>, standard HTML form submits are used instead
5402 * of XHR (Ajax) style form submissions. Defaults to <tt>false</tt>.</p>
5403 * <br><p><b>Note:</b> When using <code>standardSubmit</code>, the
5404 * <code>options</code> to <code>{@link #submit}</code> are ignored because
5405 * Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g.
5406 * <code>baseParams</code> and <code>params</code>), utilize hidden fields
5407 * to submit extra data, for example:</p>
5410 standardSubmit: true,
5414 {@link url}: 'myProcess.php',
5421 handler: function(){
5422 var fp = this.ownerCt.ownerCt,
5423 form = fp.getForm();
5424 if (form.isValid()) {
5425 // check if there are baseParams and if
5426 // hiddent items have been added already
5427 if (fp.baseParams && !fp.paramsAdded) {
5428 // add hidden items for all baseParams
5429 for (i in fp.baseParams) {
5433 value: fp.baseParams[i]
5437 // set a custom flag to prevent re-adding
5438 fp.paramsAdded = true;
5440 form.{@link #submit}();
5448 * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
5449 * element by passing it or its id or mask the form itself by passing in true.
5451 * @property waitMsgTarget
5455 initEl : function(el){
5456 this.el = Ext.get(el);
5457 this.id = this.el.id || Ext.id();
5458 if(!this.standardSubmit){
5459 this.el.on('submit', this.onSubmit, this);
5461 this.el.addClass('x-form');
5465 * Get the HTML form Element
5466 * @return Ext.Element
5473 onSubmit : function(e){
5478 * Destroys this object.
5480 * @param {Boolean} bound true if the object is bound to a form panel. If this is the case
5481 * the FormPanel will take care of destroying certain things, so we're just doubling up.
5483 destroy: function(bound){
5485 this.items.each(function(f){
5488 Ext.destroy(this.el);
5491 this.purgeListeners();
5495 * Returns true if client-side validation on the form is successful.
5498 isValid : function(){
5500 this.items.each(function(f){
5509 * <p>Returns true if any fields in this form have changed from their original values.</p>
5510 * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
5511 * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
5512 * or {@link #loadRecord}.</p>
5515 isDirty : function(){
5517 this.items.each(function(f){
5527 * Performs a predefined action ({@link Ext.form.Action.Submit} or
5528 * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
5529 * to perform application-specific processing.
5530 * @param {String/Object} actionName The name of the predefined action type,
5531 * or instance of {@link Ext.form.Action} to perform.
5532 * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
5533 * All of the config options listed below are supported by both the
5534 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
5535 * actions unless otherwise noted (custom actions could also accept
5536 * other config options):<ul>
5538 * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
5539 * to the form's {@link #url}.)</div></li>
5541 * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
5542 * to the form's method, or POST if not defined)</div></li>
5544 * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
5545 * (defaults to the form's baseParams, or none if not defined)</p>
5546 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
5548 * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
5549 * (defaults to the form's default headers)</div></li>
5551 * <li><b>success</b> : Function<div class="sub-desc">The callback that will
5552 * be invoked after a successful response (see top of
5553 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
5554 * for a description of what constitutes a successful response).
5555 * The function is passed the following parameters:<ul>
5556 * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
5557 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
5558 * <div class="sub-desc">The action object contains these properties of interest:<ul>
5559 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
5560 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
5561 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
5562 * </ul></div></li></ul></div></li>
5564 * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
5565 * failed transaction attempt. The function is passed the following parameters:<ul>
5566 * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
5567 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
5568 * <div class="sub-desc">The action object contains these properties of interest:<ul>
5569 * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
5570 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
5571 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
5572 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
5573 * </ul></div></li></ul></div></li>
5575 * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
5576 * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
5578 * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
5579 * Determines whether a Form's fields are validated in a final call to
5580 * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
5581 * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
5583 * @return {BasicForm} this
5585 doAction : function(action, options){
5586 if(Ext.isString(action)){
5587 action = new Ext.form.Action.ACTION_TYPES[action](this, options);
5589 if(this.fireEvent('beforeaction', this, action) !== false){
5590 this.beforeAction(action);
5591 action.run.defer(100, action);
5597 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
5598 * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
5599 * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
5600 * <p>The following code:</p><pre><code>
5601 myFormPanel.getForm().submit({
5602 clientValidation: true,
5603 url: 'updateConsignment.php',
5605 newStatus: 'delivered'
5607 success: function(form, action) {
5608 Ext.Msg.alert('Success', action.result.msg);
5610 failure: function(form, action) {
5611 switch (action.failureType) {
5612 case Ext.form.Action.CLIENT_INVALID:
5613 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
5615 case Ext.form.Action.CONNECT_FAILURE:
5616 Ext.Msg.alert('Failure', 'Ajax communication failed');
5618 case Ext.form.Action.SERVER_INVALID:
5619 Ext.Msg.alert('Failure', action.result.msg);
5624 * would process the following server response for a successful submission:<pre><code>
5626 "success":true, // note this is Boolean, not string
5627 "msg":"Consignment updated"
5630 * and the following server response for a failed submission:<pre><code>
5632 "success":false, // note this is Boolean, not string
5633 "msg":"You do not have permission to perform this operation"
5636 * @return {BasicForm} this
5638 submit : function(options){
5639 options = options || {};
5640 if(this.standardSubmit){
5641 var v = options.clientValidation === false || this.isValid();
5643 var el = this.el.dom;
5644 if(this.url && Ext.isEmpty(el.action)){
5645 el.action = this.url;
5651 var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
5652 this.doAction(submitAction, options);
5657 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
5658 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
5659 * @return {BasicForm} this
5661 load : function(options){
5662 var loadAction = String.format('{0}load', this.api ? 'direct' : '');
5663 this.doAction(loadAction, options);
5668 * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
5669 * @param {Record} record The record to edit
5670 * @return {BasicForm} this
5672 updateRecord : function(record){
5674 var fs = record.fields,
5677 fs.each(function(f){
5678 field = this.findField(f.name);
5680 value = field.getValue();
5681 if (typeof value != undefined && value.getGroupValue) {
5682 value = value.getGroupValue();
5683 } else if ( field.eachItem ) {
5685 field.eachItem(function(item){
5686 value.push(item.getValue());
5689 record.set(f.name, value);
5697 * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
5698 * {@link Ext.data.Record#data record data}.
5699 * See also {@link #trackResetOnLoad}.
5700 * @param {Record} record The record to load
5701 * @return {BasicForm} this
5703 loadRecord : function(record){
5704 this.setValues(record.data);
5709 beforeAction : function(action){
5710 // Call HtmlEditor's syncValue before actions
5711 this.items.each(function(f){
5712 if(f.isFormField && f.syncValue){
5716 var o = action.options;
5718 if(this.waitMsgTarget === true){
5719 this.el.mask(o.waitMsg, 'x-mask-loading');
5720 }else if(this.waitMsgTarget){
5721 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
5722 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
5724 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
5730 afterAction : function(action, success){
5731 this.activeAction = null;
5732 var o = action.options;
5734 if(this.waitMsgTarget === true){
5736 }else if(this.waitMsgTarget){
5737 this.waitMsgTarget.unmask();
5739 Ext.MessageBox.updateProgress(1);
5740 Ext.MessageBox.hide();
5747 Ext.callback(o.success, o.scope, [this, action]);
5748 this.fireEvent('actioncomplete', this, action);
5750 Ext.callback(o.failure, o.scope, [this, action]);
5751 this.fireEvent('actionfailed', this, action);
5756 * Find a {@link Ext.form.Field} in this form.
5757 * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
5758 * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
5761 findField : function(id) {
5762 var field = this.items.get(id);
5764 if (!Ext.isObject(field)) {
5765 //searches for the field corresponding to the given id. Used recursively for composite fields
5766 var findMatchingField = function(f) {
5767 if (f.isFormField) {
5768 if (f.dataIndex == id || f.id == id || f.getName() == id) {
5771 } else if (f.isComposite) {
5772 return f.items.each(findMatchingField);
5773 } else if (f instanceof Ext.form.CheckboxGroup && f.rendered) {
5774 return f.eachItem(findMatchingField);
5779 this.items.each(findMatchingField);
5781 return field || null;
5786 * Mark fields in this form invalid in bulk.
5787 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
5788 * @return {BasicForm} this
5790 markInvalid : function(errors){
5791 if (Ext.isArray(errors)) {
5792 for(var i = 0, len = errors.length; i < len; i++){
5793 var fieldError = errors[i];
5794 var f = this.findField(fieldError.id);
5796 f.markInvalid(fieldError.msg);
5802 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
5803 field.markInvalid(errors[id]);
5812 * Set values for fields in this form in bulk.
5813 * @param {Array/Object} values Either an array in the form:<pre><code>
5814 [{id:'clientName', value:'Fred. Olsen Lines'},
5815 {id:'portOfLoading', value:'FXT'},
5816 {id:'portOfDischarge', value:'OSL'} ]</code></pre>
5817 * or an object hash of the form:<pre><code>
5819 clientName: 'Fred. Olsen Lines',
5820 portOfLoading: 'FXT',
5821 portOfDischarge: 'OSL'
5823 * @return {BasicForm} this
5825 setValues : function(values){
5826 if(Ext.isArray(values)){ // array of objects
5827 for(var i = 0, len = values.length; i < len; i++){
5829 var f = this.findField(v.id);
5831 f.setValue(v.value);
5832 if(this.trackResetOnLoad){
5833 f.originalValue = f.getValue();
5837 }else{ // object hash
5840 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
5841 field.setValue(values[id]);
5842 if(this.trackResetOnLoad){
5843 field.originalValue = field.getValue();
5852 * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
5853 * If multiple fields exist with the same name they are returned as an array.</p>
5854 * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
5855 * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
5856 * value can potentially be the emptyText of a field.</p>
5857 * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
5858 * @return {String/Object}
5860 getValues : function(asString){
5861 var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
5862 if(asString === true){
5865 return Ext.urlDecode(fs);
5869 * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
5870 * If multiple fields exist with the same name they are returned as an array.
5871 * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
5872 * @return {Object} The values in the form
5874 getFieldValues : function(dirtyOnly){
5879 this.items.each(function(f) {
5880 if (!f.disabled && (dirtyOnly !== true || f.isDirty())) {
5885 if(Ext.isDefined(key)){
5886 if(Ext.isArray(key)){
5900 * Clears all invalid messages in this form.
5901 * @return {BasicForm} this
5903 clearInvalid : function(){
5904 this.items.each(function(f){
5912 * @return {BasicForm} this
5915 this.items.each(function(f){
5922 * Add Ext.form Components to this form's Collection. This does not result in rendering of
5923 * the passed Component, it just enables the form to validate Fields, and distribute values to
5925 * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
5926 * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
5927 * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
5928 * collection.</b></p>
5929 * @param {Field} field1
5930 * @param {Field} field2 (optional)
5931 * @param {Field} etc (optional)
5932 * @return {BasicForm} this
5935 this.items.addAll(Array.prototype.slice.call(arguments, 0));
5940 * Removes a field from the items collection (does NOT remove its markup).
5941 * @param {Field} field
5942 * @return {BasicForm} this
5944 remove : function(field){
5945 this.items.remove(field);
5950 * Removes all fields from the collection that have been destroyed.
5952 cleanDestroyed : function() {
5953 this.items.filterBy(function(o) { return !!o.isDestroyed; }).each(this.remove, this);
5957 * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
5958 * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
5959 * @return {BasicForm} this
5961 render : function(){
5962 this.items.each(function(f){
5963 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
5964 f.applyToMarkup(f.id);
5971 * Calls {@link Ext#apply} for all fields in this form with the passed object.
5972 * @param {Object} values
5973 * @return {BasicForm} this
5975 applyToFields : function(o){
5976 this.items.each(function(f){
5983 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
5984 * @param {Object} values
5985 * @return {BasicForm} this
5987 applyIfToFields : function(o){
5988 this.items.each(function(f){
5994 callFieldMethod : function(fnName, args){
5996 this.items.each(function(f){
5997 if(Ext.isFunction(f[fnName])){
5998 f[fnName].apply(f, args);
6006 Ext.BasicForm = Ext.form.BasicForm;
6008 * @class Ext.form.FormPanel
6009 * @extends Ext.Panel
6010 * <p>Standard form container.</p>
6012 * <p><b><u>Layout</u></b></p>
6013 * <p>By default, FormPanel is configured with <tt>layout:'form'</tt> to use an {@link Ext.layout.FormLayout}
6014 * layout manager, which styles and renders fields and labels correctly. When nesting additional Containers
6015 * within a FormPanel, you should ensure that any descendant Containers which host input Fields use the
6016 * {@link Ext.layout.FormLayout} layout manager.</p>
6018 * <p><b><u>BasicForm</u></b></p>
6019 * <p>Although <b>not listed</b> as configuration options of FormPanel, the FormPanel class accepts all
6020 * of the config options required to configure its internal {@link Ext.form.BasicForm} for:
6021 * <div class="mdetail-params"><ul>
6022 * <li>{@link Ext.form.BasicForm#fileUpload file uploads}</li>
6023 * <li>functionality for {@link Ext.form.BasicForm#doAction loading, validating and submitting} the form</li>
6026 * <p><b>Note</b>: If subclassing FormPanel, any configuration options for the BasicForm must be applied to
6027 * the <tt><b>initialConfig</b></tt> property of the FormPanel. Applying {@link Ext.form.BasicForm BasicForm}
6028 * configuration settings to <b><tt>this</tt></b> will <b>not</b> affect the BasicForm's configuration.</p>
6030 * <p><b><u>Form Validation</u></b></p>
6031 * <p>For information on form validation see the following:</p>
6032 * <div class="mdetail-params"><ul>
6033 * <li>{@link Ext.form.TextField}</li>
6034 * <li>{@link Ext.form.VTypes}</li>
6035 * <li>{@link Ext.form.BasicForm#doAction BasicForm.doAction <b>clientValidation</b> notes}</li>
6036 * <li><tt>{@link Ext.form.FormPanel#monitorValid monitorValid}</tt></li>
6039 * <p><b><u>Form Submission</u></b></p>
6040 * <p>By default, Ext Forms are submitted through Ajax, using {@link Ext.form.Action}. To enable normal browser
6041 * submission of the {@link Ext.form.BasicForm BasicForm} contained in this FormPanel, see the
6042 * <tt><b>{@link Ext.form.BasicForm#standardSubmit standardSubmit}</b></tt> option.</p>
6045 * @param {Object} config Configuration options
6048 Ext.FormPanel = Ext.extend(Ext.Panel, {
6050 * @cfg {String} formId (optional) The id of the FORM tag (defaults to an auto-generated id).
6053 * @cfg {Boolean} hideLabels
6054 * <p><tt>true</tt> to hide field labels by default (sets <tt>display:none</tt>). Defaults to
6055 * <tt>false</tt>.</p>
6056 * <p>Also see {@link Ext.Component}.<tt>{@link Ext.Component#hideLabel hideLabel}</tt>.
6059 * @cfg {Number} labelPad
6060 * The default padding in pixels for field labels (defaults to <tt>5</tt>). <tt>labelPad</tt> only
6061 * applies if <tt>{@link #labelWidth}</tt> is also specified, otherwise it will be ignored.
6064 * @cfg {String} labelSeparator
6065 * See {@link Ext.Component}.<tt>{@link Ext.Component#labelSeparator labelSeparator}</tt>
6068 * @cfg {Number} labelWidth The width of labels in pixels. This property cascades to child containers
6069 * and can be overridden on any child container (e.g., a fieldset can specify a different <tt>labelWidth</tt>
6070 * for its fields) (defaults to <tt>100</tt>).
6073 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
6076 * @cfg {Array} buttons
6077 * An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this FormPanel.<br>
6078 * <p>Buttons in the footer of a FormPanel may be configured with the option <tt>formBind: true</tt>. This causes
6079 * the form's {@link #monitorValid valid state monitor task} to enable/disable those Buttons depending on
6080 * the form's valid/invalid state.</p>
6085 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to <tt>75</tt>).
6087 minButtonWidth : 75,
6090 * @cfg {String} labelAlign The label alignment value used for the <tt>text-align</tt> specification
6091 * for the <b>container</b>. Valid values are <tt>"left</tt>", <tt>"top"</tt> or <tt>"right"</tt>
6092 * (defaults to <tt>"left"</tt>). This property cascades to child <b>containers</b> and can be
6093 * overridden on any child <b>container</b> (e.g., a fieldset can specify a different <tt>labelAlign</tt>
6096 labelAlign : 'left',
6099 * @cfg {Boolean} monitorValid If <tt>true</tt>, the form monitors its valid state <b>client-side</b> and
6100 * regularly fires the {@link #clientvalidation} event passing that state.<br>
6101 * <p>When monitoring valid state, the FormPanel enables/disables any of its configured
6102 * {@link #buttons} which have been configured with <code>formBind: true</code> depending
6103 * on whether the {@link Ext.form.BasicForm#isValid form is valid} or not. Defaults to <tt>false</tt></p>
6105 monitorValid : false,
6108 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
6113 * @cfg {String} layout Defaults to <tt>'form'</tt>. Normally this configuration property should not be altered.
6114 * For additional details see {@link Ext.layout.FormLayout} and {@link Ext.Container#layout Ext.Container.layout}.
6119 initComponent : function(){
6120 this.form = this.createForm();
6121 Ext.FormPanel.superclass.initComponent.call(this);
6125 cls: this.baseCls + '-body',
6126 method : this.method || 'POST',
6127 id : this.formId || Ext.id()
6129 if(this.fileUpload) {
6130 this.bodyCfg.enctype = 'multipart/form-data';
6136 * @event clientvalidation
6137 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
6138 * @param {Ext.form.FormPanel} this
6139 * @param {Boolean} valid true if the form has passed client-side validation
6144 this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']);
6148 createForm : function(){
6149 var config = Ext.applyIf({listeners: {}}, this.initialConfig);
6150 return new Ext.form.BasicForm(null, config);
6154 initFields : function(){
6156 var formPanel = this;
6157 var fn = function(c){
6158 if(formPanel.isField(c)){
6160 }else if(c.findBy && c != formPanel){
6161 formPanel.applySettings(c);
6162 //each check required for check/radio groups.
6163 if(c.items && c.items.each){
6164 c.items.each(fn, this);
6168 this.items.each(fn, this);
6172 applySettings: function(c){
6175 labelAlign: ct.labelAlign,
6176 labelWidth: ct.labelWidth,
6182 getLayoutTarget : function(){
6183 return this.form.el;
6187 * Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains.
6188 * @return {Ext.form.BasicForm} The {@link Ext.form.BasicForm Form} which this Panel contains.
6190 getForm : function(){
6195 onRender : function(ct, position){
6197 Ext.FormPanel.superclass.onRender.call(this, ct, position);
6198 this.form.initEl(this.body);
6202 beforeDestroy : function(){
6203 this.stopMonitoring();
6204 this.form.destroy(true);
6205 Ext.FormPanel.superclass.beforeDestroy.call(this);
6208 // Determine if a Component is usable as a form Field.
6209 isField : function(c) {
6210 return !!c.setValue && !!c.getValue && !!c.markInvalid && !!c.clearInvalid;
6214 initEvents : function(){
6215 Ext.FormPanel.superclass.initEvents.call(this);
6216 // Listeners are required here to catch bubbling events from children.
6219 add: this.onAddEvent,
6220 remove: this.onRemoveEvent
6222 if(this.monitorValid){ // initialize after render
6223 this.startMonitoring();
6229 Ext.FormPanel.superclass.onAdd.call(this, c);
6234 onAddEvent: function(ct, c){
6241 processAdd : function(c){
6242 // If a single form Field, add it
6243 if(this.isField(c)){
6245 // If a Container, add any Fields it might contain
6247 this.applySettings(c);
6248 this.form.add.apply(this.form, c.findBy(this.isField));
6253 onRemove: function(c){
6254 Ext.FormPanel.superclass.onRemove.call(this, c);
6255 this.processRemove(c);
6258 onRemoveEvent: function(ct, c){
6260 this.processRemove(c);
6265 processRemove: function(c){
6266 if(!this.destroying){
6267 // If a single form Field, remove it
6268 if(this.isField(c)){
6269 this.form.remove(c);
6270 // If a Container, its already destroyed by the time it gets here. Remove any references to destroyed fields.
6271 }else if (c.findBy){
6272 Ext.each(c.findBy(this.isField), this.form.remove, this.form);
6274 * This isn't the most efficient way of getting rid of the items, however it's the most
6275 * correct, which in this case is most important.
6277 this.form.cleanDestroyed();
6283 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
6284 * option "monitorValid"
6286 startMonitoring : function(){
6287 if(!this.validTask){
6288 this.validTask = new Ext.util.TaskRunner();
6289 this.validTask.start({
6290 run : this.bindHandler,
6291 interval : this.monitorPoll || 200,
6298 * Stops monitoring of the valid state of this form
6300 stopMonitoring : function(){
6302 this.validTask.stopAll();
6303 this.validTask = null;
6308 * This is a proxy for the underlying BasicForm's {@link Ext.form.BasicForm#load} call.
6309 * @param {Object} options The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details)
6312 this.form.load.apply(this.form, arguments);
6316 onDisable : function(){
6317 Ext.FormPanel.superclass.onDisable.call(this);
6319 this.form.items.each(function(){
6326 onEnable : function(){
6327 Ext.FormPanel.superclass.onEnable.call(this);
6329 this.form.items.each(function(){
6336 bindHandler : function(){
6338 this.form.items.each(function(f){
6339 if(!f.isValid(true)){
6345 var fitems = this.fbar.items.items;
6346 for(var i = 0, len = fitems.length; i < len; i++){
6347 var btn = fitems[i];
6348 if(btn.formBind === true && btn.disabled === valid){
6349 btn.setDisabled(!valid);
6353 this.fireEvent('clientvalidation', this, valid);
6356 Ext.reg('form', Ext.FormPanel);
6358 Ext.form.FormPanel = Ext.FormPanel;
6360 * @class Ext.form.FieldSet
6361 * @extends Ext.Panel
6362 * Standard container used for grouping items within a {@link Ext.form.FormPanel form}.
6364 var form = new Ext.FormPanel({
6365 title: 'Simple Form with FieldSets',
6366 labelWidth: 75, // label settings here cascade unless overridden
6367 url: 'save-form.php',
6369 bodyStyle:'padding:5px 5px 0',
6371 renderTo: document.body,
6372 layout:'column', // arrange items in columns
6373 defaults: { // defaults applied to items
6376 bodyStyle: 'padding:4px'
6379 // Fieldset in Column 1
6382 title: 'Fieldset 1',
6386 anchor: '-20' // leave room for error icon
6388 defaultType: 'textfield',
6390 fieldLabel: 'Field 1'
6392 fieldLabel: 'Field 2'
6394 fieldLabel: 'Field 3'
6398 // Fieldset in Column 2 - Panel inside
6400 title: 'Show Panel', // title, header, or checkboxToggle creates fieldset header
6403 checkboxToggle: true,
6404 collapsed: true, // fieldset initially collapsed
6409 title: 'Panel inside a fieldset',
6417 * @param {Object} config Configuration options
6420 Ext.form.FieldSet = Ext.extend(Ext.Panel, {
6422 * @cfg {Mixed} checkboxToggle <tt>true</tt> to render a checkbox into the fieldset frame just
6423 * in front of the legend to expand/collapse the fieldset when the checkbox is toggled. (defaults
6424 * to <tt>false</tt>).
6425 * <p>A {@link Ext.DomHelper DomHelper} element spec may also be specified to create the checkbox.
6426 * If <tt>true</tt> is specified, the default DomHelper config object used to create the element
6427 * is:</p><pre><code>
6428 * {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}
6432 * @cfg {String} checkboxName The name to assign to the fieldset's checkbox if <tt>{@link #checkboxToggle} = true</tt>
6433 * (defaults to <tt>'[checkbox id]-checkbox'</tt>).
6436 * @cfg {Boolean} collapsible
6437 * <tt>true</tt> to make the fieldset collapsible and have the expand/collapse toggle button automatically
6438 * rendered into the legend element, <tt>false</tt> to keep the fieldset statically sized with no collapse
6439 * button (defaults to <tt>false</tt>). Another option is to configure <tt>{@link #checkboxToggle}</tt>.
6442 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
6445 * @cfg {String} itemCls A css class to apply to the <tt>x-form-item</tt> of fields (see
6446 * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} for details).
6447 * This property cascades to child containers.
6450 * @cfg {String} baseCls The base CSS class applied to the fieldset (defaults to <tt>'x-fieldset'</tt>).
6452 baseCls : 'x-fieldset',
6454 * @cfg {String} layout The {@link Ext.Container#layout} to use inside the fieldset (defaults to <tt>'form'</tt>).
6458 * @cfg {Boolean} animCollapse
6459 * <tt>true</tt> to animate the transition when the panel is collapsed, <tt>false</tt> to skip the
6460 * animation (defaults to <tt>false</tt>).
6462 animCollapse : false,
6465 onRender : function(ct, position){
6467 this.el = document.createElement('fieldset');
6468 this.el.id = this.id;
6469 if (this.title || this.header || this.checkboxToggle) {
6470 this.el.appendChild(document.createElement('legend')).className = this.baseCls + '-header';
6474 Ext.form.FieldSet.superclass.onRender.call(this, ct, position);
6476 if(this.checkboxToggle){
6477 var o = typeof this.checkboxToggle == 'object' ?
6478 this.checkboxToggle :
6479 {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'};
6480 this.checkbox = this.header.insertFirst(o);
6481 this.checkbox.dom.checked = !this.collapsed;
6482 this.mon(this.checkbox, 'click', this.onCheckClick, this);
6487 onCollapse : function(doAnim, animArg){
6489 this.checkbox.dom.checked = false;
6491 Ext.form.FieldSet.superclass.onCollapse.call(this, doAnim, animArg);
6496 onExpand : function(doAnim, animArg){
6498 this.checkbox.dom.checked = true;
6500 Ext.form.FieldSet.superclass.onExpand.call(this, doAnim, animArg);
6504 * This function is called by the fieldset's checkbox when it is toggled (only applies when
6505 * checkboxToggle = true). This method should never be called externally, but can be
6506 * overridden to provide custom behavior when the checkbox is toggled if needed.
6508 onCheckClick : function(){
6509 this[this.checkbox.dom.checked ? 'expand' : 'collapse']();
6513 * @cfg {String/Number} activeItem
6517 * @cfg {Mixed} applyTo
6521 * @cfg {Boolean} bodyBorder
6525 * @cfg {Boolean} border
6529 * @cfg {Boolean/Number} bufferResize
6533 * @cfg {Boolean} collapseFirst
6537 * @cfg {String} defaultType
6541 * @cfg {String} disabledClass
6545 * @cfg {String} elements
6549 * @cfg {Boolean} floating
6553 * @cfg {Boolean} footer
6557 * @cfg {Boolean} frame
6561 * @cfg {Boolean} header
6565 * @cfg {Boolean} headerAsText
6569 * @cfg {Boolean} hideCollapseTool
6573 * @cfg {String} iconCls
6577 * @cfg {Boolean/String} shadow
6581 * @cfg {Number} shadowOffset
6585 * @cfg {Boolean} shim
6589 * @cfg {Object/Array} tbar
6593 * @cfg {Array} tools
6597 * @cfg {Ext.Template/Ext.XTemplate} toolTemplate
6601 * @cfg {String} xtype
6617 * @method getBottomToolbar
6621 * @method getTopToolbar
6625 * @method setIconClass
6633 * @event beforeclose
6649 Ext.reg('fieldset', Ext.form.FieldSet);/**
6650 * @class Ext.form.HtmlEditor
6651 * @extends Ext.form.Field
6652 * Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be
6653 * automatically hidden when needed. These are noted in the config options where appropriate.
6654 * <br><br>The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not
6655 * enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}.
6656 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
6657 * supported by this editor.</b>
6658 * <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
6659 * any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs.
6660 * <br><br>Example usage:
6662 // Simple example rendered with default options:
6663 Ext.QuickTips.init(); // enable tooltips
6664 new Ext.form.HtmlEditor({
6665 renderTo: Ext.getBody(),
6670 // Passed via xtype into a container and with custom options:
6671 Ext.QuickTips.init(); // enable tooltips
6673 title: 'HTML Editor',
6674 renderTo: Ext.getBody(),
6680 xtype: 'htmleditor',
6681 enableColors: false,
6682 enableAlignments: false
6687 * Create a new HtmlEditor
6688 * @param {Object} config
6692 Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, {
6694 * @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true)
6696 enableFormat : true,
6698 * @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true)
6700 enableFontSize : true,
6702 * @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true)
6704 enableColors : true,
6706 * @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true)
6708 enableAlignments : true,
6710 * @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true)
6714 * @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true)
6716 enableSourceEdit : true,
6718 * @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true)
6722 * @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true)
6726 * @cfg {String} createLinkText The default text for the create link prompt
6728 createLinkText : 'Please enter the URL for the link:',
6730 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
6732 defaultLinkValue : 'http:/'+'/',
6734 * @cfg {Array} fontFamilies An array of available font families
6743 defaultFont: 'tahoma',
6745 * @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).
6747 defaultValue: (Ext.isOpera || Ext.isIE6) ? ' ' : '​',
6749 // private properties
6751 validationEvent : false,
6753 initialized : false,
6755 sourceEditMode : false,
6756 onFocus : Ext.emptyFn,
6759 defaultAutoCreate : {
6761 style:"width:500px;height:300px;",
6766 initComponent : function(){
6770 * Fires when the editor is fully initialized (including the iframe)
6771 * @param {HtmlEditor} this
6776 * Fires when the editor is first receives the focus. Any insertion must wait
6777 * until after this event.
6778 * @param {HtmlEditor} this
6783 * Fires before the textarea is updated with content from the editor iframe. Return false
6784 * to cancel the sync.
6785 * @param {HtmlEditor} this
6786 * @param {String} html
6791 * Fires before the iframe editor is updated with content from the textarea. Return false
6792 * to cancel the push.
6793 * @param {HtmlEditor} this
6794 * @param {String} html
6799 * Fires when the textarea is updated with content from the editor iframe.
6800 * @param {HtmlEditor} this
6801 * @param {String} html
6806 * Fires when the iframe editor is updated with content from the textarea.
6807 * @param {HtmlEditor} this
6808 * @param {String} html
6812 * @event editmodechange
6813 * Fires when the editor switches edit modes
6814 * @param {HtmlEditor} this
6815 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
6819 Ext.form.HtmlEditor.superclass.initComponent.call(this);
6823 createFontOptions : function(){
6824 var buf = [], fs = this.fontFamilies, ff, lc;
6825 for(var i = 0, len = fs.length; i< len; i++){
6827 lc = ff.toLowerCase();
6829 '<option value="',lc,'" style="font-family:',ff,';"',
6830 (this.defaultFont == lc ? ' selected="true">' : '>'),
6835 return buf.join('');
6839 * Protected method that will not generally be called directly. It
6840 * is called when the editor creates its toolbar. Override this method if you need to
6841 * add custom toolbar buttons.
6842 * @param {HtmlEditor} editor
6844 createToolbar : function(editor){
6846 var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled();
6849 function btn(id, toggle, handler){
6853 iconCls: 'x-edit-'+id,
6854 enableToggle:toggle !== false,
6856 handler:handler||editor.relayBtnCmd,
6857 clickEvent:'mousedown',
6858 tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined,
6859 overflowText: editor.buttonTips[id].title || undefined,
6865 if(this.enableFont && !Ext.isSafari2){
6866 var fontSelectItem = new Ext.Toolbar.Item({
6869 cls:'x-font-select',
6870 html: this.createFontOptions()
6880 if(this.enableFormat){
6888 if(this.enableFontSize){
6891 btn('increasefontsize', false, this.adjustFont),
6892 btn('decreasefontsize', false, this.adjustFont)
6896 if(this.enableColors){
6901 iconCls: 'x-edit-forecolor',
6902 clickEvent:'mousedown',
6903 tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined,
6905 menu : new Ext.menu.ColorMenu({
6906 allowReselect: true,
6912 select: function(cp, color){
6913 this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
6917 clickEvent:'mousedown'
6922 iconCls: 'x-edit-backcolor',
6923 clickEvent:'mousedown',
6924 tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined,
6926 menu : new Ext.menu.ColorMenu({
6930 allowReselect: true,
6933 select: function(cp, color){
6935 this.execCmd('useCSS', false);
6936 this.execCmd('hilitecolor', color);
6937 this.execCmd('useCSS', true);
6940 this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
6945 clickEvent:'mousedown'
6951 if(this.enableAlignments){
6955 btn('justifycenter'),
6961 if(this.enableLinks){
6964 btn('createlink', false, this.createLink)
6968 if(this.enableLists){
6971 btn('insertorderedlist'),
6972 btn('insertunorderedlist')
6975 if(this.enableSourceEdit){
6978 btn('sourceedit', true, function(btn){
6979 this.toggleSourceEdit(!this.sourceEditMode);
6985 // build the toolbar
6986 var tb = new Ext.Toolbar({
6987 renderTo: this.wrap.dom.firstChild,
6991 if (fontSelectItem) {
6992 this.fontSelect = fontSelectItem.el;
6994 this.mon(this.fontSelect, 'change', function(){
6995 var font = this.fontSelect.dom.value;
6996 this.relayCmd('fontname', font);
7001 // stop form submits
7002 this.mon(tb.el, 'click', function(e){
7010 onDisable: function(){
7012 Ext.form.HtmlEditor.superclass.onDisable.call(this);
7015 onEnable: function(){
7017 Ext.form.HtmlEditor.superclass.onEnable.call(this);
7020 setReadOnly: function(readOnly){
7022 Ext.form.HtmlEditor.superclass.setReadOnly.call(this, readOnly);
7023 if(this.initialized){
7025 this.getEditorBody().contentEditable = !readOnly;
7027 this.setDesignMode(!readOnly);
7029 var bd = this.getEditorBody();
7031 bd.style.cursor = this.readOnly ? 'default' : 'text';
7033 this.disableItems(readOnly);
7038 * Protected method that will not generally be called directly. It
7039 * is called when the editor initializes the iframe with HTML contents. Override this method if you
7040 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
7042 * Note: IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility
7044 getDocMarkup : function(){
7045 var h = Ext.fly(this.iframe).getHeight() - this.iframePad * 2;
7046 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);
7050 getEditorBody : function(){
7051 var doc = this.getDoc();
7052 return doc.body || doc.documentElement;
7056 getDoc : function(){
7057 return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document);
7061 getWin : function(){
7062 return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name];
7066 onRender : function(ct, position){
7067 Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position);
7068 this.el.dom.style.border = '0 none';
7069 this.el.dom.setAttribute('tabIndex', -1);
7070 this.el.addClass('x-hidden');
7071 if(Ext.isIE){ // fix IE 1px bogus margin
7072 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;');
7074 this.wrap = this.el.wrap({
7075 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
7078 this.createToolbar(this);
7080 this.disableItems(true);
7084 this.createIFrame();
7087 var sz = this.el.getSize();
7088 this.setSize(sz.width, this.height || sz.height);
7090 this.resizeEl = this.positionEl = this.wrap;
7093 createIFrame: function(){
7094 var iframe = document.createElement('iframe');
7095 iframe.name = Ext.id();
7096 iframe.frameBorder = '0';
7097 iframe.style.overflow = 'auto';
7098 iframe.src = Ext.SSL_SECURE_URL;
7100 this.wrap.dom.appendChild(iframe);
7101 this.iframe = iframe;
7103 this.monitorTask = Ext.TaskMgr.start({
7104 run: this.checkDesignMode,
7110 initFrame : function(){
7111 Ext.TaskMgr.stop(this.monitorTask);
7112 var doc = this.getDoc();
7113 this.win = this.getWin();
7116 doc.write(this.getDocMarkup());
7119 var task = { // must defer to wait for browser to be ready
7121 var doc = this.getDoc();
7122 if(doc.body || doc.readyState == 'complete'){
7123 Ext.TaskMgr.stop(task);
7124 this.setDesignMode(true);
7125 this.initEditor.defer(10, this);
7132 Ext.TaskMgr.start(task);
7136 checkDesignMode : function(){
7137 if(this.wrap && this.wrap.dom.offsetWidth){
7138 var doc = this.getDoc();
7142 if(!doc.editorInitialized || this.getDesignMode() != 'on'){
7149 * set current design mode. To enable, mode can be true or 'on', off otherwise
7151 setDesignMode : function(mode){
7152 var doc = this.getDoc();
7157 doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off';
7163 getDesignMode : function(){
7164 var doc = this.getDoc();
7165 if(!doc){ return ''; }
7166 return String(doc.designMode).toLowerCase();
7170 disableItems: function(disabled){
7171 if(this.fontSelect){
7172 this.fontSelect.dom.disabled = disabled;
7174 this.tb.items.each(function(item){
7175 if(item.getItemId() != 'sourceedit'){
7176 item.setDisabled(disabled);
7182 onResize : function(w, h){
7183 Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments);
7184 if(this.el && this.iframe){
7185 if(Ext.isNumber(w)){
7186 var aw = w - this.wrap.getFrameWidth('lr');
7187 this.el.setWidth(aw);
7188 this.tb.setWidth(aw);
7189 this.iframe.style.width = Math.max(aw, 0) + 'px';
7191 if(Ext.isNumber(h)){
7192 var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight();
7193 this.el.setHeight(ah);
7194 this.iframe.style.height = Math.max(ah, 0) + 'px';
7195 var bd = this.getEditorBody();
7197 bd.style.height = Math.max((ah - (this.iframePad*2)), 0) + 'px';
7204 * Toggles the editor between standard and source edit mode.
7205 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
7207 toggleSourceEdit : function(sourceEditMode){
7211 if (sourceEditMode === undefined) {
7212 sourceEditMode = !this.sourceEditMode;
7214 this.sourceEditMode = sourceEditMode === true;
7215 var btn = this.tb.getComponent('sourceedit');
7217 if (btn.pressed !== this.sourceEditMode) {
7218 btn.toggle(this.sourceEditMode);
7219 if (!btn.xtbHidden) {
7223 if (this.sourceEditMode) {
7224 // grab the height of the containing panel before we hide the iframe
7225 this.previousSize = this.getSize();
7227 iframeHeight = Ext.get(this.iframe).getHeight();
7229 this.disableItems(true);
7231 this.iframe.className = 'x-hidden';
7232 this.el.removeClass('x-hidden');
7233 this.el.dom.removeAttribute('tabIndex');
7235 this.el.dom.style.height = iframeHeight + 'px';
7238 elHeight = parseInt(this.el.dom.style.height, 10);
7239 if (this.initialized) {
7240 this.disableItems(this.readOnly);
7243 this.iframe.className = '';
7244 this.el.addClass('x-hidden');
7245 this.el.dom.setAttribute('tabIndex', -1);
7248 this.setSize(this.previousSize);
7249 delete this.previousSize;
7250 this.iframe.style.height = elHeight + 'px';
7252 this.fireEvent('editmodechange', this, this.sourceEditMode);
7255 // private used internally
7256 createLink : function() {
7257 var url = prompt(this.createLinkText, this.defaultLinkValue);
7258 if(url && url != 'http:/'+'/'){
7259 this.relayCmd('createlink', url);
7264 initEvents : function(){
7265 this.originalValue = this.getValue();
7269 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
7272 markInvalid : Ext.emptyFn,
7275 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
7278 clearInvalid : Ext.emptyFn,
7280 // docs inherit from Field
7281 setValue : function(v){
7282 Ext.form.HtmlEditor.superclass.setValue.call(this, v);
7288 * Protected method that will not generally be called directly. If you need/want
7289 * custom HTML cleanup, this is the method you should override.
7290 * @param {String} html The HTML to be cleaned
7291 * @return {String} The cleaned HTML
7293 cleanHtml: function(html) {
7294 html = String(html);
7295 if(Ext.isWebKit){ // strip safari nonsense
7296 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
7300 * Neat little hack. Strips out all the non-digit characters from the default
7301 * value and compares it to the character code of the first character in the string
7302 * because it can cause encoding issues when posted to the server.
7304 if(html.charCodeAt(0) == this.defaultValue.replace(/\D/g, '')){
7305 html = html.substring(1);
7311 * Protected method that will not generally be called directly. Syncs the contents
7312 * of the editor iframe with the textarea.
7314 syncValue : function(){
7315 if(this.initialized){
7316 var bd = this.getEditorBody();
7317 var html = bd.innerHTML;
7319 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
7320 var m = bs.match(/text-align:(.*?);/i);
7322 html = '<div style="'+m[0]+'">' + html + '</div>';
7325 html = this.cleanHtml(html);
7326 if(this.fireEvent('beforesync', this, html) !== false){
7327 this.el.dom.value = html;
7328 this.fireEvent('sync', this, html);
7333 //docs inherit from Field
7334 getValue : function() {
7335 this[this.sourceEditMode ? 'pushValue' : 'syncValue']();
7336 return Ext.form.HtmlEditor.superclass.getValue.call(this);
7340 * Protected method that will not generally be called directly. Pushes the value of the textarea
7341 * into the iframe editor.
7343 pushValue : function(){
7344 if(this.initialized){
7345 var v = this.el.dom.value;
7346 if(!this.activated && v.length < 1){
7347 v = this.defaultValue;
7349 if(this.fireEvent('beforepush', this, v) !== false){
7350 this.getEditorBody().innerHTML = v;
7352 // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8
7353 this.setDesignMode(false); //toggle off first
7354 this.setDesignMode(true);
7356 this.fireEvent('push', this, v);
7363 deferFocus : function(){
7364 this.focus.defer(10, this);
7367 // docs inherit from Field
7369 if(this.win && !this.sourceEditMode){
7377 initEditor : function(){
7378 //Destroying the component during/before initEditor can cause issues.
7380 var dbody = this.getEditorBody(),
7381 ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat', 'background-color', 'color'),
7385 ss['background-attachment'] = 'fixed'; // w3c
7386 dbody.bgProperties = 'fixed'; // ie
7388 Ext.DomHelper.applyStyles(dbody, ss);
7390 doc = this.getDoc();
7394 Ext.EventManager.removeAll(doc);
7399 * We need to use createDelegate here, because when using buffer, the delayed task is added
7400 * as a property to the function. When the listener is removed, the task is deleted from the function.
7401 * Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors
7402 * is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function.
7404 fn = this.onEditorEvent.createDelegate(this);
7405 Ext.EventManager.on(doc, {
7414 Ext.EventManager.on(doc, 'keypress', this.applyCommand, this);
7416 if(Ext.isIE || Ext.isWebKit || Ext.isOpera){
7417 Ext.EventManager.on(doc, 'keydown', this.fixKeys, this);
7419 doc.editorInitialized = true;
7420 this.initialized = true;
7422 this.setReadOnly(this.readOnly);
7423 this.fireEvent('initialize', this);
7428 beforeDestroy : function(){
7429 if(this.monitorTask){
7430 Ext.TaskMgr.stop(this.monitorTask);
7433 Ext.destroy(this.tb);
7434 var doc = this.getDoc();
7437 Ext.EventManager.removeAll(doc);
7438 for (var prop in doc){
7444 this.wrap.dom.innerHTML = '';
7448 Ext.form.HtmlEditor.superclass.beforeDestroy.call(this);
7452 onFirstFocus : function(){
7453 this.activated = true;
7454 this.disableItems(this.readOnly);
7455 if(Ext.isGecko){ // prevent silly gecko errors
7457 var s = this.win.getSelection();
7458 if(!s.focusNode || s.focusNode.nodeType != 3){
7459 var r = s.getRangeAt(0);
7460 r.selectNodeContents(this.getEditorBody());
7465 this.execCmd('useCSS', true);
7466 this.execCmd('styleWithCSS', false);
7469 this.fireEvent('activate', this);
7473 adjustFont: function(btn){
7474 var adjust = btn.getItemId() == 'increasefontsize' ? 1 : -1,
7475 doc = this.getDoc(),
7476 v = parseInt(doc.queryCommandValue('FontSize') || 2, 10);
7477 if((Ext.isSafari && !Ext.isSafari2) || Ext.isChrome || Ext.isAir){
7479 // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px
7493 v = v.constrain(1, 6);
7495 if(Ext.isSafari){ // safari
7498 v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0);
7500 this.execCmd('FontSize', v);
7504 onEditorEvent : function(e){
7505 this.updateToolbar();
7510 * Protected method that will not generally be called directly. It triggers
7511 * a toolbar update by reading the markup state of the current selection in the editor.
7513 updateToolbar: function(){
7519 if(!this.activated){
7520 this.onFirstFocus();
7524 var btns = this.tb.items.map,
7525 doc = this.getDoc();
7527 if(this.enableFont && !Ext.isSafari2){
7528 var name = (doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase();
7529 if(name != this.fontSelect.dom.value){
7530 this.fontSelect.dom.value = name;
7533 if(this.enableFormat){
7534 btns.bold.toggle(doc.queryCommandState('bold'));
7535 btns.italic.toggle(doc.queryCommandState('italic'));
7536 btns.underline.toggle(doc.queryCommandState('underline'));
7538 if(this.enableAlignments){
7539 btns.justifyleft.toggle(doc.queryCommandState('justifyleft'));
7540 btns.justifycenter.toggle(doc.queryCommandState('justifycenter'));
7541 btns.justifyright.toggle(doc.queryCommandState('justifyright'));
7543 if(!Ext.isSafari2 && this.enableLists){
7544 btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist'));
7545 btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist'));
7548 Ext.menu.MenuMgr.hideAll();
7554 relayBtnCmd : function(btn){
7555 this.relayCmd(btn.getItemId());
7559 * Executes a Midas editor command on the editor document and performs necessary focus and
7560 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
7561 * @param {String} cmd The Midas command
7562 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
7564 relayCmd : function(cmd, value){
7567 this.execCmd(cmd, value);
7568 this.updateToolbar();
7573 * Executes a Midas editor command directly on the editor document.
7574 * For visual commands, you should use {@link #relayCmd} instead.
7575 * <b>This should only be called after the editor is initialized.</b>
7576 * @param {String} cmd The Midas command
7577 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
7579 execCmd : function(cmd, value){
7580 var doc = this.getDoc();
7581 doc.execCommand(cmd, false, value === undefined ? null : value);
7586 applyCommand : function(e){
7588 var c = e.getCharCode(), cmd;
7590 c = String.fromCharCode(c);
7613 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
7615 * @param {String} text
7617 insertAtCursor : function(text){
7618 if(!this.activated){
7623 var doc = this.getDoc(),
7624 r = doc.selection.createRange();
7632 this.execCmd('InsertHTML', text);
7638 fixKeys : function(){ // load time branching for fastest keydown performance
7642 doc = this.getDoc(),
7646 r = doc.selection.createRange();
7649 r.pasteHTML(' ');
7652 }else if(k == e.ENTER){
7653 r = doc.selection.createRange();
7655 var target = r.parentElement();
7656 if(!target || target.tagName.toLowerCase() != 'li'){
7658 r.pasteHTML('<br />');
7665 }else if(Ext.isOpera){
7671 this.execCmd('InsertHTML',' ');
7675 }else if(Ext.isWebKit){
7680 this.execCmd('InsertText','\t');
7682 }else if(k == e.ENTER){
7684 this.execCmd('InsertHtml','<br /><br />');
7692 * Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b>
7693 * @return {Ext.Toolbar}
7695 getToolbar : function(){
7700 * Object collection of toolbar tooltips for the buttons in the editor. The key
7701 * is the command id associated with that button and the value is a valid QuickTips object.
7706 title: 'Bold (Ctrl+B)',
7707 text: 'Make the selected text bold.',
7708 cls: 'x-html-editor-tip'
7711 title: 'Italic (Ctrl+I)',
7712 text: 'Make the selected text italic.',
7713 cls: 'x-html-editor-tip'
7721 title: 'Bold (Ctrl+B)',
7722 text: 'Make the selected text bold.',
7723 cls: 'x-html-editor-tip'
7726 title: 'Italic (Ctrl+I)',
7727 text: 'Make the selected text italic.',
7728 cls: 'x-html-editor-tip'
7731 title: 'Underline (Ctrl+U)',
7732 text: 'Underline the selected text.',
7733 cls: 'x-html-editor-tip'
7735 increasefontsize : {
7737 text: 'Increase the font size.',
7738 cls: 'x-html-editor-tip'
7740 decreasefontsize : {
7741 title: 'Shrink Text',
7742 text: 'Decrease the font size.',
7743 cls: 'x-html-editor-tip'
7746 title: 'Text Highlight Color',
7747 text: 'Change the background color of the selected text.',
7748 cls: 'x-html-editor-tip'
7751 title: 'Font Color',
7752 text: 'Change the color of the selected text.',
7753 cls: 'x-html-editor-tip'
7756 title: 'Align Text Left',
7757 text: 'Align text to the left.',
7758 cls: 'x-html-editor-tip'
7761 title: 'Center Text',
7762 text: 'Center text in the editor.',
7763 cls: 'x-html-editor-tip'
7766 title: 'Align Text Right',
7767 text: 'Align text to the right.',
7768 cls: 'x-html-editor-tip'
7770 insertunorderedlist : {
7771 title: 'Bullet List',
7772 text: 'Start a bulleted list.',
7773 cls: 'x-html-editor-tip'
7775 insertorderedlist : {
7776 title: 'Numbered List',
7777 text: 'Start a numbered list.',
7778 cls: 'x-html-editor-tip'
7782 text: 'Make the selected text a hyperlink.',
7783 cls: 'x-html-editor-tip'
7786 title: 'Source Edit',
7787 text: 'Switch to source editing mode.',
7788 cls: 'x-html-editor-tip'
7792 // hide stuff that is not compatible
7810 * @cfg {String} fieldClass @hide
7813 * @cfg {String} focusClass @hide
7816 * @cfg {String} autoCreate @hide
7819 * @cfg {String} inputType @hide
7822 * @cfg {String} invalidClass @hide
7825 * @cfg {String} invalidText @hide
7828 * @cfg {String} msgFx @hide
7831 * @cfg {String} validateOnBlur @hide
7834 * @cfg {Boolean} allowDomMove @hide
7837 * @cfg {String} applyTo @hide
7840 * @cfg {String} autoHeight @hide
7843 * @cfg {String} autoWidth @hide
7846 * @cfg {String} cls @hide
7849 * @cfg {String} disabled @hide
7852 * @cfg {String} disabledClass @hide
7855 * @cfg {String} msgTarget @hide
7858 * @cfg {String} readOnly @hide
7861 * @cfg {String} style @hide
7864 * @cfg {String} validationDelay @hide
7867 * @cfg {String} validationEvent @hide
7870 * @cfg {String} tabIndex @hide
7873 * @property disabled
7877 * @method applyToMarkup
7897 * @method setDisabled
7905 Ext.reg('htmleditor', Ext.form.HtmlEditor);
7907 * @class Ext.form.TimeField
7908 * @extends Ext.form.ComboBox
7909 * Provides a time input field with a time dropdown and automatic time validation. Example usage:
7911 new Ext.form.TimeField({
7912 minValue: '9:00 AM',
7913 maxValue: '6:00 PM',
7918 * Create a new TimeField
7919 * @param {Object} config
7922 Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, {
7924 * @cfg {Date/String} minValue
7925 * The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
7926 * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
7928 minValue : undefined,
7930 * @cfg {Date/String} maxValue
7931 * The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
7932 * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
7934 maxValue : undefined,
7936 * @cfg {String} minText
7937 * The error text to display when the date in the cell is before minValue (defaults to
7938 * 'The time in this field must be equal to or after {0}').
7940 minText : "The time in this field must be equal to or after {0}",
7942 * @cfg {String} maxText
7943 * The error text to display when the time is after maxValue (defaults to
7944 * 'The time in this field must be equal to or before {0}').
7946 maxText : "The time in this field must be equal to or before {0}",
7948 * @cfg {String} invalidText
7949 * The error text to display when the time in the field is invalid (defaults to
7950 * '{value} is not a valid time').
7952 invalidText : "{0} is not a valid time",
7954 * @cfg {String} format
7955 * The default time format string which can be overriden for localization support. The format must be
7956 * valid according to {@link Date#parseDate} (defaults to 'g:i A', e.g., '3:15 PM'). For 24-hour time
7957 * format try 'H:i' instead.
7961 * @cfg {String} altFormats
7962 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
7963 * 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').
7965 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",
7967 * @cfg {Number} increment
7968 * The number of minutes between each time value in the list (defaults to 15).
7975 triggerAction: 'all',
7979 // private - This is the date to use when generating time values in the absence of either minValue
7980 // or maxValue. Using the current date causes DST issues on DST boundary dates, so this is an
7981 // arbitrary "safe" date that can be any date aside from DST boundary dates.
7982 initDate: '1/1/2008',
7984 initDateFormat: 'j/n/Y',
7987 initComponent : function(){
7988 if(Ext.isDefined(this.minValue)){
7989 this.setMinValue(this.minValue, true);
7991 if(Ext.isDefined(this.maxValue)){
7992 this.setMaxValue(this.maxValue, true);
7995 this.generateStore(true);
7997 Ext.form.TimeField.superclass.initComponent.call(this);
8001 * Replaces any existing {@link #minValue} with the new time and refreshes the store.
8002 * @param {Date/String} value The minimum time that can be selected
8004 setMinValue: function(value, /* private */ initial){
8005 this.setLimit(value, true, initial);
8010 * Replaces any existing {@link #maxValue} with the new time and refreshes the store.
8011 * @param {Date/String} value The maximum time that can be selected
8013 setMaxValue: function(value, /* private */ initial){
8014 this.setLimit(value, false, initial);
8019 generateStore: function(initial){
8020 var min = this.minValue || new Date(this.initDate).clearTime(),
8021 max = this.maxValue || new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1),
8025 times.push(min.dateFormat(this.format));
8026 min = min.add('mi', this.increment);
8028 this.bindStore(times, initial);
8032 setLimit: function(value, isMin, initial){
8034 if(Ext.isString(value)){
8035 d = this.parseDate(value);
8036 }else if(Ext.isDate(value)){
8040 var val = new Date(this.initDate).clearTime();
8041 val.setHours(d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
8042 this[isMin ? 'minValue' : 'maxValue'] = val;
8044 this.generateStore();
8050 getValue : function(){
8051 var v = Ext.form.TimeField.superclass.getValue.call(this);
8052 return this.formatDate(this.parseDate(v)) || '';
8056 setValue : function(value){
8057 return Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value)));
8060 // private overrides
8061 validateValue : Ext.form.DateField.prototype.validateValue,
8063 formatDate : Ext.form.DateField.prototype.formatDate,
8065 parseDate: function(value) {
8066 if (!value || Ext.isDate(value)) {
8070 var id = this.initDate + ' ',
8071 idf = this.initDateFormat + ' ',
8072 v = Date.parseDate(id + value, idf + this.format), // *** handle DST. note: this.format is a TIME-only format
8073 af = this.altFormats;
8076 if (!this.altFormatsArray) {
8077 this.altFormatsArray = af.split("|");
8079 for (var i = 0, afa = this.altFormatsArray, len = afa.length; i < len && !v; i++) {
8080 v = Date.parseDate(id + value, idf + afa[i]);
8087 Ext.reg('timefield', Ext.form.TimeField);/**
8088 * @class Ext.form.SliderField
8089 * @extends Ext.form.Field
8090 * Wraps a {@link Ext.slider.MultiSlider Slider} so it can be used as a form field.
8092 * Creates a new SliderField
8093 * @param {Object} config Configuration options. Note that you can pass in any slider configuration options, as well as
8094 * as any field configuration options.
8095 * @xtype sliderfield
8097 Ext.form.SliderField = Ext.extend(Ext.form.Field, {
8100 * @cfg {Boolean} useTips
8101 * True to use an Ext.slider.Tip to display tips for the value. Defaults to <tt>true</tt>.
8106 * @cfg {Function} tipText
8107 * A function used to display custom text for the slider tip. Defaults to <tt>null</tt>, which will
8108 * use the default on the plugin.
8116 * Initialize the component.
8119 initComponent : function() {
8120 var cfg = Ext.copyTo({
8121 id: this.id + '-slider'
8122 }, this.initialConfig, ['vertical', 'minValue', 'maxValue', 'decimalPrecision', 'keyIncrement', 'increment', 'clickToChange', 'animate']);
8124 // only can use it if it exists.
8126 var plug = this.tipText ? {getText: this.tipText} : {};
8127 cfg.plugins = [new Ext.slider.Tip(plug)];
8129 this.slider = new Ext.Slider(cfg);
8130 Ext.form.SliderField.superclass.initComponent.call(this);
8134 * Set up the hidden field
8135 * @param {Object} ct The container to render to.
8136 * @param {Object} position The position in the container to render to.
8139 onRender : function(ct, position){
8146 Ext.form.SliderField.superclass.onRender.call(this, ct, position);
8147 this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
8148 this.resizeEl = this.positionEl = this.wrap;
8149 this.slider.render(this.wrap);
8153 * Ensure that the slider size is set automatically when the field resizes.
8154 * @param {Object} w The width
8155 * @param {Object} h The height
8156 * @param {Object} aw The adjusted width
8157 * @param {Object} ah The adjusted height
8160 onResize : function(w, h, aw, ah){
8161 Ext.form.SliderField.superclass.onResize.call(this, w, h, aw, ah);
8162 this.slider.setSize(w, h);
8166 * Initialize any events for this class.
8169 initEvents : function(){
8170 Ext.form.SliderField.superclass.initEvents.call(this);
8171 this.slider.on('change', this.onChange, this);
8175 * Utility method to set the value of the field when the slider changes.
8176 * @param {Object} slider The slider object.
8177 * @param {Object} v The new value.
8180 onChange : function(slider, v){
8181 this.setValue(v, undefined, true);
8185 * Enable the slider when the field is enabled.
8188 onEnable : function(){
8189 Ext.form.SliderField.superclass.onEnable.call(this);
8190 this.slider.enable();
8194 * Disable the slider when the field is disabled.
8197 onDisable : function(){
8198 Ext.form.SliderField.superclass.onDisable.call(this);
8199 this.slider.disable();
8203 * Ensure the slider is destroyed when the field is destroyed.
8206 beforeDestroy : function(){
8207 Ext.destroy(this.slider);
8208 Ext.form.SliderField.superclass.beforeDestroy.call(this);
8212 * If a side icon is shown, do alignment to the slider
8215 alignErrorIcon : function(){
8216 this.errorIcon.alignTo(this.slider.el, 'tl-tr', [2, 0]);
8220 * Sets the minimum field value.
8221 * @param {Number} v The new minimum value.
8222 * @return {Ext.form.SliderField} this
8224 setMinValue : function(v){
8225 this.slider.setMinValue(v);
8230 * Sets the maximum field value.
8231 * @param {Number} v The new maximum value.
8232 * @return {Ext.form.SliderField} this
8234 setMaxValue : function(v){
8235 this.slider.setMaxValue(v);
8240 * Sets the value for this field.
8241 * @param {Number} v The new value.
8242 * @param {Boolean} animate (optional) Whether to animate the transition. If not specified, it will default to the animate config.
8243 * @return {Ext.form.SliderField} this
8245 setValue : function(v, animate, /* private */ silent){
8246 // silent is used if the setValue method is invoked by the slider
8247 // which means we don't need to set the value on the slider.
8249 this.slider.setValue(v, animate);
8251 return Ext.form.SliderField.superclass.setValue.call(this, this.slider.getValue());
8255 * Gets the current value for this field.
8256 * @return {Number} The current value.
8258 getValue : function(){
8259 return this.slider.getValue();
8263 Ext.reg('sliderfield', Ext.form.SliderField);/**
8264 * @class Ext.form.Label
8265 * @extends Ext.BoxComponent
8266 * Basic Label field.
8268 * Creates a new Label
8269 * @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
8270 * 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
8271 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
8274 Ext.form.Label = Ext.extend(Ext.BoxComponent, {
8276 * @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML
8277 * tags within the label's innerHTML, use the {@link #html} config instead.
8280 * @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for'
8281 * attribute. If not specified, the attribute will not be added to the label.
8284 * @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to '').
8285 * Note that if {@link #text} is specified it will take precedence and this value will be ignored.
8289 onRender : function(ct, position){
8291 this.el = document.createElement('label');
8292 this.el.id = this.getId();
8293 this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || '');
8295 this.el.setAttribute('for', this.forId);
8298 Ext.form.Label.superclass.onRender.call(this, ct, position);
8302 * Updates the label's innerHTML with the specified string.
8303 * @param {String} text The new label text
8304 * @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it
8305 * to the label (defaults to true which encodes the value). This might be useful if you want to include
8306 * tags in the label's innerHTML rather than rendering them as string literals per the default logic.
8307 * @return {Label} this
8309 setText : function(t, encode){
8310 var e = encode === false;
8311 this[!e ? 'text' : 'html'] = t;
8312 delete this[e ? 'text' : 'html'];
8314 this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t;
8320 Ext.reg('label', Ext.form.Label);/**
8321 * @class Ext.form.Action
8322 * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>
8323 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8324 * the Form needs to perform an action such as submit or load. The Configuration options
8325 * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},
8326 * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>
8327 * <p>The instance of Action which performed the action is passed to the success
8328 * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},
8329 * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),
8330 * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and
8331 * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>
8333 Ext.form.Action = function(form, options){
8335 this.options = options || {};
8339 * Failure type returned when client side validation of the Form fails
8340 * thus aborting a submit action. Client side validation is performed unless
8341 * {@link #clientValidation} is explicitly set to <tt>false</tt>.
8345 Ext.form.Action.CLIENT_INVALID = 'client';
8347 * <p>Failure type returned when server side processing fails and the {@link #result}'s
8348 * <tt style="font-weight:bold">success</tt> property is set to <tt>false</tt>.</p>
8349 * <p>In the case of a form submission, field-specific error messages may be returned in the
8350 * {@link #result}'s <tt style="font-weight:bold">errors</tt> property.</p>
8354 Ext.form.Action.SERVER_INVALID = 'server';
8356 * Failure type returned when a communication error happens when attempting
8357 * to send a request to the remote server. The {@link #response} may be examined to
8358 * provide further information.
8362 Ext.form.Action.CONNECT_FAILURE = 'connect';
8364 * Failure type returned when the response's <tt style="font-weight:bold">success</tt>
8365 * property is set to <tt>false</tt>, or no field values are returned in the response's
8366 * <tt style="font-weight:bold">data</tt> property.
8370 Ext.form.Action.LOAD_FAILURE = 'load';
8372 Ext.form.Action.prototype = {
8374 * @cfg {String} url The URL that the Action is to invoke.
8377 * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be
8378 * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens
8379 * <b>before</b> the {@link #success} callback is called and before the Form's
8380 * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.
8383 * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the
8384 * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.
8387 * @cfg {Mixed} params <p>Extra parameter values to pass. These are added to the Form's
8388 * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's
8390 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
8393 * @cfg {Number} timeout The number of seconds to wait for a server response before
8394 * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. If not specified,
8395 * defaults to the configured <tt>{@link Ext.form.BasicForm#timeout timeout}</tt> of the
8396 * {@link Ext.form.BasicForm form}.
8399 * @cfg {Function} success The function to call when a valid success return packet is recieved.
8400 * The function is passed the following parameters:<ul class="mdetail-params">
8401 * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
8402 * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result}
8403 * property of this object may be examined to perform custom postprocessing.</div></li>
8407 * @cfg {Function} failure The function to call when a failure packet was recieved, or when an
8408 * error ocurred in the Ajax communication.
8409 * The function is passed the following parameters:<ul class="mdetail-params">
8410 * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
8411 * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax
8412 * error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
8413 * property of this object may be examined to perform custom postprocessing.</div></li>
8417 * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference
8418 * for the callback functions).
8421 * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait}
8422 * during the time the action is being processed.
8425 * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait}
8426 * during the time the action is being processed.
8430 * @cfg {Boolean} submitEmptyText If set to <tt>true</tt>, the emptyText value will be sent with the form
8431 * when it is submitted. Defaults to <tt>true</tt>.
8435 * The type of action this Action instance performs.
8436 * Currently only "submit" and "load" are supported.
8441 * The type of failure detected will be one of these: {@link #CLIENT_INVALID},
8442 * {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}. Usage:
8444 var fp = new Ext.form.FormPanel({
8449 handler: function(){
8450 if(fp.getForm().isValid()){
8451 fp.getForm().submit({
8452 url: 'form-submit.php',
8453 waitMsg: 'Submitting your data...',
8454 success: function(form, action){
8455 // server responded with success = true
8456 var result = action.{@link #result};
8458 failure: function(form, action){
8459 if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
8460 Ext.Msg.alert('Error',
8461 'Status:'+action.{@link #response}.status+': '+
8462 action.{@link #response}.statusText);
8464 if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
8465 // server responded with success = false
8466 Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
8474 handler: function(){
8475 fp.getForm().reset();
8479 * @property failureType
8483 * The XMLHttpRequest object used to perform the action.
8484 * @property response
8488 * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
8489 * other, action-specific properties.
8495 run : function(options){
8500 success : function(response){
8505 handleResponse : function(response){
8509 // default connection failure
8510 failure : function(response){
8511 this.response = response;
8512 this.failureType = Ext.form.Action.CONNECT_FAILURE;
8513 this.form.afterAction(this, false);
8517 // shared code among all Actions to validate that there was a response
8518 // with either responseText or responseXml
8519 processResponse : function(response){
8520 this.response = response;
8521 if(!response.responseText && !response.responseXML){
8524 this.result = this.handleResponse(response);
8528 // utility functions used internally
8529 getUrl : function(appendParams){
8530 var url = this.options.url || this.form.url || this.form.el.dom.action;
8532 var p = this.getParams();
8534 url = Ext.urlAppend(url, p);
8541 getMethod : function(){
8542 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
8546 getParams : function(){
8547 var bp = this.form.baseParams;
8548 var p = this.options.params;
8550 if(typeof p == "object"){
8551 p = Ext.urlEncode(Ext.applyIf(p, bp));
8552 }else if(typeof p == 'string' && bp){
8553 p += '&' + Ext.urlEncode(bp);
8556 p = Ext.urlEncode(bp);
8562 createCallback : function(opts){
8563 var opts = opts || {};
8565 success: this.success,
8566 failure: this.failure,
8568 timeout: (opts.timeout*1000) || (this.form.timeout*1000),
8569 upload: this.form.fileUpload ? this.success : undefined
8575 * @class Ext.form.Action.Submit
8576 * @extends Ext.form.Action
8577 * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s
8578 * and processes the returned response.</p>
8579 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8580 * {@link Ext.form.BasicForm#submit submit}ting.</p>
8581 * <p><u><b>Response Packet Criteria</b></u></p>
8582 * <p>A response packet may contain:
8583 * <div class="mdetail-params"><ul>
8584 * <li><b><code>success</code></b> property : Boolean
8585 * <div class="sub-desc">The <code>success</code> property is required.</div></li>
8586 * <li><b><code>errors</code></b> property : Object
8587 * <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
8588 * which is optional, contains error messages for invalid fields.</div></li>
8590 * <p><u><b>JSON Packets</b></u></p>
8591 * <p>By default, response packets are assumed to be JSON, so a typical response
8592 * packet may look like this:</p><pre><code>
8596 clientCode: "Client not found",
8597 portOfLoading: "This field must not be null"
8600 * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback
8601 * or event handler methods. The object decoded from this JSON is available in the
8602 * {@link Ext.form.Action#result result} property.</p>
8603 * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
8604 errorReader: new Ext.data.XmlReader({
8612 * <p>then the results may be sent back in XML format:</p><pre><code>
8613 <?xml version="1.0" encoding="UTF-8"?>
8614 <message success="false">
8617 <id>clientCode</id>
8618 <msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
8621 <id>portOfLoading</id>
8622 <msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
8627 * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
8628 * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
8630 Ext.form.Action.Submit = function(form, options){
8631 Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
8634 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
8636 * @cfg {Ext.data.DataReader} errorReader <p><b>Optional. JSON is interpreted with
8637 * no need for an errorReader.</b></p>
8638 * <p>A Reader which reads a single record from the returned data. The DataReader's
8639 * <b>success</b> property specifies how submission success is determined. The Record's
8640 * data provides the error messages to apply to any invalid form Fields.</p>
8643 * @cfg {boolean} clientValidation Determines whether a Form's fields are validated
8644 * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
8645 * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation
8652 var o = this.options,
8653 method = this.getMethod(),
8654 isGet = method == 'GET';
8655 if(o.clientValidation === false || this.form.isValid()){
8656 if (o.submitEmptyText === false) {
8657 var fields = this.form.items,
8659 setupEmptyFields = function(f){
8660 if (f.el.getValue() == f.emptyText) {
8661 emptyFields.push(f);
8662 f.el.dom.value = "";
8664 if(f.isComposite && f.rendered){
8665 f.items.each(setupEmptyFields);
8669 fields.each(setupEmptyFields);
8671 Ext.Ajax.request(Ext.apply(this.createCallback(o), {
8672 form:this.form.el.dom,
8673 url:this.getUrl(isGet),
8676 params:!isGet ? this.getParams() : null,
8677 isUpload: this.form.fileUpload
8679 if (o.submitEmptyText === false) {
8680 Ext.each(emptyFields, function(f) {
8681 if (f.applyEmptyText) {
8686 }else if (o.clientValidation !== false){ // client validation failed
8687 this.failureType = Ext.form.Action.CLIENT_INVALID;
8688 this.form.afterAction(this, false);
8693 success : function(response){
8694 var result = this.processResponse(response);
8695 if(result === true || result.success){
8696 this.form.afterAction(this, true);
8700 this.form.markInvalid(result.errors);
8702 this.failureType = Ext.form.Action.SERVER_INVALID;
8703 this.form.afterAction(this, false);
8707 handleResponse : function(response){
8708 if(this.form.errorReader){
8709 var rs = this.form.errorReader.read(response);
8712 for(var i = 0, len = rs.records.length; i < len; i++) {
8713 var r = rs.records[i];
8717 if(errors.length < 1){
8721 success : rs.success,
8725 return Ext.decode(response.responseText);
8731 * @class Ext.form.Action.Load
8732 * @extends Ext.form.Action
8733 * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
8734 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8735 * {@link Ext.form.BasicForm#load load}ing.</p>
8736 * <p><u><b>Response Packet Criteria</b></u></p>
8737 * <p>A response packet <b>must</b> contain:
8738 * <div class="mdetail-params"><ul>
8739 * <li><b><code>success</code></b> property : Boolean</li>
8740 * <li><b><code>data</code></b> property : Object</li>
8741 * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
8742 * The individual value object for each Field is passed to the Field's
8743 * {@link Ext.form.Field#setValue setValue} method.</div></li>
8745 * <p><u><b>JSON Packets</b></u></p>
8746 * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
8747 var myFormPanel = new Ext.form.FormPanel({
8748 title: 'Client and routing info',
8750 fieldLabel: 'Client',
8753 fieldLabel: 'Port of loading',
8754 name: 'portOfLoading'
8756 fieldLabel: 'Port of discharge',
8757 name: 'portOfDischarge'
8760 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
8761 url: '/getRoutingInfo.php',
8763 consignmentRef: myConsignmentRef
8765 failure: function(form, action) {
8766 Ext.Msg.alert("Load failed", action.result.errorMessage);
8770 * a <b>success response</b> packet may look like this:</p><pre><code>
8774 clientName: "Fred. Olsen Lines",
8775 portOfLoading: "FXT",
8776 portOfDischarge: "OSL"
8779 * while a <b>failure response</b> packet may look like this:</p><pre><code>
8782 errorMessage: "Consignment reference not found"
8784 * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
8785 * callback or event handler methods. The object decoded from this JSON is available in the
8786 * {@link Ext.form.Action#result result} property.</p>
8788 Ext.form.Action.Load = function(form, options){
8789 Ext.form.Action.Load.superclass.constructor.call(this, form, options);
8790 this.reader = this.form.reader;
8793 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
8799 Ext.Ajax.request(Ext.apply(
8800 this.createCallback(this.options), {
8801 method:this.getMethod(),
8802 url:this.getUrl(false),
8803 headers: this.options.headers,
8804 params:this.getParams()
8809 success : function(response){
8810 var result = this.processResponse(response);
8811 if(result === true || !result.success || !result.data){
8812 this.failureType = Ext.form.Action.LOAD_FAILURE;
8813 this.form.afterAction(this, false);
8816 this.form.clearInvalid();
8817 this.form.setValues(result.data);
8818 this.form.afterAction(this, true);
8822 handleResponse : function(response){
8823 if(this.form.reader){
8824 var rs = this.form.reader.read(response);
8825 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
8827 success : rs.success,
8831 return Ext.decode(response.responseText);
8838 * @class Ext.form.Action.DirectLoad
8839 * @extends Ext.form.Action.Load
8840 * <p>Provides Ext.direct support for loading form data.</p>
8841 * <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
8843 var myFormPanel = new Ext.form.FormPanel({
8844 // configs for FormPanel
8845 title: 'Basic Information',
8846 renderTo: document.body,
8847 width: 300, height: 160,
8850 // configs apply to child items
8851 defaults: {anchor: '100%'},
8852 defaultType: 'textfield',
8857 fieldLabel: 'Email',
8860 fieldLabel: 'Company',
8864 // configs for BasicForm
8866 // The server-side method to call for load() requests
8867 load: Profile.getBasicInfo,
8868 // The server-side must mark the submit handler as a 'formHandler'
8869 submit: Profile.updateBasicInfo
8871 // specify the order for the passed params
8872 paramOrder: ['uid', 'foo']
8876 myFormPanel.getForm().load({
8877 // pass 2 arguments to server side getBasicInfo method (len=2)
8884 * The data packet sent to the server will resemble something like:
8888 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
8889 "data":[34,"bar"] // note the order of the params
8893 * The form will process a data packet returned by the server that is similar
8894 * to the following format:
8898 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
8902 "name":"Fred Flintstone",
8903 "company":"Slate Rock and Gravel",
8904 "email":"fred.flintstone@slaterg.com"
8911 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
8912 constructor: function(form, opts) {
8913 Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
8915 type : 'directload',
8918 var args = this.getParams();
8919 args.push(this.success, this);
8920 this.form.api.load.apply(window, args);
8923 getParams : function() {
8924 var buf = [], o = {};
8925 var bp = this.form.baseParams;
8926 var p = this.options.params;
8927 Ext.apply(o, p, bp);
8928 var paramOrder = this.form.paramOrder;
8930 for(var i = 0, len = paramOrder.length; i < len; i++){
8931 buf.push(o[paramOrder[i]]);
8933 }else if(this.form.paramsAsHash){
8938 // Direct actions have already been processed and therefore
8939 // we can directly set the result; Direct Actions do not have
8940 // a this.response property.
8941 processResponse : function(result) {
8942 this.result = result;
8946 success : function(response, trans){
8947 if(trans.type == Ext.Direct.exceptions.SERVER){
8950 Ext.form.Action.DirectLoad.superclass.success.call(this, response);
8955 * @class Ext.form.Action.DirectSubmit
8956 * @extends Ext.form.Action.Submit
8957 * <p>Provides Ext.direct support for submitting form data.</p>
8958 * <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
8960 var myFormPanel = new Ext.form.FormPanel({
8961 // configs for FormPanel
8962 title: 'Basic Information',
8963 renderTo: document.body,
8964 width: 300, height: 160,
8968 handler: function(){
8969 myFormPanel.getForm().submit({
8978 // configs apply to child items
8979 defaults: {anchor: '100%'},
8980 defaultType: 'textfield',
8985 fieldLabel: 'Email',
8988 fieldLabel: 'Company',
8992 // configs for BasicForm
8994 // The server-side method to call for load() requests
8995 load: Profile.getBasicInfo,
8996 // The server-side must mark the submit handler as a 'formHandler'
8997 submit: Profile.updateBasicInfo
8999 // specify the order for the passed params
9000 paramOrder: ['uid', 'foo']
9003 * The data packet sent to the server will resemble something like:
9006 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
9010 "extAction":"Profile","extMethod":"updateBasicInfo",
9011 "extType":"rpc","extTID":"6","extUpload":"false",
9012 "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
9017 * The form will process a data packet returned by the server that is similar
9020 // sample success packet (batched requests)
9023 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
9030 // sample failure packet (one request)
9032 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
9035 "email":"already taken"
9042 * Also see the discussion in {@link Ext.form.Action.DirectLoad}.
9044 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
9045 constructor : function(form, opts) {
9046 Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
9048 type : 'directsubmit',
9049 // override of Submit
9051 var o = this.options;
9052 if(o.clientValidation === false || this.form.isValid()){
9053 // tag on any additional params to be posted in the
9055 this.success.params = this.getParams();
9056 this.form.api.submit(this.form.el.dom, this.success, this);
9057 }else if (o.clientValidation !== false){ // client validation failed
9058 this.failureType = Ext.form.Action.CLIENT_INVALID;
9059 this.form.afterAction(this, false);
9063 getParams : function() {
9065 var bp = this.form.baseParams;
9066 var p = this.options.params;
9067 Ext.apply(o, p, bp);
9070 // Direct actions have already been processed and therefore
9071 // we can directly set the result; Direct Actions do not have
9072 // a this.response property.
9073 processResponse : function(result) {
9074 this.result = result;
9078 success : function(response, trans){
9079 if(trans.type == Ext.Direct.exceptions.SERVER){
9082 Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
9086 Ext.form.Action.ACTION_TYPES = {
9087 'load' : Ext.form.Action.Load,
9088 'submit' : Ext.form.Action.Submit,
9089 'directload' : Ext.form.Action.DirectLoad,
9090 'directsubmit' : Ext.form.Action.DirectSubmit
9093 * @class Ext.form.VTypes
9094 * <p>This is a singleton object which contains a set of commonly used field validation functions.
9095 * The validations provided are basic and intended to be easily customizable and extended.</p>
9096 * <p>To add custom VTypes specify the <code>{@link Ext.form.TextField#vtype vtype}</code> validation
9097 * test function, and optionally specify any corresponding error text to display and any keystroke
9098 * filtering mask to apply. For example:</p>
9100 // custom Vtype for vtype:'time'
9101 var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
9102 Ext.apply(Ext.form.VTypes, {
9103 // vtype validation function
9104 time: function(val, field) {
9105 return timeTest.test(val);
9107 // vtype Text property: The error text to display when the validation function returns false
9108 timeText: 'Not a valid time. Must be in the format "12:34 PM".',
9109 // vtype Mask property: The keystroke filter mask
9110 timeMask: /[\d\s:amp]/i
9115 // custom Vtype for vtype:'IPAddress'
9116 Ext.apply(Ext.form.VTypes, {
9117 IPAddress: function(v) {
9118 return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
9120 IPAddressText: 'Must be a numeric IP address',
9121 IPAddressMask: /[\d\.]/i
9126 Ext.form.VTypes = function(){
9127 // closure these in so they are only created once.
9128 var alpha = /^[a-zA-Z_]+$/,
9129 alphanum = /^[a-zA-Z0-9_]+$/,
9130 email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,
9131 url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
9133 // All these messages and functions are configurable
9136 * The function used to validate email addresses. Note that this is a very basic validation -- complete
9137 * validation per the email RFC specifications is very complex and beyond the scope of this class, although
9138 * this function can be overridden if a more comprehensive validation scheme is desired. See the validation
9139 * section of the <a href="http://en.wikipedia.org/wiki/E-mail_address">Wikipedia article on email addresses</a>
9140 * for additional information. This implementation is intended to validate the following emails:<tt>
9141 * 'barney@example.de', 'barney.rubble@example.com', 'barney-rubble@example.coop', 'barney+rubble@example.com'
9143 * @param {String} value The email address
9144 * @return {Boolean} true if the RegExp test passed, and false if not.
9146 'email' : function(v){
9147 return email.test(v);
9150 * The error text to display when the email validation function returns false. Defaults to:
9151 * <tt>'This field should be an e-mail address in the format "user@example.com"'</tt>
9154 'emailText' : 'This field should be an e-mail address in the format "user@example.com"',
9156 * The keystroke filter mask to be applied on email input. See the {@link #email} method for
9157 * information about more complex email validation. Defaults to:
9158 * <tt>/[a-z0-9_\.\-@]/i</tt>
9161 'emailMask' : /[a-z0-9_\.\-@\+]/i,
9164 * The function used to validate URLs
9165 * @param {String} value The URL
9166 * @return {Boolean} true if the RegExp test passed, and false if not.
9168 'url' : function(v){
9172 * The error text to display when the url validation function returns false. Defaults to:
9173 * <tt>'This field should be a URL in the format "http:/'+'/www.example.com"'</tt>
9176 'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"',
9179 * The function used to validate alpha values
9180 * @param {String} value The value
9181 * @return {Boolean} true if the RegExp test passed, and false if not.
9183 'alpha' : function(v){
9184 return alpha.test(v);
9187 * The error text to display when the alpha validation function returns false. Defaults to:
9188 * <tt>'This field should only contain letters and _'</tt>
9191 'alphaText' : 'This field should only contain letters and _',
9193 * The keystroke filter mask to be applied on alpha input. Defaults to:
9194 * <tt>/[a-z_]/i</tt>
9197 'alphaMask' : /[a-z_]/i,
9200 * The function used to validate alphanumeric values
9201 * @param {String} value The value
9202 * @return {Boolean} true if the RegExp test passed, and false if not.
9204 'alphanum' : function(v){
9205 return alphanum.test(v);
9208 * The error text to display when the alphanumeric validation function returns false. Defaults to:
9209 * <tt>'This field should only contain letters, numbers and _'</tt>
9212 'alphanumText' : 'This field should only contain letters, numbers and _',
9214 * The keystroke filter mask to be applied on alphanumeric input. Defaults to:
9215 * <tt>/[a-z0-9_]/i</tt>
9218 'alphanumMask' : /[a-z0-9_]/i