Graphene:Forms Documentation

NOTE: This is a apha version, possibly still containing bugs and some parts of the api may still change slightly.

What is it?

Graphene:Forms is an extensible JavaScript library for managing forms, includeing rendering, loading, parsing, validation, conditional fields and much more.


Getting Started

Dependencies - Graphene:Forms has only one dependency: lodash.js

A minimum setup would look something like this

<!DOCTYPE html>
<html>
  <head>
    <script src='assets/js/lodash.min.js'></script>
    <script src='assets/js/gform.min.js'></script>
  </head>
  <body>
  <div class="myForm">
  </div>
  </body>
</html>

Now that we all set up we can begin enjoying the magic of Graphene:Forms!

var config = {
  "el":     ".myForm"
  "fields": [
    {"name": "Example"}
  ]
};
var myForm = new gform(config);

Configuration


var config = {
  'el':     '.myForm',		
  'legend': 'My Form',
  'name':   'myForm',
  'data':   { 'first_name': 'Bob' },
  'fields': [
    { 'name': 'first_name' }
  ]
};
var myForm = new gform(config);

legend

The legend of the form as it is to be rendered, if left blank no legend will be rendered.


name

The name of your form. This can be used to reference the form after it is created. If no name is given one will be generated automatically. A reference to all forms created is maintained in the object gform.instances. Accesssing a form with the name "myForm" would look like this gform.instances['myForm']


data

If data is an object then gform populates your form with the values contained in the data.
If data is set to hash the form is populated with data from the url hash.
Lastly the data can be set to a url and the data will be fetched and populated from the response.


fields

An array of fields that define each field to be included in the form. If no fields are defined then no form is drawn.


default

This is an object that defines what a default field that is created looks for any undefined property. For example by default if the type is not defined a text field is created, if you would preer that a textarea is default you could define default to be {"type":"textarea"}

config.default = {"type": "textarea"} // this would set the default type to textearea


Public Methods


get myForm.get([name]);

an object will be returned containing a serializable object with all of the values. If the optional 'name' parameter is supplied then only the value of the field with that name is returned.
an alias for toJSON exists so

JSON.stringify(myForm)
is valid as well



find myForm.find(path || name);

the gform field that the path leads to is returned, for first level fields the path is just the name if it is contained within a fieldset the path would be 'fieldset_name.field_name'



validate myForm.validate();

all of the fields are validated and the status of the validation is returned. If a field fails validation the error message is added to that field if the theme supports it. The flag myForm.valid is also set to this status and an array of errors is containted in the myForm.errors property;



destroy myForm.destroy();

this will remove the form and clean up any residuals and remove all events



Field Options


var config = {
  'el': '.myForm',
  'fields': [
    {
      'label':    'First Name',
      'value':    'John'
    },  
    {
      'label':          'Last Name',
      'placeholder':    'doe'
    },  
    {
      'type':     'select',
      'label':    'State',
      'required': true,
      'options':  './data/states.json', 
      'format':   {'label': '{{name}}'},
      'help': 'Choose your state'
    }
  ]
};

type ['string'] Example

default = 'text'

This defines the type of form element to render. The default type is a simple text input.
supported types out of the box are:


This list can be expanded through plugins


name ['string']Example

default = ''; all types

If this property is not set then the name will be set to the internally genderated uuid for this field. The 'name' property is set on the field in the html and is used to reference this field in the collection maintained by Graphene:Forms.


label ['string', 'bool']Example

default = ''; all types

If a string is set this will be used as the label on the current field. To hide the label then this can be set to 'false'. The default label that will apply if no label is set will be the index of the field i.e. the first field will have a label of '0'.


value ['text', 'integer', 'bool', 'function']Example

default = ''; all types

This is the default value of the field and has lower precedence than the data field on the form.


help ['string']Example

default = ''; all types

This is the help text that will be shown to a user to guide them in filling out the field. By default no help text will be included.


placeholder ['string']Example

default = ""; (text, number, email, textarea, select)

The placeholder property sets the placeholder for some field types, for example the 'text' type.


target ['selector', 'node']

default = ''; all types

The target by default is the form or fieldset that contains the field however you can declare a selector string for the field and it will be appended to the element found by the selector if it exists.

{
  'type':     'text',
  'name':     'first_name',
  'label':    'First Name',
  'target':   '.sidebar'
}

columns ['integer'] => 12Example

default = ''; all types

Fields default to the full width but based on the grid that the theme uses fields can be set to be smaller (1-12).


array ['object']Example

default = false; all types

Array is used to allow for multiple instances of a field or fieldset to be created. If no options are set then you will have buttons for inserting and removeing instances. options on this are max and min. By default max is set to 5 and min is set to 1, this means that you will be able to insert new instances up to 5 and remove instances down to 1. If max is set higher then more instances will automatically be created on form instantiation and the number will not be allowed to drop below that number.


show ['bool', 'function' 'gform.conditions']Example

default = true; all types

By defualt this is set to 'true', if the value is simply set to false the field will not be shown. If show is set to a function then the function must return a boolean. The last option is to pass an object with the structure of gform.conditions that is used to dynamically determine if the field should be shown based on the values of other fields.

The 'display' property must in one way or another result in a bool indicating if the field should be shown or not.


edit ['bool', 'function' 'gform.conditions']Example

default = true; all types

See as display for acceptable values here.

The 'edit' property must in one way or another result in a bool indicating if the field should be enabled for editing/changing.


parse ['bool', 'function' 'gform.conditions']Example

default = true; all types

See as display for acceptable values here.

The 'parse' property must in one way or another result in a bool indicating if the field should be included in a 'get' call on the form.


required ['bool', 'function' 'gform.conditions']

default = false; all types

See as display for acceptable values here.

The 'required' property must in one way or another result in a bool indicating if the field should be a required field.


validate ['bool', 'function' 'gform.conditions']

default = {}; all types

config.fields[0].validate = true

max ['integer']Example

default = empty; select, radio, number

This field has a different meaning based on the field type and has no effect on many field types. For a field type of 'number' this will set a maximum number that the fields value can be. If the max is set on any field that would normally have its options passed in then the max is used to generate a set of options for that field.


min ['integer']Example

default = 0; select, radio, number

Similar to the max field this field has a different meaning based on the field type and has no effect on many field types. For a field type of 'number' this will set a minimum number that the fields value can be. If the max is set on any field that would normally have its options passed in then the min is used with the max to generate a set of options for that field. If max is set but min is not then min is assumed to be 0 when generating config.


step ['integer']Example

default = 1; select, radio, number

Similar to the max field this field has a different meaning based on the field type and has no effect on many field types. For a field type of 'number' this will set a step number that the fields value will increase/decreases by when using the arrows. If the max is set on any field that would normally have its options passed in then the min is used with the max to generate a set of options for that field. If max is set but step is not then step is assumed to be 1 when generating config.


options ['array', 'string', 'function']Example

(select, radio) default = [];

(checkbox) default = [false, true];

For the 'checkbox' type this should either be unset or a an array of length 2 should be defined, where the first element is the value for an unchecked box and the second is the value for a checked box.

For


format ['object']Example

select, radio
{ label: '{{label}}', value: '{{value}}' }

This option allows you to define custom labels and values to use for building options, this allows you to use existing data to generate usable form elements.
note: 'index' is a calculated value that is available to generate labels and values.


Conditions

var config = {
  'el': '.myForm',
  'fields': [
  {
    "label":"Candy"
  },
  {
    "label": "Reason",
    "name": "reason",
    "display": [
      { 
        // looks for a matching value
        "type": "matches",
        // field to be compared to
        "name": "candy",
       // value or array of acceptable values
        "value": "chocolate"
      }
    ]
  }] // this field will be hidden unless the field named "candy" has a value of "chocolate"
}

requires

The 'requires' condition requires that the field indicated with the 'name' property passes the required validation.


matches

The 'matches' condition requires that the value of the field indicated with the 'name' property matches the value that is set in the 'value' property.


not_matches

The 'matches' condition requires that the value of the field indicated with the 'name' property does not match the value that is set in the 'value' property.


contains

The 'contains' condition requires that the value of the field indicated with the 'name' property contains the value that is set in the 'value property'.


test

This 'test' condition requires a callback method to be set as well which should return a boolean indicating if it passes the test. The callback will recieve a reference to the field as well as the condition definition.


nesting

Complex conditions can be created by nesting.


Validation

var config = {
  "el": ".validateForm",
  "fields": [{
    "label": "Answer",
    "name": "answer",
    "validate": [
      { 
        "type": "length",
        "min": 3,
        "max": 10,
      },
      {
        "type": "custom",
        "test": function(value){
          if(~["reserved", "word"].indexOf(value)){
            return "Must not be a reserved word";
          }
        }
      }
    ]
  }],
  "events": {"input": function(e){
    e.form.validate();
  }}
};

matches

fails validation if the field value does not match the value of the field indicated.

{type:'matches': name:'password_1'}
valid_email

fails validation if the field value is not a valid email address.

{type:'valid_email'}
valid_url

fails validation if the value of the field is not a valid url.

{type: 'valid_url'}
length

fails validation if the length of the field is not between the 'min' and 'max' parameters

					
{'type': 'length', 'min': 3, 'max': 10} // requires a length between 3 and 10 (inclusive) characters
{'type': 'length', 'min': 10} // requires a minimum of 10 characters
{'type': 'length', 'max': 10} // requires a maximum of 10 characters
{'type': 'length', 'min': 4, 'max': 4} // requires exactly 4 characters

numeric

fails validation if the value of the field is not numeric or is not between the min and max (inclusive) parameters.

					
{'type': 'numeric'} // requires a number be entered
{'type': 'numeric', 'min': 2, 'max': 5} // requires a number between 2 and 5 be entered
{'type': 'numeric', 'min': 2} // requires a number greater than 2 be entered
{'type': 'numeric', 'max': 5} // requires a number less than 5 be entered
{'type': 'numeric', 'min': 3, 'max': 3} // requires 3 be entered
					

custom

A custom fuction can be passed for validation and should return a false if there is no error or the error if there is one.

{'type': 'custom', 'test': function}
pattern

A custom regex pattern can be passed for validation a failing test will respond with the message

{'type': 'pattern', 'pattern': regex, 'message': '{{name}} failed to meet expectations'}

Events


.sub('event', function(event){})Example

Bind a callback function to an object. The callback will be invoked whenever the event is fired. The event string may also be a space-delimited list of several events. The event object will contain the following information

    event.event  // the name of the event that triggered the callback
    event.form   // a reference to the form instance
    event.field  // situational - if a field triggered the event then a reference will be included

Specific events may have other data provided as well but they will be highly situational to that event
i.e. The 'invalid' event will pass the errors


.pub('event',[args])

Trigger callbacks for the given event, or space-delimited list of events. An object with additional arguments to pub will be passed along to the event callbacks.

myForm.pub('save');


Built-in Events

The list of built-in events. You're also free to trigger your own events as you see fit. The context is always set to that of the form instance triggering the event.

  • initialize

    This event is fired as Graphene:Forms begins the initialization and is a good place to put set up code.

  • input   (input:fieldname)

    The input event is triggered whenever a field is changed manually by user input.

  • change   (change:fieldname)

    The change event is triggered whenever a field is changed or any change is made to the form.

  • inserted   (inserted:fieldname)

    The inserted event is triggered when a field that is duplicatable has had an new instance inserted

  • removed   (removed:fieldname)

    The removed event is triggered when a field that is duplicatable has had an instance removed

  • validation

    The validation event is triggered whenevere form validation is performed.

  • invalid   (invalid:fieldname)

    The invalid event is triggered whenevere form validation is performed and validation fails.

  • valid   (valid:fieldname)

    The validation event is triggered whenevere form validation is performed and no errors exist.

  • destroy

    This event is fired when the destroy method is called but before anything has been destroyed.

  • destroyed

    Fires after everything related to the form has been destroyed.



© Escher Labs 2019