ghinch / yui3-gallery forked from yui/yui3-gallery
Form Examples
Forms can be created in several ways. The first is to define the form object and all of the fields directly in the configuration, as an array of object literal definitions:
YUI().use('gallery-form', function(Y) {
var f = new Y.Form({
action : 'test.php',
fields : [
{name : "testText2", required : true, label : "Test Label 2"},
{name : 'testHiddenField', type : "hidden"},
{name : 'testSelectField', type : 'select', choices : [{label : 'Foo', value : 'foo'}, {label : 'Bar', value : 'bar'}], label : 'testSelect'},
{name : 'submit', type : 'submit', label : 'Submit'},
{name : 'reset', type : 'reset', label : 'Reset'}
]
});
f.render("#testForm");
});
You can also create a field object ahead of time, and the include that in your form instance configuration:
var myField = new Y.CheckboxField({
name : "myCheckbox",
value : "check",
label : "Test Checkbox"
});
var f = new Y.Form({
action : "test.php",
fields : [
myField,
{name : "testText", label : "Text Field"}
]
});
This method is useful when creating custom form field definitions that extend the base FormField module.
Validation functions may be passed to field constructors to run on that field at the time of form submission:
function validateTextInput (val) {
val = val.toLowerCase();
if (val != 'red' && val != 'blue' && val != 'yellow') {
this.showError("Value must be a primary color");
return false;
}
return true;
}
...
{name : "textField", type : "text", label : "Primary Color", validator : validateTextInput}
The final method is to build a form object from markup.
<form action="test.php" method="post">
<label for="ti1">Text Input 1</label>
<input name="textInput1" id="ti1">
<label for="ti2">Text Input 2</label>
<input name="textInput2" id="ti2">
<label for="sel1">Select Input</label>
<select id="sel1" name="selectInput1">
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
<input name="submit" type="submit" value="Submit">
<input name="reset" type="reset" value="Reset">
</form>
</div>
...
var f = new Y.Form({
contentBox: '#testForm'
});
Due to the current way that the widget module works, it’s not possible to build a form via markup AND define it in the configuration. If you want to add validation or set a field to be required in this method, you must get that field after rendering the form and set those attributes manually:
var ti1 = f.getField('textField1'); // Get a field via it's name or numerical index
ti1.set('required', true);
Finally, form submission is done via the IO object, using XHR. If the validation passes, the form’s contents will be sent to whatever location is defined in the action parameter. To handle the return, subscribe to the form’s success and failure events:
var f = new Y.Form({...});
f.subscribe('success', function(args) {
var result = Y.JSON.parse(args.response.responseText);
...
});
f.subscribe('failure', function(args) {
alert('Form submission had an error');
});
