ValidForm Builder API Documentation

ValidForm extends ClassDynamic
in package

ValidForm Builder main class - all the magic starts here.

Check out some of the following examples to get started

Example; Create a ValidForm Builder instance

$objForm = new ValidForm("cool_new_form", "Please fill out my cool form", "/awesome-submits");

Example 2; Add a field

Check out the constants section starting with ValidForm::VFORM_BOOLEAN for more field types

$objForm->addField(
    "first-name",
    "First name",
    ValidForm::VFORM_STRING,
    array(
        // Make this field required
        "required" => true
    ),
    array(
        // Show this error to indicate this is an required field if no value is submitted
        "required" => "This field is required"
    )
);

Example 3; Using ValidForm::setDefaults() to set default values on form fields

//*** Add a checklist
$objCheck = $objForm->addField("cool", "Cool checklist", ValidForm::VFORM_CHECK_LIST);
$objCheck->addField("Option 1", "option1");
$objCheck->addField("Option 2", "option2");
$objCheck->addField("Option 3", "option3");

// Add a standard string field
$objCheck = $objForm->addField("cool-text", "Coolest PHP Library", ValidForm::VFORM_STRING);

$objForm->setDefaults([
    // Set value of field 'cool text' to 'ValidForm Builder'
    "cool-text" => "ValidForm Builder",
    // Check options 2 and 3
    "cool" => ["option2", "option3"]
]);
Tags
author

Felix Langfeldt [email protected]

author

Robin van Baalen [email protected]

version
5.3.0

Table of Contents

Constants

VFORM_BOOLEAN  = 10
Input type[radio]
VFORM_CHECK_LIST  = 13
Group element. Each added element is an input[type=checkbox]
VFORM_COMPARISON_CONTAINS  = "contains"
Check if the value contains this string (case insensitive)
VFORM_COMPARISON_DOES_NOT_CONTAIN  = "doesnotcontain"
Check if the value does not contain this string (case insensitive)
VFORM_COMPARISON_EMPTY  = "empty"
Check if this value is empty
VFORM_COMPARISON_ENDS_WITH  = "endswith"
Check if the value **ends** with this string
VFORM_COMPARISON_EQUAL  = "equal"
Check if this value is equal (case insensitive)
VFORM_COMPARISON_GREATER_THAN  = "greaterthan"
Check if this value is greater than
VFORM_COMPARISON_GREATER_THAN_OR_EQUAL  = "greaterthanorequal"
Check if this value is greater than or equal
VFORM_COMPARISON_IN_ARRAY  = "in_array"
Check if the value matches your own custom regular expression
VFORM_COMPARISON_LESS_THAN  = "lessthan"
Check if this value is less than
VFORM_COMPARISON_LESS_THAN_OR_EQUAL  = "lessthanorequal"
Check if this value is less than or equal
VFORM_COMPARISON_NOT_EMPTY  = "notempty"
Check if this value is **not** empty
VFORM_COMPARISON_NOT_EQUAL  = "notequal"
Check if this value is **not** equal (case insensitive)
VFORM_COMPARISON_NOT_IN_ARRAY  = "not_in_array"
Check if the value matches your own custom regular expression
VFORM_COMPARISON_REGEX  = "regex"
Check if the value matches your own custom regular expression
VFORM_COMPARISON_STARTS_WITH  = "startswith"
Check if the value **starts** with this string
VFORM_CURRENCY  = 16
Input element
VFORM_CUSTOM  = 18
Input type[text] with custom regular expression validation
VFORM_CUSTOM_TEXT  = 19
Textarea with custom regular expression validation
VFORM_DATE  = 17
Input type[text] with European date validation (dd/mm/yyyy)
VFORM_EMAIL  = 6
Input type[text] with email validation
VFORM_FILE  = 9
Input type[file]
VFORM_HIDDEN  = 22
Input type[hidden]
VFORM_HTML  = 20
Textarea with basic input validation + HTML tags allowed
VFORM_INTEGER  = 4
Input type[text] with integer validation
VFORM_MATCH_ALL  = "all"
ValidForm Condition match
VFORM_MATCH_ANY  = "any"
ValidForm Condition match
VFORM_NUMERIC  = 3
Input type[text] with numeric validation
VFORM_PARAGRAPH  = 15
Not an element. This creates a paragraph in between form fields.
VFORM_PASSWORD  = 7
Input type[password]
VFORM_RADIO_LIST  = 12
Group element. Each added element is an input[type=radio]
VFORM_SELECT_LIST  = 14
Group element. Each added element is an option element
VFORM_SIMPLEURL  = 8
Input type[text] with basic URL validation
VFORM_STRING  = 1
Input type[text] with standard string validation
VFORM_TEXT  = 2
Textarea element type
VFORM_URL  = 21
Input type[text] with url validation
VFORM_WORD  = 5
Input type[text] with single word validation

Methods

__call()  : mixed
Magic caller method
__construct()  : mixed
Create a new ValidForm Builder instance
__get()  : mixed
Magic getter method
__set()  : mixed
Magic setter method
addArea()  : Area
Add an area to the internal elements collection.
addButton()  : Button
Adds a <button> element to the internal fields collection.
addField()  : Element
Add a new element to the internal elements collection
addFieldset()  : Fieldset
Add a fieldset to the form field collection
addHiddenField()  : Hidden
Add a hidden input field to the form collection.
addHtml()  : StaticText
Injects a string in the form.
addJSEvent()  : mixed
Add a custom javascript event with corresponding callback function
addMultiField()  : MultiField
Create a Multifield element
addNavigation()  : Navigation
Add 'navigation' to the form. By navigation we mean a 'navigation div' at the buttom of the form containing the submit button. This method is optional for customization purposes -- navigation is created automatically.
addParagraph()  : Paragraph
Adds a \ValidFormBuilder\Paragraph object to the internal elements collection.
elementsToJs()  : string
Generate the Javascript output only for the fields and conditions.
fieldsetAsHtml()  : string
Generates HTML output for all fieldsets and their children elements.
fieldsToHtml()  : string
This method generates HTML output for the current internal elements collection.
generateId()  : string
Generate a unique ID
get()  : string|array<string|int, mixed>
Read parameters from the `$_REQUEST` array and body string with an optional fallback value
getAction()  : string
getCachedFields()  : Collection
Fetch a cached flat collection of form fields instead of making an expensive getFields() call and looping through all elements
getDefaults()  : array<string|int, mixed>
getDescription()  : string
getDisplayErrors()  : bool
getElements()  : Collection
getFields()  : Collection
Get a flat Collection of all internal elements.
getHttpBodyValue()  : string|array<string|int, mixed>
Get the value of a form field from the raw HTTP body. This is used for PUT and DELETE HTTP methods.
getInvalidFields()  : array<string|int, mixed>
Get an associative array of invalid field names (the array's keys) and the error message (the values)
getIsSet()  : bool
Read parameters from the `$_REQUEST` array and body string and determine if it is "set".
getJsEvents()  : array<string|int, mixed>
getLastFieldset()  : Fieldset
Retrieve the last fieldset from the form elements.
getMainAlert()  : string
getMeta()  : array<string|int, mixed>
getName()  : string
getNoValuesMessage()  : string
getRequiredStyle()  : string
getStrippedClassName()  : string
Returns the class name and strips off the namespace.
getSubmitLabel()  : string
getUniqueId()  : string
Returns the auto-generated unique ID of this form instance.
getValidField()  : Element|null
Get a valid field object.
isSubmitted()  : bool
Check if the form is submitted by validating the value of the hidden vf__dispatch field.
isValid()  : bool
As short as it is powerful: validate the submitted field values.
renderField()  : Element
Use this utility method to only render \ValidFormBuilder\Element instances of the defined types.
serialize()  : string
Serialize, compress and encode the entire form including it's values
setAction()  : void
setAutoComplete()  : mixed
setCachedFields()  : void
setDefaults()  : mixed
Use an array to set default values on all the forms children.
setDescription()  : void
setDisplayErrors()  : void
setElements()  : void
setJsEvents()  : void
setMainAlert()  : void
setMeta()  : void
setName()  : void
setNoValuesMessage()  : void
setRequiredStyle()  : void
setSubmitLabel()  : void
setUniqueId()  : void
setUseCsrfProtection()  : void
toHtml()  : string
Generate HTML output - build form
toJs()  : string
Generate the Javascript output only.
unserialize()  : ValidForm
Unserialize previously serialized ValidForm object
valuesAsHtml()  : string
A utility method to parse an overview of the submitted values.

Constants

VFORM_BOOLEAN

Input type[radio]

public number VFORM_BOOLEAN = 10

VFORM_CHECK_LIST

Group element. Each added element is an input[type=checkbox]

public number VFORM_CHECK_LIST = 13

VFORM_COMPARISON_CONTAINS

Check if the value contains this string (case insensitive)

public string VFORM_COMPARISON_CONTAINS = "contains"

VFORM_COMPARISON_DOES_NOT_CONTAIN

Check if the value does not contain this string (case insensitive)

public string VFORM_COMPARISON_DOES_NOT_CONTAIN = "doesnotcontain"

VFORM_COMPARISON_EMPTY

Check if this value is empty

public string VFORM_COMPARISON_EMPTY = "empty"

VFORM_COMPARISON_ENDS_WITH

Check if the value **ends** with this string

public string VFORM_COMPARISON_ENDS_WITH = "endswith"

VFORM_COMPARISON_EQUAL

Check if this value is equal (case insensitive)

public string VFORM_COMPARISON_EQUAL = "equal"

VFORM_COMPARISON_GREATER_THAN

Check if this value is greater than

public string VFORM_COMPARISON_GREATER_THAN = "greaterthan"

VFORM_COMPARISON_GREATER_THAN_OR_EQUAL

Check if this value is greater than or equal

public string VFORM_COMPARISON_GREATER_THAN_OR_EQUAL = "greaterthanorequal"

VFORM_COMPARISON_IN_ARRAY

Check if the value matches your own custom regular expression

public string VFORM_COMPARISON_IN_ARRAY = "in_array"

VFORM_COMPARISON_LESS_THAN

Check if this value is less than

public string VFORM_COMPARISON_LESS_THAN = "lessthan"

VFORM_COMPARISON_LESS_THAN_OR_EQUAL

Check if this value is less than or equal

public string VFORM_COMPARISON_LESS_THAN_OR_EQUAL = "lessthanorequal"

VFORM_COMPARISON_NOT_EMPTY

Check if this value is **not** empty

public string VFORM_COMPARISON_NOT_EMPTY = "notempty"

VFORM_COMPARISON_NOT_EQUAL

Check if this value is **not** equal (case insensitive)

public string VFORM_COMPARISON_NOT_EQUAL = "notequal"

VFORM_COMPARISON_NOT_IN_ARRAY

Check if the value matches your own custom regular expression

public string VFORM_COMPARISON_NOT_IN_ARRAY = "not_in_array"

VFORM_COMPARISON_REGEX

Check if the value matches your own custom regular expression

public string VFORM_COMPARISON_REGEX = "regex"

VFORM_COMPARISON_STARTS_WITH

Check if the value **starts** with this string

public string VFORM_COMPARISON_STARTS_WITH = "startswith"

VFORM_CURRENCY

Input element

public number VFORM_CURRENCY = 16

VFORM_CUSTOM

Input type[text] with custom regular expression validation

public number VFORM_CUSTOM = 18

VFORM_CUSTOM_TEXT

Textarea with custom regular expression validation

public number VFORM_CUSTOM_TEXT = 19

VFORM_DATE

Input type[text] with European date validation (dd/mm/yyyy)

public number VFORM_DATE = 17

VFORM_EMAIL

Input type[text] with email validation

public number VFORM_EMAIL = 6

VFORM_FILE

Input type[file]

public number VFORM_FILE = 9

VFORM_HIDDEN

Input type[hidden]

public number VFORM_HIDDEN = 22

VFORM_HTML

Textarea with basic input validation + HTML tags allowed

public number VFORM_HTML = 20

VFORM_INTEGER

Input type[text] with integer validation

public number VFORM_INTEGER = 4

VFORM_MATCH_ALL

ValidForm Condition match

public string VFORM_MATCH_ALL = "all"

Match all of the defined conditions

VFORM_MATCH_ANY

ValidForm Condition match

public string VFORM_MATCH_ANY = "any"

Match any of the defined conditions

VFORM_NUMERIC

Input type[text] with numeric validation

public number VFORM_NUMERIC = 3

VFORM_PARAGRAPH

Not an element. This creates a paragraph in between form fields.

public number VFORM_PARAGRAPH = 15

VFORM_PASSWORD

Input type[password]

public number VFORM_PASSWORD = 7

VFORM_RADIO_LIST

Group element. Each added element is an input[type=radio]

public number VFORM_RADIO_LIST = 12

VFORM_SELECT_LIST

Group element. Each added element is an option element

public number VFORM_SELECT_LIST = 14

VFORM_SIMPLEURL

Input type[text] with basic URL validation

public number VFORM_SIMPLEURL = 8

VFORM_STRING

Input type[text] with standard string validation

public number VFORM_STRING = 1

VFORM_TEXT

Textarea element type

public number VFORM_TEXT = 2

VFORM_URL

Input type[text] with url validation

public number VFORM_URL = 21

VFORM_WORD

Input type[text] with single word validation

public number VFORM_WORD = 5

Methods

__call()

Magic caller method

public __call(string $method, mixed $values) : mixed
Parameters
$method : string
$values : mixed
Tags
throws
BadMethodCallException

__construct()

Create a new ValidForm Builder instance

public __construct(string $name[, string $description = null ][, string $action = null ][, array<string|int, mixed> $meta = array() ]) : mixed
Parameters
$name : string

The form's name. This will also be the value of the name attribute in the generated HTML. Note*: At this moment, it is mandatory to enter a name even though the API states that it is optional. Check issue 8 for more details.

$description : string = null

Optional. A descriptive text shown above the form fields.

$action : string = null

The generated form element's action attribute.

$meta : array<string|int, mixed> = array()

Custom form meta array

__get()

Magic getter method

public __get(string $property) : mixed
Parameters
$property : string
Tags
throws
BadMethodCallException

__set()

Magic setter method

public __set(string $property, mixed $value) : mixed
Parameters
$property : string
$value : mixed
Tags
throws
BadMethodCallException

addArea()

Add an area to the internal elements collection.

public addArea([string $label = null ][, bool $active = false ][, string $name = null ][, bool $checked = false ][, array<string|int, mixed> $meta = array() ]) : Area

See Area for examples

Parameters
$label : string = null

The title of this area

$active : bool = false

If true, the title has a checkbox which can enable or disable all child elements

$name : string = null

The ID of this area

$checked : bool = false

Use in combination with $active; if true, the checkbox will be checked by default

$meta : array<string|int, mixed> = array()

The meta array

Return values
Area

addButton()

Adds a <button> element to the internal fields collection.

public addButton(string $strLabel[, array<string|int, mixed> $arrMeta = array() ]) : Button

For an example; see Button

Parameters
$strLabel : string

The button's label

$arrMeta : array<string|int, mixed> = array()

The meta array

Return values
Button

addField()

Add a new element to the internal elements collection

public addField(string $name, string $label, int $type[, array<string|int, mixed> $validationRules = array() ][, array<string|int, mixed> $errorHandlers = array() ][, array<string|int, mixed> $meta = array() ][, bool $blnJustRender = false ]) : Element
APIYes

Example; add a text field:

$objForm->addField(
    "first-name",
    "First name",
    ValidForm::VFORM_STRING,
    array(
        // Make this field required
        "required" => true
    ),
    array(
        // Show this error to indicate this is an required field if no value is submitted
        "required" => "This field is required"
    )
);
Parameters
$name : string

The element's name

$label : string

The element's label

$type : int

The element's validation type

$validationRules : array<string|int, mixed> = array()

Optional.Custom validation rules array

$errorHandlers : array<string|int, mixed> = array()

Custom error handling array

$meta : array<string|int, mixed> = array()

Optional. Meta data array

$blnJustRender : bool = false

When true, the element is not added to the internal elements collection. addField() with $blnJustRender set to true is exactly the same as calling ValidForm::renderField()

Return values
Element

Returns null when no valid type is defined

addFieldset()

Add a fieldset to the form field collection

public addFieldset([string $header = null ][, string $noteHeader = null ][, string $noteBody = null ][, array<string|int, mixed> $meta = array() ]) : Fieldset

Example:

$objForm->addFieldset("Header for fieldset", "Note", "Cool fields contained by fieldset.");
Parameters
$header : string = null

The header for this fieldset

$noteHeader : string = null

An optional header for the 'note' block on the side of this fieldset

$noteBody : string = null

The optional body for the 'note block on the side of this fieldset

$meta : array<string|int, mixed> = array()

The meta array

Return values
Fieldset

addHiddenField()

Add a hidden input field to the form collection.

public addHiddenField(string $name, string $type[, array<string|int, mixed> $meta = array() ][, bool $blnJustRender = false ]) : Hidden

Hidden fields can be used for example to inject custom values in your post data and still have them validated using ValidForm Builder.

Parameters
$name : string

The hidden field's name attribute

$type : string

Define a validation type using one of the ValidForm::VFORM_ constants. This does not influence the fact that you're creating a hidden field. This is only used for validation of the hidden field's content.

$meta : array<string|int, mixed> = array()

Optional meta array

$blnJustRender : bool = false

If true, only create a Hidden instance and return it. When false, this Hidden instance is added to the internal elements collection and will be parsed when toHtml() is called.

Return values
Hidden

addHtml()

Injects a string in the form.

public addHtml(string $html[, array<string|int, mixed> $meta = array() ]) : StaticText

Use this to add an extra string in the form. For instance, you can create an input field like this:

Enter the amount:   $ _____

In this example, we used StaticText to inject the dollar sign before our input field.

Parameters
$html : string

The string or HTML code to inject

$meta : array<string|int, mixed> = array()
Return values
StaticText

addJSEvent()

Add a custom javascript event with corresponding callback function

public addJSEvent(string $strEvent, string $strMethod) : mixed

With this method you can either register a custom callback function on one of the predefined custom events or you can register the callback function on a jQuery bindable event (e.g. jQuery().bind(eventName, callback)).

These are predefined event hooks in the ValidForm Builder client-side library:

  • beforeSubmit
  • beforeNextPage
  • afterNextPage
  • beforePreviousPage
  • afterPreviousPage
  • beforeAddPreviousButton
  • afterAddPreviousButton
  • beforeShowPage
  • afterShowPage
  • beforeAddPageNavigation
  • afterAddPageNavigation
  • beforeDynamicChange
  • afterDynamicChange
  • afterValidate
Parameters
$strEvent : string

The event name

$strMethod : string

The name of the callback function

addMultiField()

Create a Multifield element

public addMultiField([string $label = null ][, array<string|int, mixed> $meta = array() ]) : MultiField

Multifield elements allow you to combine multiple fields horizontally with one label. For example, create a first name + last name field with label "Full name"

$objMulti = $objForm->addMultifield("Full name");
// Note: when using addField on a multifield, we don't set a label!
$objMulti->addField(
    "first-name",
    ValidForm::VFORM_STRING,
    array(),
    array(),
    // Keep it short, this is just a first name field
    array("style" => "width: 50px")
);
$objMulti->addField("last-name", ValidForm::VFORM_STRING);

You can also combine select elements to create a date picker:

$objMulti = $objForm->addMultiField("Birthdate");
$objMulti->addField(
    "year",
    ValidForm::VFORM_SELECT_LIST,
    array(),
    array(),
    array(
        "start" => 1920,
        "end" => 2014,
        // 'fieldstyle' gets applied on the <select>
        // regular 'style' applies on the wrapping <div>
        "fieldstyle" => "width: 75px"
    )
);
$objMulti->addField(
    "month",
    ValidForm::VFORM_SELECT_LIST,
    array(),
    array(),
    array(
        "start" => 01,
        "end" => 12,
        "fieldstyle" => "width: 75px"
    )
);
$objMulti->addField(
    "day",
    ValidForm::VFORM_SELECT_LIST,
    array(),
    array(),
    array(
        "start" => 1,
        "end" => 31,
        "fieldstyle" => "width: 75px"
    )
);
Parameters
$label : string = null
$meta : array<string|int, mixed> = array()

The meta array

Return values
MultiField

addNavigation()

Add 'navigation' to the form. By navigation we mean a 'navigation div' at the buttom of the form containing the submit button. This method is optional for customization purposes -- navigation is created automatically.

public addNavigation([array<string|int, mixed> $meta = array() ]) : Navigation
Parameters
$meta : array<string|int, mixed> = array()

Array with meta data. Only the "style" attribute is supported as for now.

Return values
Navigation

addParagraph()

Adds a \ValidFormBuilder\Paragraph object to the internal elements collection.

public addParagraph(string $strBody[, string $strHeader = "" ][, array<string|int, mixed> $meta = array() ]) : Paragraph

This renders a paragraph inside the form. Formfields can be added before and after the paragraph. Example:

$objForm->addField("name", "Your Name", ValidForm::VFORM_STRING);
$objForm->addParagraph("Next, you should enter your last name.", "Enter your name!");
$objForm->addField("last-name", "Last Name", ValidForm::VFORM_STRING);
Parameters
$strBody : string

Paragraph body

$strHeader : string = ""

Optional header above the paragraph

$meta : array<string|int, mixed> = array()

Custom meta array

Return values
Paragraph

elementsToJs()

Generate the Javascript output only for the fields and conditions.

public elementsToJs([bool $blnRawJs = false ]) : string

This is particulary useful when using ValidForm Builder in combination with AJAX form handling. You can inject new fields and field logic into an existing ValidForm and all validation will be handled by that "parent" form.

Parameters
$blnRawJs : bool = false

Return javascript without the surrounding <script> tags.

Return values
string

fieldsetAsHtml()

Generates HTML output for all fieldsets and their children elements.

public fieldsetAsHtml(Fieldset $objFieldset, string &$strSet[, bool $hideEmpty = false ]) : string

This method is hardly used in the public API. The only reason why this is a public method is to enable customization through class extension.

Parameters
$objFieldset : Fieldset

The Fieldset object to parse

$strSet : string

Previously generated HTML

$hideEmpty : bool = false

Set to true to hide empty field values from the overview. Defaults to false.

Return values
string

Generated HTML

fieldsToHtml()

This method generates HTML output for the current internal elements collection.

public fieldsToHtml([bool $blnForceSubmitted = false ][, bool &$blnNavigation = false ]) : string

This method is mostly used internally in the library and it's therefore not recommended to use this except for these rare occasions when you only want the rendered fields an not all the meta surrounding the fields like the form tag, description element and form error message.

Parameters
$blnForceSubmitted : bool = false

This forces the form rendering as if the fields are submitted

$blnNavigation : bool = false

This is a reference returning true if the form contains a navigation element

Return values
string

Generated HTML output

generateId()

Generate a unique ID

public generateId([int $intLength = 8 ]) : string
Parameters
$intLength : int = 8

ID length

Return values
string

Generated ID

get()

Read parameters from the `$_REQUEST` array and body string with an optional fallback value

public static get(string $param[, string $replaceEmpty = "" ]) : string|array<string|int, mixed>
Parameters
$param : string

The parameter to read

$replaceEmpty : string = ""

Optional replace value when parameter is not available or empty

Return values
string|array<string|int, mixed>

getAction()

public getAction() : string

getAction() Returns the value of $__action

Return values
string

getCachedFields()

Fetch a cached flat collection of form fields instead of making an expensive getFields() call and looping through all elements

public getCachedFields() : Collection
Return values
Collection

getDefaults()

public getDefaults() : array<string|int, mixed>

getDefaults() Returns the value of $__defaults

Return values
array<string|int, mixed>

getDescription()

public getDescription() : string

getDescription() Returns the value of $__description

Return values
string

getDisplayErrors()

public getDisplayErrors() : bool

getDisplayErrors() Returns the value of $__displayerrors

Return values
bool

getFields()

Get a flat Collection of all internal elements.

public getFields() : Collection

This loops through all elements and adds each element and their children to a new Collection which will be returned. This results in a flat Collection filled with ValidForm Builder elements.

Return values
Collection

getHttpBodyValue()

Get the value of a form field from the raw HTTP body. This is used for PUT and DELETE HTTP methods.

public static getHttpBodyValue(string $param[, string $varReplaceNotSet = null ]) : string|array<string|int, mixed>
Parameters
$param : string

The parameter to read

$varReplaceNotSet : string = null

Optional replace value when parameter is not set in the body

Return values
string|array<string|int, mixed>

getInvalidFields()

Get an associative array of invalid field names (the array's keys) and the error message (the values)

public getInvalidFields() : array<string|int, mixed>

This method is very useful when using ValidForm Builder with AJAX empowered forms. Example:

//*** The basic form set-up
$objForm = new ValidForm('ajaxForm');

$objForm->addField(
    'firstName',
    'First name',
    ValidForm::VFORM_STRING,
    array(
        'required' => true
    ),
    array(
        'required' => 'This field is required'
    )
);
$objForm->addField(
    'lastName',
    'Last name',
    ValidForm::VFORM_STRING
);
$objForm->addField(
    'emailAddress',
    'E-mail address',
    ValidForm::VFORM_EMAIL,
    array(),
    array(
        'type' => 'Invalid e-mail address'
    )
);

//*** Form handling
if ($objForm->isSubmitted() && $objForm->isValid()) {
    // Form is submitted and valid, do stuff with the validated values
} elseif ($objForm->isSubmitted()) {
    // Form is submitted but not valid, return the invalid fields array as a response:
    $strOutput = json_encode(
        $objForm->getInvalidFields()
    );
} else {
    // Form is not even submitted, show regular parsed form
    $strOutput = $objForm->toHtml();
}

Assuming we've posted the following values (and managed to bypass client-side validation):

  • firstName: ''
  • lastName: 'van Baalen'
  • emailAddress: 'Robin Hood'

The following would be a response from getInvalidFields():

array(
    'firstName' => 'This field is required',
    'emailAddress' => 'Invalid e-mail address'
)
Return values
array<string|int, mixed>

getIsSet()

Read parameters from the `$_REQUEST` array and body string and determine if it is "set".

public static getIsSet(string $param) : bool
Parameters
$param : string

The parameter to read

Return values
bool

getJsEvents()

public getJsEvents() : array<string|int, mixed>

getJsEvents() Returns the value of $__jsevents

Return values
array<string|int, mixed>

getLastFieldset()

Retrieve the last fieldset from the form elements.

public getLastFieldset() : Fieldset

If no fieldset exists or the last element is not a valid object, a new fieldset is created and returned.

Return values
Fieldset

getMainAlert()

public getMainAlert() : string

getMainAlert() Returns the main alertof this ValidForm instance

Return values
string

getMeta()

public getMeta() : array<string|int, mixed>

getMeta() Returns the value of $__meta

Return values
array<string|int, mixed>

getName()

public getName() : string

getName() Returns the name of this ValidForm instance

Return values
string

getNoValuesMessage()

public getNoValuesMessage() : string

getNoValuesMessage() Returns the value of $__novaluesmessage

Return values
string

getRequiredStyle()

public getRequiredStyle() : string

getRequiredStyle() Returns the value of $__requiredstyle

Return values
string

getStrippedClassName()

Returns the class name and strips off the namespace.

public static getStrippedClassName(string $classname) : string
Parameters
$classname : string

The classname with optional namespace reference

Return values
string

Only the classname without the namespace.

getSubmitLabel()

public getSubmitLabel() : string

getSubmitLabel() Returns the value of $__submitlabel

Return values
string

getUniqueId()

Returns the auto-generated unique ID of this form instance.

public getUniqueId() : string
Return values
string

getValidField()

Get a valid field object.

public getValidField(string $id) : Element|null

This is about the most important method of ValidForm Builder. Use this to get a valid field after validation to fetch it's validated value.

Example:

$objForm = new ValidForm('example');

$objForm->addField('test', 'Test field', ValidForm::VFORM_STRING);

if ($objForm->isSubmitted() && $objForm->isValid()) {
    $strTest = $objForm->getValidField("test")->getValue();
    // $strTest now contains the validated value of the 'test' field which is safe for database storage etc.

    $strOutput = "Test value is: " . $strTest;
} else {
    $strOutput = $objForm->toHtml();
}
Parameters
$id : string
Return values
Element|null

isSubmitted()

Check if the form is submitted by validating the value of the hidden vf__dispatch field.

public isSubmitted([bool $blnForce = false ]) : bool
Parameters
$blnForce : bool = false

Fake isSubmitted to true to force field values.

Return values
bool

isValid()

As short as it is powerful: validate the submitted field values.

public isValid() : bool
Return values
bool

True if successful, false if one of the fields contains an error.

renderField()

Use this utility method to only render \ValidFormBuilder\Element instances of the defined types.

public static renderField(string $name, string $label, int $type, array<string|int, mixed> $validationRules, array<string|int, mixed> $errorHandlers, array<string|int, mixed> $meta) : Element

Elements rendered with this method aren't added to the internal elements collection.

Parameters
$name : string

The element's name

$label : string

The element's label

$type : int

The element's validation type

$validationRules : array<string|int, mixed>

Optional.Custom validation rules array

$errorHandlers : array<string|int, mixed>

Custom error handling array

$meta : array<string|int, mixed>

Optional. Meta data array

Return values
Element

Returns null when no valid type is defined

serialize()

Serialize, compress and encode the entire form including it's values

public serialize([bool $blnSubmittedValues = true ]) : string
Parameters
$blnSubmittedValues : bool = true

Whether or not to include submitted values or only serialize default values.

Return values
string

Base64 encoded, gzcompressed, serialized form.

setAction()

public setAction() : void

setAction(string $strFormAction) Overwrites the value of $__action

setAutoComplete()

public setAutoComplete(mixed $blnValue) : mixed
Parameters
$blnValue : mixed

setCachedFields()

public setCachedFields() : void

setCachedFields(Collection $objCollection) Overwrites the value of $__cachedfields. Not recommended for API use*

setDefaults()

Use an array to set default values on all the forms children.

public setDefaults([array<string|int, mixed> $arrDefaults = array() ]) : mixed

The array's keys should be the form name to set the default value of, the value is the actual value or values to set.

Example 1 - Basic defaults:

//*** The form
$objCheck = $objForm->addField("cool", "Coolest PHP Library", ValidForm::VFORM_STRING);

//*** Set field 'cool' default value to "ValidForm Builder"
$objForm->setDefaults([
    "cool" => "ValidForm Builder"
]);

Example 2 - An array of defaults:

//*** The form
$objCheck = $objForm->addField("cool", "Cool checklist", ValidForm::VFORM_CHECK_LIST);
$objCheck->addField("Option 1", "option1");
$objCheck->addField("Option 2", "option2");
$objCheck->addField("Option 3", "option3");

$objCheck = $objForm->addField("cool-text", "Coolest PHP Library", ValidForm::VFORM_STRING);

//*** Check options 2 and 3 by default using setDefaults()
$objForm->setDefaults([
    "cool-text" => "ValidForm Builder",
    "cool" => ["option2", "option3"]
]);
Parameters
$arrDefaults : array<string|int, mixed> = array()

The array of default values. Keys are field names, values strings or arrays

Tags
throws
InvalidArgumentException

setDescription()

public setDescription() : void

setDescription(string $strDescription) Overwrites the value of $__description

setDisplayErrors()

public setDisplayErrors() : void

setDisplayErrors(bool $arrJsEvents) Overwrites the value of $__displayerrors. Not recommended* use ValidForm::addJsEvent() instead.

setElements()

public setElements() : void

setElements(Collection $objCollection) Overwrites the internal elements collection.

setJsEvents()

public setJsEvents() : void

setJsEvents(array $arrJsEvents) Overwrites the value of $__jsevents.

setMainAlert()

public setMainAlert() : void

setMainAlert(string $strMainAlert) Overwrites the main alert of this ValidForm instance

setMeta()

public setMeta() : void

setMeta(array $arrMeta) Overwrites the value of $__meta

setName()

public setName() : void

setName(string $strName) Overwrites the name of this ValidForm instance

setNoValuesMessage()

public setNoValuesMessage() : void

setNoValuesMessage(string $strNoValuesMessage) Overwrites the value of $__novaluesmessage.

setRequiredStyle()

public setRequiredStyle() : void

setRequiredStyle(string $strRequiredStyle) Overwrites the value of $__requiredstyle.

setSubmitLabel()

public setSubmitLabel() : void

setSubmitLabel(string $strSubmitLabel) Overwrites the value of $__submitlabel

setUniqueId()

public setUniqueId() : void

setUniqueId(string $strUniqueId) Overwrites the value of $__uniqueid.

setUseCsrfProtection()

public setUseCsrfProtection() : void

setUseCsrfProtection(boolean $value) Overwrites the value of $__usecsrfprotection

toHtml()

Generate HTML output - build form

public toHtml([bool $blnClientSide = true ][, bool $blnForceSubmitted = null ][, string $strCustomJs = "" ]) : string
Parameters
$blnClientSide : bool = true

Render javascript code or not, defaults to true

$blnForceSubmitted : bool = null

This forces the form rendering as if the fields are submitted

$strCustomJs : string = ""

Inject custom javascript to be executed while initializing ValidForm Builder client-side.

Return values
string

Generated HTML output

toJs()

Generate the Javascript output only.

public toJs([string $strCustomJs = "" ]) : string

This is particulary useful when using ValidForm Builder in combination with AJAX form handling. In that case you don't want to output the HTML together with the javascript.

Parameters
$strCustomJs : string = ""

Inject custom javascript to be executed while initializing ValidForm Builder client-side.

Return values
string

unserialize()

Unserialize previously serialized ValidForm object

public static unserialize(string $strSerialized) : ValidForm
Parameters
$strSerialized : string

Serialized ValidForm object

Return values
ValidForm

valuesAsHtml()

A utility method to parse an overview of the submitted values.

public valuesAsHtml([bool $hideEmpty = false ][, string $collection = null ]) : string

This generates a table with label: value pairs. The output of this function is mostly used in for example e-mail bodies. When the contact form created with ValidForm Builder is submitted, you only have to e-mail the results of valuesAsHtml()

Parameters
$hideEmpty : bool = false

Set to true to hide empty field values from the overview. Defaults to false.

$collection : string = null

Optional - advanced usage only; a custom Collection of elements to parse

Return values
string

Generated table with label: value pairs


        
On this page

Search results