Skip to content

PHP API, Hooks & CLI

<?php namespace ProcessWire;
$forms = Forms::requireInstance($wire);
// Definitions & import/export
$form = $forms->getForm('charter-inquiry');
$all = $forms->getForms();
$forms->saveForm('charter-inquiry', $spec);
$spec = $forms->exportForm('charter-inquiry');
$forms->importForm($specOrJson);
$forms->addFormsPath($config->paths->templates . 'custom-forms/');
// Rendering, submission & validation
$html = $forms->render('charter-inquiry', ['theme' => 'modern', 'sourcePageId' => $page->id]);
$stepErrors = $forms->validateStep('charter-inquiry', 0, $input->post->getArray());
$result = $forms->submit('charter-inquiry', $input->post->getArray(), ['enforceCsrf' => true]);
$closedReason = $forms->checkFormAvailability('charter-inquiry', $input->ip());
$alreadySent = $forms->hasSubmitted('charter-inquiry', $values);
// Drafts, self-service tokens & delivery
$draft = $forms->restoreDraftToken('charter-inquiry', $draftToken);
$forms->sendDraftResumeEmail('charter-inquiry', $email, $resumeUrl);
$forms->deleteSubmissionByToken($deleteToken, 'charter-inquiry');
$forms->deliverSubmission('charter-inquiry', $submission, $sanitizedValues);
$forms->deliverAfterPayment($form, $submission);
$forms->retrySubmissionDelivery('charter-inquiry', $submissionId);
// Submissions, surveys & A/B testing
$entries = $forms->submissions('charter-inquiry', 'sort=-created, limit=100');
$count = $forms->countSubmissions('charter-inquiry');
$survey = $forms->surveyResults('charter-inquiry');
$surveyHtml = $forms->renderSurveyResults('charter-inquiry');
$abHtml = $forms->renderAbTest('charter-inquiry-layout');

Hookable Extension Seams (Forms & ProcessForms: 21 Hooks)

Section titled “Hookable Extension Seams (Forms & ProcessForms: 21 Hooks)”

External modules hooking Forms::* declare 'formsHooks' (true | string | list<string>) in getModuleInfo() for lazy pull-discovery.

Hook Arguments & Return Timing What It Does
Forms::render (string|EntryItem|FormDefinition $form, array $options = []): string Before / After Renders frontend form HTML, themes, and CSRF/honeypot markup.
Forms::submit (string|EntryItem|FormDefinition $form, array $rawInput, array $context = []): SubmissionResult Before / After Runs the full validation, spam check, persistence, and delivery pipeline.
Forms::afterSubmit (FormDefinition $form, ?EntryItem $submission, SubmissionResult $result): void After Fires after a valid non-spam submission is stored.
Forms::enrichSubmissionValues (FormDefinition $form, array $values, array $context = []): array After Normalizes or enriches submitted field values right before persistence and notifications.
Forms::evaluateAiSpam (FormDefinition $form, array $values, array $context = []): ?array After Plugs custom or Ai-powered semantic spam classification into SpamGuard.
Forms::forwardWebhook (string $event, array $payload): void After Inspects or forwards outbound forms.* webhook payloads.
Forms::processPaymentIntent (FormDefinition $form, ?EntryItem $submission, array $values, array $context = []): ?array After Handles payment field checkout links or subscriptions (Payments).
Forms::resolveMoneyObject (float|int|string $amountMajor, string $currency): ?object After Converts major-unit amounts into minor-unit Money value objects (Currency).
Forms::executeElementMapping (FormDefinition $form, ?EntryItem $submission, array $values): array Before / After Maps validated submission fields onto ProcessWire Pages or Entries items.
Forms::isAiBuilderAvailable / Forms::generateFormSpecFromPrompt (): bool / (string $prompt): ?array After Supplies prompt-to-form AI authoring inside the Visual Builder.
Forms::storePrivateAttachment / resolvePrivateAttachment / deletePrivateAttachments / resolveEditorialImage (string $tmpPath, string $safeFilename, array $context = []): ?array / ... After Bridges private upload storage, secure download resolution, deletion, and editorial image lookup (Media).
Forms::availableIntegrationCatalog / collectIntegrationSchemaFields / collectWebhookForwardingFields / resolveIntegrationEntryConfig / syncIntegrationEntryFields (): array / (array $fields, ...) / (EntryItem $item, FormDefinition $def): void After Extends form-level integration tabs, schema fields, and synced entry settings cleanly.
ProcessForms::translations (): array After Returns localized UI strings for the Setup -> Forms React workspace.
site/ready.php
<?php
declare(strict_types=1);
namespace ProcessWire;
use Totoglu\Entries\Entity\EntryItem;
use Totoglu\Forms\Model\FormDefinition;
use Totoglu\Forms\Submission\SubmissionResult;
// 1. Normalize values before persistence (uppercase charter reference codes)
$wire->addHookAfter('Forms::enrichSubmissionValues', function (HookEvent $event): void {
/** @var FormDefinition $form */
$form = $event->arguments(0);
$values = (array) $event->return;
if ($form->slug === 'charter-inquiry' && isset($values['referral_code'])) {
$values['referral_code'] = strtoupper(trim((string) $values['referral_code']));
$event->return = $values;
}
});
// 2. React after a valid submission is saved
$wire->addHookAfter('Forms::afterSubmit', function (HookEvent $event): void {
/** @var FormDefinition $form */
$form = $event->arguments(0);
/** @var ?EntryItem $submission */
$submission = $event->arguments(1);
/** @var SubmissionResult $result */
$result = $event->arguments(2);
if ($result->ok && $submission instanceof EntryItem) {
$event->wire()->log->save('forms-audit', "Saved {$form->slug} submission {$submission->id}");
}
});
// 3. Add a custom semantic spam rule
$wire->addHookAfter('Forms::evaluateAiSpam', function (HookEvent $event): void {
if ($event->return !== null) {
return;
}
$values = (array) $event->arguments(1);
$message = strtolower((string) ($values['message'] ?? ''));
if (str_contains($message, 'buy cheap backlinks')) {
$event->return = ['isSpam' => true, 'score' => 0.99, 'reason' => 'Blocked keyword pattern'];
}
});

CLI Command (1), Queue (1) & Scheduled Tasks (4)

Section titled “CLI Command (1), Queue (1) & Scheduled Tasks (4)”
Component Arguments / Options Purpose
make:form <slug>, -t/--title, --stencil, -s/--steps, --db, --dry-run, -f/--force, --json Scaffolds a new YAML form blueprint in site/forms/ (or saves directly to DB with --db) from contact, quote, survey, or job-application stencils.
ProcessFormDeliveryQueue queue/ProcessFormDeliveryQueue.php Asynchronous queue worker for email notifications and signed webhooks.
MonitorFormsHealthTask schedule/MonitorFormsHealthTask.php Periodic diagnostics check ($forms->runHealthCheck()) with throttled failure alerts.
PruneFormSubmissionsTask schedule/PruneFormSubmissionsTask.php Nightly pruning of expired submissions and staged uploads ($forms->pruneExpiredSubmissions()).
RunScheduledExportsTask schedule/RunScheduledExportsTask.php Runs recurring Export Profiles ($forms->runScheduledExports()).
SendFormsDigestTask schedule/SendFormsDigestTask.php Dispatches daily or weekly submission summary digests ($forms->sendDigestSummary()).

Run the background queue worker and system cron so queued notifications, signed webhooks, pruning, scheduled exports, and digests execute reliably:

Terminal window
php vendor/bin/wire queue:work --tries=3 --sleep=3
# Crontab entry (runs all 4 Forms scheduled tasks)
* * * * * cd /var/www/aegeanvoyages.example && /usr/bin/php vendor/bin/wire schedule:run >> /var/log/pw-schedule.log 2>&1

Webhook Payload, HMAC Verification & A/B Event Route

Section titled “Webhook Payload, HMAC Verification & A/B Event Route”
  • A/B Tracking Endpoint (/_forms/ab-event): FormsFrontend.js posts impression and conversion beacons to /_forms/ab-event when A/B tests are active.
  • Outbound Webhook Payload & Signature: WebhookDispatcher signs every delivery with X-Forms-Event, X-Forms-Form, X-Forms-Delivery, and X-Forms-Signature (sha256=<hex>):
{
"event": "forms.submission.created",
"timestamp": "2026-06-15T12:15:00Z",
"data": {
"form": "charter-inquiry",
"submission_id": "0196f8d2-3c1a-7b40-9e12-8a4c5d6e7f01",
"values": {
"email": "[email protected]",
"yacht_class": "gulet"
}
}
}
<?php
declare(strict_types=1);
$rawBody = file_get_contents('php://input') ?: '';
$received = $_SERVER['HTTP_X_FORMS_SIGNATURE'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, (string) getenv('FORMS_WEBHOOK_SECRET'));
$isValid = hash_equals($expected, $received);

Automated Testing, Secrets, Caching & Localization

Section titled “Automated Testing, Secrets, Caching & Localization”
  • Mocking Outbound Webhooks in Pest/PHPUnit: Swap the live transport with a fake implementing Totoglu\Forms\Contract\WebhookTransportInterface via $forms->setWebhookTransport($fakeTransport).
  • Secrets via $env:VAR: Reference webhook signing secrets and CAPTCHA keys as $env:FORMS_WEBHOOK_SECRET so credentials never sit in Git or YAML exports.
  • ProCache Exclusion: Exclude /_forms/* from full-page caches, or enable AJAX token hydration so FormsFrontend.js fetches a fresh CSRF token from /_forms/token/{slug}.
  • 6-Locale Translation Packs: Bundled CSV packs (en, tr, de, fr, es, ru) live in site/modules/Forms/languages/ for import under Setup -> Languages -> [Language] -> Site Translation Files.

Submissions Fail With a Timestamp or CSRF Validation Error

Section titled “Submissions Fail With a Timestamp or CSRF Validation Error”
  • When rendering forms on heavily cached pages, enable AJAX mode or let FormsFrontend.js fetch a fresh token from /_forms/token/{slug} before submission.
  • For programmatic tests or CLI scripts, pass ['skipCsrf' => true, 'skipTimestamp' => true, 'skipJsChallenge' => true] in the $context array of $forms->submit().

Webhook Delivery Logs an SSRF or Blocked Host Error

Section titled “Webhook Delivery Logs an SSRF or Blocked Host Error”
  • WebhookUrlPolicy and WireHttpWebhookTransport block loopback (127.0.0.1, localhost.), private RFC 1918 networks, and reserved IPv6 ranges. Point live webhooks to public HTTPS endpoints, or inject a fake transport via $forms->setWebhookTransport() during local testing.

Uploaded Files Are Rejected With a Validation Error

Section titled “Uploaded Files Are Rejected With a Validation Error”
  • Verify the file extension and detected MIME type match the field’s allowlist, avoid double extensions (such as .php.jpg), and check that installed FileValidatorModule upload scanners pass.

Password Fields Are Missing From CSV/XLSX Exports

Section titled “Password Fields Are Missing From CSV/XLSX Exports”
  • By design, SubmissionExporter excludes password and sensitive columns from all exports, while FormSecretMasker redacts them to •••••••• in webhooks and notifications.

Next steps