FormBuilder / $forms

FormBuilder is the ProcessWire Form Builder module API

When the module is installed, ProcessWire provides it as the $forms API variable.

$form = $forms->load('contact');
echo $forms->render('contact');

For hook-based customization of rendered and submitted forms, see API-HOOKS.md. Most form lifecycle customization happens through FormBuilderProcessor hooks.

Expand all      API reference

Getting Forms

load($id)

Load one form by name or ID.

$form = $forms->load('contact');

Returns FormBuilderForm|null.

loadAll()

Load all forms, indexed by form name.

foreach($forms->loadAll() as $name => $form) {
  echo $name;
}

Returns FormBuilderForm[].

getFormName($id)

Get the form name for a form ID, FormBuilderForm, or InputfieldForm.

Returns string.

getFormNames($id = 0)

Get all form names indexed by form ID, or pass an ID to get one name.

Returns array|string.

isForm($id)

Return true when the given form name or ID identifies an existing form.

Returns bool.

Creating And Saving Forms

addForm($formName)

Create a new form object. Call save() when you are ready to persist it.

$form = $forms->addForm('contact');
$form->addField('email', 'Email', 'Your email');
$form->save();

Returns FormBuilderForm.

save(FormBuilderForm $form)

Save a form.

$forms->save($form);

Returns bool.

delete(FormBuilderForm $form)

Delete a form.

Returns bool.

clone(FormBuilderForm $form, $newFormName = '')

Clone a form to a new form.

Returns FormBuilderForm.

Rendering Forms

render($form, $vars = array())

Render a form by name, ID, or FormBuilderForm. This returns a FormBuilderRender object containing markup plus any styles/scripts collected for the render. Also known as: Embed method C

$form = $forms->render('contact');
echo $form->styles;
echo $form->scripts;
echo $form; // string value is form markup

Example of using the $vars argument to pre-populate form:

$form = $forms->render('contact', [
    'first_name' => 'Ryan',
    'last_name' => 'Cramer',
    'email'=> 'ryan@processwire.com',
]);
echo $form->styles . $form->scripts . $form;

Example of rendering with ProcessWire WireMarkupRegions to populate HTML containing elements:

$form = $forms->render('contact');
echo "
    <head pw-append>$form->styles</head>
    <body pw-append>$form->scripts</body>
    <div id='content' pw-append>$form</div>
";

Returns FormBuilderRender.

embed($formName, array $vars = null)

Return embed markup for embed method A or B. This makes the form render in an <iframe> rendered by the /form-builder/ page using the /site/templates/form-builder.php template file:

// render form 
echo $forms->embed('contact');

// with variables pre-populated
echo $forms->embed('contact', [
    'first_name' => 'Ryan',
    'last_name' => 'Cramer',
    'email' => 'ryan@processwire.com'
]); 
Entries

Entries are the results collected from user-submitted forms.

getEntry($entryID, $form = 0)

Get a submitted entry by ID. Entry IDs are unique across all forms, so the form can usually be inferred from $entryID. Pass $form when you want to require that the entry belongs to a specific form.

Returns array|false.

saveEntry(array $entry, $form = 0)

Save an entry array. Existing entries should include their id in the $entry array; new entries omit it.

Returns int|false. On success it returns the saved entry ID.

findEntries($keywords, $operator = '*=', $form = 0)

Search entries by keywords. If no $form is given, all forms will be searched. For selector-based queries, use $form->entries()->find($selector) where $form is a FormBuilderForm object.

Returns array[].

countEntries($id)

Return the number of entries for a form name, ID, or FormBuilderForm.

Returns int.

Export And Import

exportJSON($form)

Return the JSON schema for a form name, ID, or FormBuilderForm.

Returns string.

importJSON($form, $json)

Import JSON schema data into a form name, ID, or FormBuilderForm.

Returns bool.

Files

getFilesPath($tmp = false, $create = true)

Return the filesystem path FormBuilder uses for uploaded files.

Returns string.

getFileKey($formID, $entryID, $filename)

Generate a portable key for a file belonging to a form and entry. A portable key is a string that can be used to retrieve the file and is safe to include in URLs. It is referred to as "key" in other file methods.

Returns string|false.

getFileFromKey($key)

Resolve a file key back to a filename.

Returns string|false.

getFileURL($formID, $entryID, $filename)

Return a URL where a stored file can be viewed.

Returns string|false.

viewFile($key)

Send a stored file to the browser using a file key.

Returns void. Throws Wire404Exception if the file cannot be found or viewed.

Access And Tools

hasPermission($name, $form)

Return whether the current user has the named FormBuilder permission for a form.

Returns bool.

isReservedName($name)

Return whether a name is reserved and should not be used for a form or field.

Returns bool.

form($form, $throw = true)

Resolve a form name, ID, or FormBuilderForm to a FormBuilderForm object. When $throw is true, invalid values throw a FormBuilderException; when false, invalid values return false.

Returns FormBuilderForm|false.

formID($value, $throw = true)

Resolve a form name, ID, or FormBuilderForm to a form ID.

Returns int.

formName($value, $throw = true)

Resolve a form name, ID, or FormBuilderForm to a form name.

Returns string.

entryToForm($entry)

Resolve an entry array or entry ID to the FormBuilderForm it belongs to.

Returns FormBuilderForm|false.

getFramework(FormBuilderForm $form)

Return the configured FormBuilderFramework for a form, when available.

Returns FormBuilderFramework|null.

count()

Return the total number of forms in FormBuilder.

Returns int.

themesPath($theme = '')

Return the filesystem path for FormBuilder themes, optionally including a theme name.

Returns string.

frameworksPath()

Return the filesystem path for FormBuilder frameworks.

Returns string.

themesURL($theme = '')

Return the URL for FormBuilder themes, optionally including a theme name.

Returns string.

frameworksURL()

Return the URL for FormBuilder frameworks.

Returns string.

formLog($form, $str)

Record a FormBuilder log entry.

Returns void.

Examples

Update A Form Setting

$fbForm = $forms->load('contact');
$fbForm->successMessage = 'Thanks, we received your message.';
$fbForm->save();

Add And Remove Fields

$fbForm = $forms->load('contact');
$fbForm->addField('phone', 'Text', 'Phone', [
  'required' => true,
  'columnWidth' => 50,
]);
$fbForm->removeField('old_field');
$fbForm->save();

Find Entries With A Selector

$fbForm = $forms->load('contact');
$entries = $fbForm->entries()->find('created>=2026-01-01, sort=-created, limit=10');

Save Or Update An Entry

$entryID = $forms->saveEntry([
  'first_name' => 'Ryan',
  'email' => 'ryan@example.com',
], 'contact');

$entry = $forms->getEntry($entryID);
$entry['email'] = 'new@example.com';
$forms->saveEntry($entry);

Export And Import A Form Schema

$json = $forms->exportJSON('contact');
$target = $forms->load('contact-copy');

if($target) {
  $forms->importJSON($target, $json);
}
FormBuilderForm

A FormBuilderForm represents one form, its settings, and its fields. FormBuilder often uses the variable $fbForm to represent a FormBuilderForm, at least when there is potential for confusion with InputfieldForm, which might also be represented by the variable name $form. The FormBuilderForm class extends the FormBuilderField class and also inherits its methods.

// Loading a form
$fbForm = $forms->load('contact');

// Creating a form
$fbForm = $forms->addForm('contact');
$fbForm->addField('first_name', 'Text', 'First name');
$fbForm->addField('last_name', 'Text', 'Last name');
$fbForm->addField('email', 'Email', 'Your email');
$fbForm->addField('message', 'Textarea', 'Message');
$fbForm->save();

// Updating a field
$field = $fbForm->getField('message');
$field->description = 'Please describe your needs';
$fbForm->save();

// Removing a field
$fbForm->removeField('last_name');
$fbForm->save();

// Convert to an InputfieldForm
$inputfields = $fbForm->getInputfield();

Properties

Core

PropertyTypeDescription
idintForm ID.
namestringForm name.
descriptionstringForm description.
mobilePxintMobile responsive breakpoint for this form, in pixels.
flagsintForm flags. See FormBuilderProcessor::formFlag* constants.
formFlagsintAlias of flags.
rolesarrayForm roles for access control.
themestringjQuery UI theme used by this form, if any.
frameworkstringHTML/CSS framework used by this form.
pluginActionsarrayNames of plugin actions enabled for this form.
numEntriesintNumber of submitted entries for this form.
lastEntryDatestringDate of last submitted form entry.
firstEntryDatestringDate of first submitted form entry.
numFieldsintNumber of fields in this form.

Flags And Settings

PropertyTypeDescription
saveFlagsintBitwise flags for save actions. See FormBuilderProcessor::saveFlag* constants.
allowPresetbool|intAllow preset field values from GET variables.
skipSessionKeybool|intDisable session tracking and CSRF protection.
useCookiesbool|intRemember form values in cookies.

Spam Protection

PropertyTypeDescription
honeypotstring|arrayField name, or names, to use as a honeypot.
spamWordsarray|nullWords that cause a submission to be treated as spam when spam words are enabled.
spamFlagsint|nullSpam handling flags. Common values include silent, verbose, and save-spam-entry behaviors.
akismetstringCSV data for Akismet configuration.

Entries

PropertyTypeDescription
listFieldsarrayField names to show in entries list by default.
entryDaysintMaximum days an entry may be saved in the system.
partialEntryTypeintStorage type for partial entries, where 0 is session and 1 is database.
partialEntryDaysintMaximum days an incomplete/partial entry may exist.
spamEntryDaysintMaximum days a spam entry may be saved.

Administrator Email

Settings for administrator email.

PropertyTypeDescription
emailTostringAdministrator email recipient address, addresses, or format string.
emailFromstringAdministrator email reply-to address, also used as from address when emailFrom2 is not specified.
emailFrom2stringAdministrator email from address when different from emailFrom.
emailSubjectstringAdministrator email subject line.

Auto-responder

Settings for auto-responder email.

PropertyTypeDescription
responderTostringField containing the submitter email address, or CSV string for multiple fields.
responderFromstringAuto-responder from address.
responderFromNamestringAuto-responder from name.
responderReplyTostringAuto-responder reply-to address.
responderSubjectstringAuto-responder subject.
responderBodystringAuto-responder body.

Duplicate Submission

Settings for sending a duplicate copy of the form submission to another URL.

PropertyTypeDescription
action2stringDuplicate submission URL.
action2_addstringFields to add to duplicate submission, in textarea format.
action2_removestringNewline-separated field names to remove from duplicate submission.
action2_renamestringField renames for duplicate submission, in key=value format with one per line.

Output

PropertyTypeDescription
submitTextstringDefault submit button text.
nextTextstringDefault next button text for paginated forms.
backTextstringDefault back button text for paginated forms.
successMessagestringMessage displayed after successful form submission.
errorMessagestringMessage displayed when the form has errors.
submitNotifybool|intNotify user if they attempt to leave after changing the form without submitting.

Save To Pages

These settings apply only if the form is configured to save form submissions to pages.

PropertyTypeDescription
savePageTemplateintTemplate ID for pages created from entries.
savePageParentintParent page ID for pages created from entries.
savePageFieldsarrayMap of page field IDs to form field names.
savePageSubfieldsstringMulti-line mapping of form_field=page_field or form_field=page_field.subfield.
savePageStatusintPage status used for newly created pages.

Google Sheets

To populate a Google Sheet you must have the GoogleClientAPI module installed.

PropertyTypeDescription
googleSpreadsheetUrlstring|nullFull URL of Google Sheet to populate with entries.
googleSpreadsheetFieldsarray|nullForm field names to populate into Google Sheet, in order.
googleSheetsResponseFieldstringOptional field name to populate with the Google Sheets response.

Pagination

PropertyTypeDescription
hLevelintHeadline level used above paginated forms, or 0 for off.
showNavintSelect-nav position for paginations, or 0 for off.

addField($name, $type = '', $label = '', array $options = [])

Create and append a field to the form. $type is the Inputfield class name without the Inputfield prefix, such as Text, Email, Textarea, or Select.

Returns FormBuilderField. The returned field is already added to the form, but the form is not saved until you call $fbForm->save().

$fbForm->addField('first_name', 'Text', 'First name', [
  'required' => true,
  'columnWidth' => 50,
]);

add(FormBuilderField $child)

Append an existing FormBuilderForm or FormBuilderField as a child field element.

Returns FormBuilderForm.

removeField($key)

Remove a field by object or name.

Returns FormBuilderForm.

save()

Save this form.

Returns bool.

render()

Render and/or process this form using its FormBuilderProcessor.

Returns string.

processor($options = array())

Return the FormBuilderProcessor for this form. Pass ['reset' => true] to force a new instance.

Returns FormBuilderProcessor.

entries()

Return the FormBuilderEntries manager for this form.

Returns FormBuilderEntries.

isSubmitted()

Return whether the form has been submitted in the current request.

Returns bool.

getErrors()

Return form processing errors.

Returns array.

hasPermission($name)

Return whether the current user has a permission for this form.

Returns bool.

getFramework()

Return the HTML/CSS framework used by this form.

Returns FormBuilderFramework|null.

getPageBreakFields()

Return FormBuilderPageBreak fields indexed by page number.

Returns FormBuilderField[].

getNumPaginations()

Return the number of paginations in the form.

Returns int.

hasField($name)

Return whether this form has a field by name.

Returns bool.

getField($name)

Get a field by name from anywhere in the form.

Returns FormBuilderField|null.

getFieldByName($name)

Alias of getField($name).

Returns FormBuilderField|null.

exists($name)

Return whether a field exists in the form.

Returns bool.

children()

Return direct child fields. Use getChildrenFlat() when you need nested fields too.

Returns FormBuilderField[].

getChildrenFlat(array $options = array())

Return all fields as a flat array indexed by field name.

Returns FormBuilderField[].

getInputfield(array $options = array())

Create a new InputfieldForm from this form configuration.

Returns InputfieldForm.

Flags (bitwise)

By default the flag methods operate on the FormBuilderForm $flags property. See the FormBuilderProcessor class formFlag* constants. The flag methods below also include a $property argument where you can optionally substitute saveFlags (for save action flags) or spamFlags (for spam action flags). See the corresponding saveFlag* or spamFlag* constants in the FormBuilderProcessor class.

hasFlag($flag, $property = 'flags')

Return whether a form flag is present.

For this method and the two below:

Returns int.

addFlag($flag, $property = 'flags')

Add a form flag in memory.

Returns void.

removeFlag($flag, $property = 'flags')

Remove a form flag in memory.

Returns void.

FormBuilderField

FormBuilderField represents one field in a FormBuilderForm. It also provides the base tree methods used by FormBuilderForm.

setName($name)

Set and sanitize the field name.

Returns FormBuilderData.

fbForm()

Return the root FormBuilderForm for this field.

Returns FormBuilderForm.

getSetting($key)

Get a setting directly from this field.

Returns mixed|null.

setArray(array $data)

Populate this field from array data, including nested children data.

Returns void.

getArray()

Return this field and its children as array data.

Returns array.

add(FormBuilderField $child)

Append a child field.

Returns FormBuilderField.

addField($name, $type = '', $label = '', array $options = [])

Create and append a child field.

Returns FormBuilderField.

remove($key)

Remove a child field by object or name.

Returns FormBuilderField.

children()

Return direct children.

Returns FormBuilderField[].

getChildrenFlat(array $options = array())

Return all descendant fields as a flat array.

Returns FormBuilderField[].

child($name)

Return a direct child by name.

Returns FormBuilderField|null.

getFieldByName($name)

Return a field by name from anywhere in the form tree.

Returns FormBuilderField|null.

getInputfield(array $options = array())

Create a new ProcessWire Inputfield instance from this field configuration.

Returns Inputfield.

FormBuilderEntries

FormBuilderEntries manages submitted entry data for one form.

$entries = $forms->load('contact')->entries();
$latest = $entries->find('sort=-created, limit=10');

Note that an individual form entry is represented by a regular PHP associative array.

find($selectorString, array $options = array())

Find entries with a selector string.

Returns array[], where each item is an associative array representing one entry.

getById($id, $col = '')

Get an entry by ID, optionally returning one database column.

Returns array|mixed|false. Returns an entry array when $col is omitted, the requested column value when $col is specified, or false when no entry matches.

getByName($name, $col = '')

Get an entry by its entry name string.

Returns array|mixed|false. Returns an entry array when $col is omitted, the requested column value when $col is specified, or false when no entry matches.

getBySelector($selectorString)

Get the first matching entry for a selector string.

Returns array|null.

importCSV($filename, array $options = array())

Import entries from a CSV file.

Returns array with import counts, skipped/failed line numbers, and warnings.

exportCSV(FormBuilderForm $form, $selectorString, array $options = array())

Export matching entries as CSV and send the file to output.

Returns never; this method sends output and exits.

save(array $entry)

Save a new or existing entry. Existing entries should include id.

Returns int|bool. On success it returns the entry ID; on failure it returns false.

saveField($id, $name, $value)

Update one field value for an existing entry.

Returns bool.

delete($id)

Delete one entry by ID.

Returns int|bool. On success it returns the deleted entry ID; on failure it returns false.

deleteAll()

Delete all entries for the form.

Returns bool.

deleteOlderThan($age, $ageType = 'DAYS', $dateColumn = 'created', $flags = null)

Delete entries older than a given age.

Returns int, the number of entries deleted.

getTotal()

Return the total number of entries for the form.

Returns int.

getLastEntryDate($reverse = false)

Return the newest entry date, or the first entry date when $reverse is true.

Returns string, or blank string when there are no entries.

getFilesPath($entryID = 0, $create = true, $formID = 0)

Return the files path for the form or a specific entry.

Returns string.

hasFilesPath($entryID = 0, $formID = 0)

Return whether a files path exists.

Returns bool.

getForm()

Return the FormBuilderForm these entries belong to.

Returns FormBuilderForm.

addEntryFlag(array $entry, $flag)

Add an entry flag in memory and return the modified entry array.

Returns array.

removeEntryFlag(array $entry, $flag)

Remove an entry flag in memory and return the modified entry array.

Returns array.

validEntryName($name)

Validate an entry name string, returning the name or an empty string.

Returns string.

isReservedProperty($property)

Return whether an entry property name is reserved for system use.

Returns bool.

FormBuilderEmail

FormBuilderEmail prepares and sends administrator and auto-responder email messages. It is most often customized from FormBuilderProcessor email hooks.

Properties

PropertyTypeDescription
tostringRecipient email address, addresses, or conditional recipient rules.
fromstringFrom email address.
fromNamestringFrom name.
replyTostringReply-to email address or field name to pull from submitted form data.
subjectstringEmail subject.
bodystringEmail body in HTML.

setRawFormData(array $data)

Set raw submitted form data.

Returns void.

getRawFormData()

Return raw submitted form data.

Returns array.

setMailer($mailerName)

Set the WireMail module name to use. Use WireMail for native PHP mail behavior or leave blank for auto-detect.

Returns void.

setWireMail(WireMail $wireMail)

Provide a specific WireMail instance.

Returns void.

getWireMail()

Return the WireMail instance that will be used.

Returns WireMail.

addFileAttachment($filename)

Add a file attachment to the email when the WireMail implementation supports attachments.

Returns bool. Returns true when the file exists and was queued as an attachment, or false when the file does not exist.

send($template = 'email')

Send the email using the named email template.

Returns bool|int. Returns 0 when there are no recipients; otherwise returns the result from the mailer.

setSkipFieldName($fieldName)

Skip a field by name when rendering the email body.

Returns FormBuilderEmail.

setValues(array $values, $entityEncode = true)

Add values to the email template data.

Returns void.

setLabels(array $labels, $entityEncode = true)

Add labels to the email template data.

Returns void.

Notes
  • Changes to a FormBuilderForm or its FormBuilderField objects are not saved until you call $fbForm->save() or $forms->save($fbForm).
  • FormBuilderForm is FormBuilder's configuration object for a form. ProcessWire's InputfieldForm is the rendered/processable form object produced from that configuration.
  • Individual submitted entries are regular PHP associative arrays, not entry objects.
  • Methods that send files to output, such as FormBuilderEntries::exportCSV() and FormBuilder::viewFile(), end the request after sending output.
  • Hookable methods and lifecycle customization examples are documented separately in API-HOOKS.md.

API reference: methods, hooks

The $forms API variable is present if the commercial module FormBuilder is installed. Below are examples of embed method B and C. There are also embed methods A and D and instructions for those can be found on the "Embed" tab when editing a form.

// Embed method B (in iframe)
echo $forms->embed('form-name');

// Embed method C (preferred method)
$form = $forms->render('form-name');
echo $form->styles; // preferably in <head>
echo $form->scripts; // preferably in <head> or before </body>
echo $form; // wherever form should output

Please see FormBuilderProcessor for most of the hookable methods in FormBuilder, this is where most API usage and customization occurs. FormBuilderProcessorAction modules can also be used to affect any part of a form’s life cycle.

More FormBuilder class reference pages

ClassDescription
FormBuilderProcessorHandles most parts of a form’s life cycle (rendering, processing).
FormBuilderEntriesManages the data submitted to a form, which we refer to as an entry.
FormBuilderEmailHandles the setup and distribution of administrator and auto-responder emails.
FormBuilderFormThis class represents a form and maintains its configuration data and fields.
FormBuilderProcessorActionThe full documented interface for FormBuilder plugin-in modules.

Click any linked item for full usage details and examples. Hookable methods are indicated with the icon. In addition to those shown below, the FormBuilder class also inherits all the methods and properties of: WireData and Wire.

Show $var?     Show args?       Only hookable?    

Tools

NameReturnSummary 
$forms->entryToForm($entry)
bool FormBuilderForm

Given an entry array or ID return the FormBuilderForm object that it belongs to

 
$forms->form($form)
FormBuilderForm

Convert given value to FormBuilderForm if it isn’t already

 
$forms->formID($value)
int

Convert given value to form ID if is isn’t already

 
$forms->formName($value)
string

Convert given value to form name if is isn’t already

 
$forms->getFramework(FormBuilderForm $form)
FormBuilderFramework null

Get the framework used by the given $form

 
$forms->isForm($id)
bool

Given a form ID or name, returns true if is used by a form, false if not

 
$forms->isReservedName(string $name)
bool

Is the given name reserved? If true, it should not be used for form or field name

 

Access

NameReturnSummary 
$forms->hasPermission(string $name, $form)
bool

Check if the current user has the permission name for the given $form

 

Export import

NameReturnSummary 
$forms->exportJSON($form)
string

Return the JSON schema for the given form (name, ID or object)

 
$forms->importJSON($form, string $json)
bool

Import to form (name, ID or object) the given JSON schema

 

For hooks

These methods are only useful for hooking and should not be called directly.

Common

NameReturnSummary 
$forms->getFormName($id)
string

Given a form ID or object, get the name of the form

 

Additional methods and properties

In addition to the methods and properties above, FormBuilder also inherits the methods and properties of these classes:

API reference based on ProcessWire core version 3.0.275