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
Form hooks.
Expand all Collapse all API reference
load($id)
Load one form by name or ID.
$form = $forms->load('contact');Returns Form.
loadAll()
Load all forms, indexed by form name.
foreach($forms->loadAll() as $name => $form) {
echo $name;
}Returns Form.
getFormName($id)
Get the form name for a form ID, Form, 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.
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 Form.
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 Form.
render($form, $vars = array())
Render a form by name, ID, or Form. This returns a
Form 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 markupExample 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 Form.
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 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 Form object.
Returns array[].
countEntries($id)
Return the number of entries for a form name, ID, or Form.
Returns int.
exportJSON($form)
Return the JSON schema for a form name, ID, or Form.
Returns string.
importJSON($form, $json)
Import JSON schema data into a form name, ID, or Form.
Returns bool.
getFilesPath($tmp = false, $create = true)
Return the filesystem path Form Returns 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 Resolve a file key back to a filename. Returns Return a URL where a stored file can be viewed. Returns Send a stored file to the browser using a file key. Returns string.getFileKey($formID, $entryID, $filename)
string|false.getFileFromKey($key)
string|false.getFileURL($formID, $entryID, $filename)
string|false.viewFile($key)
void. Throws Wire404Exception if the file cannot be found or viewed.
hasPermission($name, $form)
Return whether the current user has the named Form Returns Return whether a name is reserved and should not be used for a form or field. Returns Resolve a form name, ID, or Returns Resolve a form name, ID, or Returns Resolve a form name, ID, or Returns Resolve an entry array or entry ID to the Returns Return the configured Returns Return the total number of forms in Form Returns Return the filesystem path for Form Returns Return the filesystem path for Form Returns Return the URL for Form Returns Return the URL for Form Returns Record a Form Returns bool.isReservedName($name)
bool.form($form, $throw = true)
Form to a Form object.
When $throw is true, invalid values throw a Form; when false,
invalid values return false.Form.formID($value, $throw = true)
Form to a form ID.int.formName($value, $throw = true)
Form to a form name.string.entryToForm($entry)
Form it belongs to.Form.getFramework(Form
Form for a form, when available.Form.count()
int.themesPath($theme = '')
string.frameworksPath()
string.themesURL($theme = '')
string.frameworksURL()
string.formLog($form, $str)
void.
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);
}A Settings for administrator email. Settings for auto-responder email. Settings for sending a duplicate copy of the form submission to another URL. These settings apply only if the form is configured to save form submissions to pages. To populate a Google Sheet you must have the GoogleClientAPI module installed. Create and append a field to the form. Returns Append an existing Returns Remove a field by object or name. Returns Save this form. Returns Render and/or process this form using its Returns Return the Returns Return the Returns Return whether the form has been submitted in the current request. Returns Return form processing errors. Returns Return whether the current user has a permission for this form. Returns Return the HTML/CSS framework used by this form. Returns Return Returns Return the number of paginations in the form. Returns Return whether this form has a field by name. Returns Get a field by name from anywhere in the form. Returns Alias of Returns Return whether a field exists in the form. Returns Return direct child fields. Use Returns Return all fields as a flat array indexed by field name. Returns Create a new Returns By default the flag methods operate on the Return whether a form flag is present. For this method and the two below: Returns Add a form flag in memory. Returns Remove a form flag in memory. Returns Form represents one form, its settings, and its fields.
Form$fbForm to represent a Form,
at least when there is potential for confusion with InputfieldForm, which might
also be represented by the variable name $form. The Form class
extends the Form 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
Property Type Description idintForm ID. namestringForm name. descriptionstringForm description. mobilePxintMobile responsive breakpoint for this form, in pixels. flagsintForm flags. See Form 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
Property Type Description saveFlagsintBitwise flags for save actions. See Form constants.allowPresetbool|intAllow preset field values from GET variables. skipSessionKeybool|intDisable session tracking and CSRF protection. useCookiesbool|intRemember form values in cookies. Spam Protection
Property Type Description 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
Property Type Description 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
Property Type Description 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
Property Type Description 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
Property Type Description 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
Property Type Description 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
Property Type Description 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
Property Type Description 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
Property Type Description 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 = [])
$type is the Inputfield class name
without the Inputfield prefix, such as Text, Email, Textarea, or
Select.Form. 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(Form
Form or Form as a child field element.Form.removeField($key)
Form.save()
bool.render()
Form.string.processor($options = array())
Form for this form. Pass ['reset' => true] to force
a new instance.Form.entries()
Form manager for this form.Form.isSubmitted()
bool.getErrors()
array.hasPermission($name)
bool.getFramework()
Form.getPageBreakFields()
Form fields indexed by page number.Form.getNumPaginations()
int.hasField($name)
bool.getField($name)
Form.getFieldByName($name)
getField($name).Form.exists($name)
bool.children()
getChildrenFlat() when you need nested fields too.Form.getChildrenFlat(array $options = array())
Form.getInputfield(array $options = array())
InputfieldForm from this form configuration.InputfieldForm.Flags (bitwise)
Form $flags property.
See the FormformFlag* 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 FormhasFlag($flag, $property = 'flags')
int.addFlag($flag, $property = 'flags')
void.removeFlag($flag, $property = 'flags')
void.
Form represents one field in a Form. It also provides
the base tree methods used by Form.
setName($name)
Set and sanitize the field name.
Returns Form.
fbForm()
Return the root Form for this field.
Returns Form.
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 Form.
addField($name, $type = '', $label = '', array $options = [])
Create and append a child field.
Returns Form.
remove($key)
Remove a child field by object or name.
Returns Form.
children()
Return direct children.
Returns Form.
getChildrenFlat(array $options = array())
Return all descendant fields as a flat array.
Returns Form.
child($name)
Return a direct child by name.
Returns Form.
getFieldByName($name)
Return a field by name from anywhere in the form tree.
Returns Form.
getInputfield(array $options = array())
Create a new ProcessWire Inputfield instance from this field configuration.
Returns Inputfield.
Form 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 Form these entries belong to.
Returns Form.
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.
Form prepares and sends administrator and auto-responder email
messages. It is most often customized from Form email hooks.
Properties
| Property | Type | Description |
|---|---|---|
to | string | Recipient email address, addresses, or conditional recipient rules. |
from | string | From email address. |
fromName | string | From name. |
replyTo | string | Reply-to email address or field name to pull from submitted form data. |
subject | string | Email subject. |
body | string | Email 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 Form.
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.
- Changes to a
Formor itsBuilderForm Formobjects are not saved until you callBuilderField $fbForm->save()or$forms->save($fbForm). Formis FormBuilderForm Builder's configuration object for a form. ProcessWire's InputfieldFormis 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
FormandBuilderEntries::exportCSV() Form, end the request after sending output.Builder::viewFile() - Hookable methods and lifecycle customization examples are documented separately in API-HOOKS.md.
API reference: methods, properties, hooks
Form The Stripe Payments Processor
is an example of a Form To create a Your module class should implement one or more of the defined methods further down in the method reference, as needed, to accomplish whatever your action module is intended to do. These defined methods can also be used to add hooks anywhere in Form Your module should be placed in the file Below is an example of the code for a Form You should also create a Test it out!
In your admin, do a Modules > Refresh and then install your module.
Edit a form and click the “Actions” tab. Check the box for your “Hello World”
action. It will open a text input where you can configure the Hello message.
Save, and then Preview your form. Now let’s take the module a little bit further, adding an action
in the admin where form entries are listed. We’ll add a “Hello” button
that can be applied to any existing form entry. In this example,
it will say "hello" to any checked entries. Silly I know, but
hopefully hints at what might be possible. This would be added
to the class from our previous code example above. Click any linked item for full usage details and examples. Hookable methods are indicated with the icon. In addition to those shown below, the Record an error message Methods that can be optionally implemented by the module and will be called automatically by Form Populate Inputfields to configure this action (if configurable) Set and save to DB a config value for this action/module here and in the Form Set a config value for this action/module here and in the Form In addition to the methods and properties above, FormCreating an action module
Form module, create a class named Form, optionally replacing “Hello” with the name of your action. The class should extend the Form
class located in /site/modules/Form. actionReady() and formReady().Form in the directory
/site/modules/Form (optionally replacing “Hello” with the name of your action). // FormForm file
in the same directory that returns information about your module:$info = [
'title' => 'Hello world action example',
'version' => 1,
'summary' => 'Example of a FormTaking it further
// List entries in admin
// Adds a 'hello world' action button for entries admin checks boxes for
public function adminListEntries() {
$this->addHookAfter('ProcessFormForm class also inherits all the methods and properties of: WireData and Wire.Common
Name Return Summary $this Implementation
Tools
Config
Name Return Summary None self self Properties
Name Return Summary Form string Name of the current form Additional methods and properties
API reference based on ProcessWire core version 3.0.275