Custom code from WebForms 3
Overview
This page is for developers whose own module, theme or integration calls WebForms classes. A store that runs WebForms with no custom code can skip it. The upgrade of the store itself is on Upgrading from WebForms 3.
Short names of core classes are relative to MageMe\WebForms\. In Add-on classes, they are relative to
the add-on's own namespace, such as MageMe\WebFormsProductOptions\.
What you can rely on in WebForms 4
From 4.0 on, the WebForms contract is what carries @api. That includes:
- the repository interfaces of forms, sections (fieldsets), fields, logic, submissions, submission values,
messages, quick responses, store view settings, files and statuses, with their
Api/Datainterfaces and column constants; - the narrow service interfaces in
Api/: the change feed, notes, the audit log, notification commands, order links, PDF documents, status assignment and the like; - the integration base classes, with their context objects.
Resource models, collections, the constants of internal tables and every class not marked @api may change in any
release. In 3.x only Api/Data/FieldInterface, Api/Data/FieldsetInterface and Config/Config were marked. If
your code reaches for anything else, check it against this list before the upgrade.
Extension points lists what you can build on.
Two kinds of breakage
- Your class fails with an error. PHP refuses to load a class that implements a changed interface. A class that passes the wrong arguments to a changed constructor fails when it is created. You see the error when that code runs.
- Your code runs and does nothing. A removed getter still answers on the model, an observer is no longer called, a Registry key is never set. Nothing fails. Search your code for the names on this page rather than waiting for an error.
Find what your code uses
| Your code… | Read |
|---|---|
reads webforms_form, webforms_result, webforms_status or another WebForms key from the Magento Registry | The Registry is no longer used |
reads or sets the mail settings of a form (getAdminNotification…, getCustomerNotification…, getApproval…), its getTitle(), or getIsNeedNotification() of a submission | Form and submission members that are gone |
| implements or replaces (DI preference) a WebForms interface | Interfaces that changed |
| extends a WebForms class and declares its own constructor | Constructors that take other arguments; for admin and account controllers and blocks, the form builder's field types and the admin buttons, also The Registry is no longer used; for the uploaders and the File, Image and Gallery field types, Classes that took one of these repositories |
| adds a field type of its own | Constructors that take other arguments ($valueRenderer) and The submission edit form (a legacy admin form element) |
keeps its own copy of form/element/form.phtml, form/multistep/form.phtml or form/default.phtml in a theme | Add-on classes, under Product Options |
observes webforms_field_prepare_save, webforms_fieldset_prepare_save or webforms_logic_prepare_save | Events that are no longer dispatched |
sends mail with Mail\…Notification or Api\Mail\NotificationInterface, or calls sendContactNotification() | Mail classes, Form and submission members that are gone |
uses a TmpFile…Repository or StatisticsRepository, or the uploaders | Repositories that 4.0 does not ship |
| changes the admin page that edits a submission | The submission edit form |
| adds rows to the submission info table | Extra rows in the submission info table |
| extends a mass action of the Forms grid, or of fields, sections or logic rules | Mass actions |
has a plugin on load() or save() of a Magento customer, subscriber, admin user, integration, role or email template | Magento models |
| prints the submissions of a form in a cached block | Pages that list submissions |
runs bin/magento config:set webforms/… in a deployment script | Settings that are gone |
| calls the REST API or GraphQL, or observes their submissions | REST and GraphQL |
| extends a class of Product Options, Product Request, Cart Quote, the GraphQL add-on or an integration add-on | Add-on classes |
The Registry is no longer used
WebForms puts nothing into the Magento Registry in 4.0. It passes the form, the submission and the status through
holder classes instead. Take the holder in your constructor and call get(). It returns null when the page set
nothing:
// 3.x
$form = $this->registry->registry('webforms_form');
// 4.0: MageMe\WebForms\Model\Context\CurrentForm $currentForm in the constructor
$form = $this->currentForm->get();
| 3.x Registry key | Where it was set | In 4.0 |
|---|---|---|
webforms_form | Admin pages, the account page of a form | Model\Context\CurrentForm |
webforms_result | Admin pages, the account page of a submission | Model\Context\CurrentResult |
webforms_status | Admin pages | Model\Context\CurrentStatus |
webforms_quickresponse, webforms_quickresponse_category | Admin pages | Not set at all |
customer_id | The account page of a form | The customer session: Magento\Customer\Model\Session::getCustomerId() |
current_url | Every form block | The block's own data current_url |
result | The storefront print, edit and delete pages | The submission that Controller\ResultAction::authorize() returns |
is_form_preview | The form preview | Nothing. Whether the request previews a draft is Block\Form\Context::getPreviewState(). |
A plugin that put a form or a submission into the Registry for a WebForms block calls set() on the holder.
The current product: a subclass of the form block that read it from the Registry takes
Magento\Catalog\Helper\Data and calls getProduct(), as Product Options does.
Classes that took the Registry and now take the holders
These classes have new constructors. If your subclass declares one, match the 4.0 signature. The protected
properties that held the Registry are removed: $registry, $_coreRegistry, and $coreRegistry of Block\Form and
Block\Form\Context. They are also gone from Controller\ResultAction, which takes no holder: see
Constructors that take other arguments. A subclass that read one of them reads the holder.
-
Admin: the controllers
Controller\Adminhtml\Form\EditandController\Adminhtml\Result\Index,Edit,ReplyandExportFiles(the last four also take the submission access check); the form builder's field typesUi\Field\Type\Email,PasswordandRegion(DynamicGrid, which had no constructor of its own, now declares one that takesModel\Context\CurrentForm). The quick response and quick response category edit controllers drop the Registry. The submission edit form reads the submission and its form from the holders. -
Storefront and account: the blocks
Block\Customer\Account,Block\Customer\Account\Results,Block\Customer\Account\Result\View,MessagesandMessageForm; the controllersController\Customer\AccountandController\Customer\Result.Block\Form\ContextandController\Form\ViewtakeModel\Context\PreviewState.Controller\Form\Loadis removed. -
Admin buttons:
Block\Adminhtml\Common\Button\GenericandAclGenerictake a singleBlock\Adminhtml\Common\Button\ButtonContext, which carries the request, the UI component context, the authorization, the current form and the status. A button of your own that declares a constructor takes the context and passes only it to the parent. The protected$requestand$contextstay, and$authorizationonAclGeneric;$registryis gone. A button without its own constructor needs no change. The 3.x call below is the one ofAclGeneric;Generictook$request,$registryand$context.// 3.xparent::__construct($authorization, $request, $registry, $context);// 4.0parent::__construct($buttonContext); // MageMe\WebForms\Block\Adminhtml\Common\Button\ButtonContext
Controller\Form\View, and Controller\Form\Preview, which extends it, no longer run Magento's store switcher when
the address carries ___store. Magento opens the page in that store, as for every other page, and the controller
only keeps the store cookie in step. Its constructor takes Magento\Store\Api\StoreCookieManagerInterface in place
of StoreRepositoryInterface and no longer takes StoreSwitcherInterface. The protected properties
$storeRepository and $storeSwitcher give way to $storeCookieManager.
Form and submission members that are gone
The 3.x mail settings of a form became notifications of that form. The upgrade turns each one into a published
notification, active if the 3.x setting was on. In the admin they live on the form's Notifications tab.
Over the Management API they are changed with POST /V1/webforms/forms/:formId/notifications/commands/:name
(add, update, remove, duplicate, set-content, set-conditions) and switched on and off with the
/V1/webforms/notifications/:notificationId/activation/* and deactivate routes.
The old names still answer, and nothing happens. The getters and setters are gone from the interfaces, but
Model\Form and Model\Result are Magento models with magic get… and set…. Called on the model, these names
still answer, from the frozen 3.x column, or null on a store installed fresh with 4.0. A value set and saved lands
in a column 4.0 never reads. Search your code for the names below.
A setting with no equivalent has no behaviour in 4.0. Its 3.x value is kept in the migration ledger, and the column stays in the table.
Members of Api\Data\FormInterface (getter, setter and column constant)
| 3.x member | In 4.0 |
|---|---|
getTitle / setTitle, TITLE | The form has a name (getName) and a browser-tab title (getMetaTitle). A heading shown on the page is a field of the form. The upgrade copies the old title into the meta title wherever the tab would otherwise read differently. |
getIsAdminNotificationEnabled / set…, IS_ADMIN_NOTIFICATION_ENABLED | A notification to staff with the trigger Form Submitted, active or not. |
getAdminNotificationEmail, getAdminNotificationBcc / set…, ADMIN_NOTIFICATION_EMAIL, ADMIN_NOTIFICATION_BCC | That notification's recipients (To and Bcc). |
getAdminNotificationSenderName, getAdminNotificationSenderEmail / set…, ADMIN_NOTIFICATION_SENDER_NAME, ADMIN_NOTIFICATION_SENDER_EMAIL | That notification's sender: a store email identity, or the 3.x address kept as its fixed sender. |
getAdminNotificationTemplateId / set…, ADMIN_NOTIFICATION_TEMPLATE_ID | That notification's content. A Magento email template stays referenced until webforms:upgrade:migrate notification-templates moves it inside. |
getIsAdminNotificationAttachmentEnabled / set…, IS_ADMIN_NOTIFICATION_ATTACHMENT_ENABLED | That notification's attachment setting. |
getIsCustomerNotificationEnabled / set…, IS_CUSTOMER_NOTIFICATION_ENABLED | A notification to the submitter with the trigger Form Submitted. |
getCustomerNotificationTemplateId, getCustomerNotificationSenderName, getCustomerNotificationReplyTo, getCustomerNotificationBcc, getIsCustomerNotificationAttachmentEnabled / set…, CUSTOMER_NOTIFICATION_TEMPLATE_ID, CUSTOMER_NOTIFICATION_SENDER_NAME, CUSTOMER_NOTIFICATION_REPLY_TO, CUSTOMER_NOTIFICATION_BCC, IS_CUSTOMER_NOTIFICATION_ATTACHMENT_ENABLED | Content, sender, reply-to, Bcc and attachment setting of that notification. |
getCustomerNotificationAttachments, getCustomerNotificationAttachmentsSerialized / set…, CUSTOMER_NOTIFICATION_ATTACHMENTS, CUSTOMER_NOTIFICATION_ATTACHMENTS_SERIALIZED | No equivalent: files fixed to the confirmation mail are not sent by 4.0. |
getIsApprovalNotificationEnabled, getApprovalNotificationBcc / set…, IS_APPROVAL_NOTIFICATION_ENABLED, APPROVAL_NOTIFICATION_BCC | Notifications to the submitter with the trigger Submission Approval Changed, one per status; Bcc is their recipient setting. The upgrade creates them only on a form whose approval controls were on: with the controls hidden no approval ever changed, so the 3.x mails never fired. |
getApprovalNotificationApprovedTemplateId, getApprovalNotificationNotapprovedTemplateId, getApprovalNotificationCompletedTemplateId / set…, APPROVAL_NOTIFICATION_APPROVED_TEMPLATE_ID, APPROVAL_NOTIFICATION_NOTAPPROVED_TEMPLATE_ID, APPROVAL_NOTIFICATION_COMPLETED_TEMPLATE_ID | The content of the Submission Approval Changed notification filtered to Approved, Not Approved and Completed. |
getEmailReplyTemplateId / set…, EMAIL_REPLY_TEMPLATE_ID | The content of the notification with the trigger Reply Sent To Customer. |
getAdminEmailReplyTemplateId / set…, ADMIN_EMAIL_REPLY_TEMPLATE_ID | The content of a notification to staff with the trigger Customer Replied, created by the upgrade only where a template was set. |
getIsEmailHeaderEnabled / set…, IS_EMAIL_HEADER_ENABLED | No equivalent. |
getIsAsyncLoaded / set…, IS_ASYNC_LOADED | No equivalent. |
getIsMenuLinkEnabled / set…, IS_MENU_LINK_ENABLED | No equivalent: the admin toolbar no longer lists forms. |
| Other 3.x member | In 4.0 |
|---|---|
Api\Data\ResultInterface::getIsNeedNotification / setIsNeedNotification, IS_NEED_NOTIFICATION | No equivalent. A submission's mails are queued by its notifications when it's saved, and sent by the webforms_notification_delivery cron job. Nothing marks the submission itself. |
Api\ResultRepositoryInterface::updateById(int $id) | Api\ResultUpdateInterface::updateById(int $id), with the same signature and result. The REST route POST /V1/webforms/result/:id/update is unchanged and now calls that interface. |
Api\Data\FieldInterface::getDisplayOptions() | MageMe\WebForms\Config\Options\Field\DisplayOption::toOptionArray() |
Api\Utility\Field\ContactInterface::sendContactNotification($result) | A notification whose recipients come from the Contact field. getContactArray() still resolves the contacts. |
Block\Form::getRegistry(), Block\Form\Context::getCoreRegistry() | No equivalent: the form block reads nothing from the Registry. The form it shows is getForm(). Whether the request previews a draft is Block\Form\Context::getPreviewState(). |
Controller\Form\Preview::IS_FORM_PREVIEW | No equivalent: nothing read the flag. |
Interfaces that changed
Code that only calls these interfaces is not affected. A class of your own that implements one, or replaces it with a DI preference, must follow it, or PHP refuses to load the class.
Methods with a new optional parameter. Declare it in your class:
Api\Data\FieldInterface::getValueForSubject($value, array $options = [])Api\Data\FieldInterface::getLogicTargetOptionsArray(?array $fieldsToFieldsets = null): arrayApi\FormRepositoryInterface::getResultsById(int $id, ?int $customerId = null, ?string $filter = null, ?int $pageSize = null, ?int $currentPage = null): array
New methods. Add them to your class:
Api\FormRepositoryInterface::getPublicById(int $id, ?int $storeId = null): FormInterface,getPreviewableById(int $id, ?int $storeId = null): FormInterface,getStorefrontDataById(int $id, ?int $storeId = null): arrayandcountResultsById(int $id, ?int $customerId = null, ?string $filter = null): intApi\StoreRepositoryInterface::findEntityStores(int $storeId, string $entityType, array $entityIds): array- the data interfaces, which 4.0 extends with the new settings of each entity:
Api\Data\FormInterface(69 new methods),MessageInterface(20),ResultInterface(19),FieldInterface(18),LogicInterface(4),ResultValueInterface(2). Extend the module's own model instead of implementing these from scratch.
Constructors that take other arguments
A class of your own that extends one of these and declares a constructor passes the new arguments on. A class without its own constructor needs no change.
| Base class | What changed |
|---|---|
Block\Form\Element\AbstractElement, Block\Form\Element\Field\AbstractField (the storefront blocks of field types) | A required Model\Contract\PartAttributes before $data. |
Model\Field\Context, Model\File\Context | A required Model\Field\ValueRenderer just before the resource model. It prints the markup of an answer from the templates under view/base/templates/field/value. A field type of your own takes the context and needs no change, unless it declares a property $valueRenderer of its own, which Model\Field\AbstractField now has. |
Model\Field\Context, Model\Form\Context (the context of Model\Form) | The resource model of their table as a required argument and, after it, Model\Form\CopyScope; Model\Form\Context follows it with Model\Cache\CleanDeferral. They take Magento\Customer\Model\Session where 3.x took SessionFactory, and Model\Form\Context takes Model\Customer\Access\Visitor after Model\Cache\CleanDeferral. They take other new arguments as well: a class that extends one of them and declares a constructor follows the 4.0 signature. |
Block\Form\Context (the context of the form block) | Magento\Customer\Model\Session and Model\Customer\Access\Visitor before $data. Model\Form\Context and Block\Form\Context read sign-in state and customer group from getVisitor(), so both stay correct on a page served from the full page cache. |
Controller\ResultAction (the base of the storefront submission pages) | No longer takes its 3.x fourth argument, Magento\Framework\Registry. Two more required arguments after the other six: the submission access check (Model\Customer\Access\ResultAccess) and Model\Customer\Access\ActorFactory. |
Controller\Adminhtml\Result\AbstractAjaxResultMassAction (the base of the 3.x integration send actions) | Four more required arguments after its 3.x five: the logger, the submission access check (Model\Inbox\Authorization\ResultAccess), the bulk updater (Model\Result\Mass\BulkUpdate) and the unstored-submission cleanup (Model\Notification\Dispatch\UnstoredSubmissionCleanup). A send action can extend Controller\Adminhtml\Result\AbstractIntegrationSend instead, which takes a single context object: see Add-on integration contract. |
Model\TmpFile\AbstractTmpFile | A required Helper\MediaStorageHelper second (after the store manager) and an optional File\StorageRoot last. |
Helper\Statistics\AbstractStat | Model\ResourceModel\Statistics instead of ResourceConnection. |
File\AbstractUploader and the uploaders, Model\Field\Type\File, Image and Gallery, Controller\Adminhtml\File\AbstractDownload | See Classes that took one of these repositories. |
Controller\Adminhtml\Form\AbstractAjaxFormMassAction, Controller\Adminhtml\AbstractAjaxMassAction | See Mass actions. |
A class that only takes one of the contexts Model\Form\Context, Model\Field\Context or Block\Form\Context, and
declares no constructor of its own, needs no change.
Events that are no longer dispatched
The 3.x edit pages of a field, a fieldset and a logic rule dispatched webforms_field_prepare_save,
webforms_fieldset_prepare_save and webforms_logic_prepare_save. WebForms 4 edits all three in the form builder,
which saves them when the form is published, and dispatches none of these events. There is no per-element
replacement. An observer on them stops being called, without an error.
webforms_fieldset_prepare_save is still dispatched by the admin's submission edit page, with the submission as
payload, as in 3.x.
The events WebForms dispatches in 4.0 are in the Events reference.
Mail classes
The 3.x mail classes Mail\AbstractNotification, AdminNotification, CustomerNotification,
ApprovalNotification and MessageNotification are gone. So is their interface Api\Mail\NotificationInterface,
with its DI preference.
WebForms 4 sends a form's mail through the notifications of that form. Code that called or implemented the interface has to move to them: configure the mail as a notification of the form instead of sending it from code. See Notifications.
Repositories that 4.0 does not ship
Statistics and temporary uploads are bookkeeping of the module, not something other code reads or writes, so 4.0 has no repository for them. These interfaces and classes are gone, with their DI preferences:
Api\StatisticsRepositoryInterface,Api\StatisticsSearchResultInterface,Model\Repository\StatisticsRepositoryApi\TmpFileDropzoneRepositoryInterface,Api\TmpFileDropzoneSearchResultInterface,Model\Repository\TmpFileDropzoneRepositoryApi\TmpFileMessageRepositoryInterface,Api\TmpFileMessageSearchResultInterface,Model\Repository\TmpFileMessageRepositoryApi\TmpFileGalleryRepositoryInterface,Api\TmpFileGallerySearchResultInterface,Model\Repository\TmpFileGalleryRepositoryApi\TmpFileCustomerNotificationRepositoryInterface,Api\TmpFileCustomerNotificationSearchResultInterface,Model\Repository\TmpFileCustomerNotificationRepository
What to use instead:
- A form's submission counts (total, unread, unreplied, last submitted):
GET /V1/webforms/forms/:formId/stats. - Uploads reach a submission through the form itself: the storefront upload, or the file values of a REST or GraphQL submit. The module cleans them up.
The GraphQL add-on's captcha token repository is gone the same way:
MageMe\WebFormsGraphQl\Api\CaptchaTokenRepositoryInterface, shipped in mageme/module-webforms-3-graph-ql 3.2.0 to
3.2.3, and its DI preference. Captcha tokens are bookkeeping of the add-on, so there is no replacement. A class that
implemented the interface or asked for it in a constructor has to drop it. The add-on's Model\Resolver\Recaptcha,
Plugin\MageMe\WebForms\Helper\Result\PostHelper\ValidateCaptcha and Cron\PurgeCaptchaTokens now take
Model\Repository\CaptchaTokenRepository in their constructors.
The admin route webforms/file/customerNotificationUpload is gone with its controller
Controller\Adminhtml\File\CustomerNotificationUpload, and so are File\CustomerNotificationUploader::copyFileFromTmpDir()
and saveFileToTmpDir(). No screen of 4.0 called them. Files a store already attached to its customer notifications
stay where they are.
Classes that took one of these repositories
They take the resource model of the table instead: Model\ResourceModel\Statistics, TmpFileDropzone,
TmpFileMessage, TmpFileGallery or TmpFileCustomerNotification.
Model\Field\Type\File,ImageandGallery. A custom field type that extends one of them passes the resource model to the parent constructor where it passed the repository.File\DropzoneUploader,MessageUploader,GalleryUploaderandCustomerNotificationUploader, which also take the collection factory of their temporary table, andFile\DropzoneApiUploader.Helper\StatisticsHelper, with the statistics collection factory; the storefront and admin dropzone controllers; the storefront reply controllerController\Customer\Message\Save.- The admin reply controller
Controller\Adminhtml\Message\Saveand the form save controllerController\Adminhtml\Form\Saveno longer take a temporary-file repository at all. Their constructors were rebuilt in 4.0, so a subclass that declares its own constructor follows the 4.0 signature.
The uploaders and the admin download base: full constructors
Class names are relative to MageMe\WebForms, except Filesystem, UploaderFactory, StoreManager, Random and
Context, which are Magento's, as in 3.x.
File\AbstractUploader takes a required File\LocalUploaderFactory and an optional File\StorageRoot after the four
3.x arguments. A subclass passes them on:
// 3.x
parent::__construct($fileSystem, $uploaderFactory, $storeManager, $random);
// 4.0
parent::__construct($fileSystem, $uploaderFactory, $storeManager, $random, $localUploaderFactory, $storageRoot);
File\MessageUploader, File\GalleryUploader and File\CustomerNotificationUploader replace the temporary-file
repository with the resource model and the collection factory of their table, and add the two base arguments. The
message uploader also takes an optional Helper\ConfigHelper. The customer notification uploader no longer copies
files out of its temporary area, so it also drops the repository and factory of the saved files and the factory of
its temporary files:
// 3.x
MessageUploader(FileMessageRepositoryInterface $fileMessageRepository,
TmpFileMessageRepositoryInterface $tmpFileMessageRepository, FileMessageFactory $fileMessageFactory,
TmpFileMessageFactory $tmpFileMessageFactory, Filesystem $fileSystem, UploaderFactory $uploaderFactory,
StoreManager $storeManager, Random $random)
// 4.0
MessageUploader(FileMessageRepositoryInterface $fileMessageRepository,
Model\ResourceModel\TmpFileMessage $tmpFileMessageResource,
Model\ResourceModel\TmpFileMessage\CollectionFactory $tmpFileMessageCollectionFactory,
FileMessageFactory $fileMessageFactory, TmpFileMessageFactory $tmpFileMessageFactory,
Filesystem $fileSystem, UploaderFactory $uploaderFactory, StoreManager $storeManager, Random $random,
LocalUploaderFactory $localUploaderFactory, ?StorageRoot $storageRoot = null,
?ConfigHelper $configHelper = null)
// 3.x
GalleryUploader(FileGalleryRepositoryInterface $fileGalleryRepository,
TmpFileGalleryRepositoryInterface $tmpFileGalleryRepository, FileGalleryFactory $fileGalleryFactory,
TmpFileGalleryFactory $tmpFileGalleryFactory, Filesystem $fileSystem, UploaderFactory $uploaderFactory,
StoreManager $storeManager, Random $random)
// 4.0
GalleryUploader(FileGalleryRepositoryInterface $fileGalleryRepository,
Model\ResourceModel\TmpFileGallery $tmpFileGalleryResource,
Model\ResourceModel\TmpFileGallery\CollectionFactory $tmpFileGalleryCollectionFactory,
FileGalleryFactory $fileGalleryFactory, TmpFileGalleryFactory $tmpFileGalleryFactory,
Filesystem $fileSystem, UploaderFactory $uploaderFactory, StoreManager $storeManager, Random $random,
LocalUploaderFactory $localUploaderFactory, ?StorageRoot $storageRoot = null)
// 3.x
CustomerNotificationUploader(FileCustomerNotificationRepositoryInterface $fileCustomerNotificationRepository,
FileCustomerNotificationFactory $fileCustomerNotificationFactory,
TmpFileCustomerNotificationRepositoryInterface $tmpFileCustomerNotificationRepository,
TmpFileCustomerNotificationFactory $tmpFileCustomerNotificationFactory, Filesystem $fileSystem,
UploaderFactory $uploaderFactory, StoreManager $storeManager, Random $random)
// 4.0
CustomerNotificationUploader(Model\ResourceModel\TmpFileCustomerNotification $tmpFileCustomerNotificationResource,
Model\ResourceModel\TmpFileCustomerNotification\CollectionFactory $tmpFileCustomerNotificationCollectionFactory,
Filesystem $fileSystem, UploaderFactory $uploaderFactory, StoreManager $storeManager, Random $random,
LocalUploaderFactory $localUploaderFactory, ?StorageRoot $storageRoot = null)
Controller\Adminhtml\File\AbstractDownload keeps its first three arguments and adds three: the submission access
check, the form access check and the message resource model, through which it finds the submission or the form a
file belongs to. A download controller of your own that declares a constructor passes them on:
// 3.x
public function __construct(RepositoryInterface $repository, Filesystem $filesystem, Context $context)
// 4.0
public function __construct(
RepositoryInterface $repository,
Filesystem $filesystem,
Context $context,
Model\Inbox\Authorization\ResultAccess $resultAccess,
Model\Form\RoleFormGate $formGate,
Model\ResourceModel\Message $messageResource
) {
parent::__construct($repository, $filesystem, $context, $resultAccess, $formGate, $messageResource);
}
If your download controller uses another repository, its files get the submission-file access check. Override
isFileAllowed() to change that.
The submission edit form
The admin page that edits a submission or adds one (Edit, New Result) is now the UI component
webforms_result_form instead of a Magento\Framework\Data\Form. The route, the layout handle
webforms_result_edit and what the page posts to Controller\Adminhtml\Result\Save stay the same. The block
webforms_result_edit is gone: a layout or theme of your own that reached it with referenceBlock no longer finds it.
To change the form:
- Add a modifier of your own to the pool
MageMe\WebForms\Ui\Component\Result\Form\Modifier\Poolinetc/adminhtml/di.xml. Its modifiers build the form: Answers, Logic, SubmissionDetails and SubmissionMeta. - A field still describes itself with
getResultAdminFormConfig(). See Custom field type. - The event
webforms_block_adminhtml_results_edit_form_prepare_layout_fieldis still dispatched for each field, withfieldandconfig.formandfieldsetare nownull: an observer that read them reads the config instead. - The config becomes UI components through a builder chosen by the field type, then by the config's
type(Ui\Component\Result\Form\Field\BuilderPool, argumentsbyFieldTypeandbyConfigType). A field type with its own legacy form element registers a builder that implementsUi\Component\Result\Form\Field\MetaBuilderInterface. Without one, its answer is shown read-only and saved unchanged, and a warning in the system log names the field. Controller\Adminhtml\Result\CustomersJsonanswers in the protocol of Magento'sui-select:searchKey,pageandlimitin,optionsandtotalout.totalisn't a count of the matches: it is one more than the rows loaded so far while another page exists, and0on the last page.- An upload on the page (
webforms/file/dropzoneUpload) needs Edit Result (MageMe_WebForms::edit_result) instead of Manage Forms, and a form the role may write.
Removed classes, templates and scripts
Block\Adminhtml\Result\Edit, Block\Adminhtml\Result\Edit\Form, the form elements Block\Adminhtml\Result\Element\*
(Checkboxes, Colorpicker, Composite, Customer, DynamicGrid, File, Gallery, Image, OrderItems, Password, Radios,
Region, Signature, Swatches, Time, Toggle, Uid), Block\Adminhtml\Result\Autocomplete\Customer, the admin templates
result/element/customer.phtml and logic.phtml, and the scripts js/result/element/*.
Edit\Form::RESULT_UID is now Controller\Adminhtml\Result\Save::RESULT_UID. An Element\*::TYPE constant is the
type name as a string ('swatches', 'time' and so on).
Extra rows in the submission info table
Block\Adminhtml\Result\Info::getExtendedData() returns rows of label and value. The admin now prints value as
text. A row that carries its own markup, such as a link, sets 'is_html' => true and escapes the parts it takes
from users itself. Without that key the markup shows as plain text. A plugin on getExtendedData() written for 3.x
that returns markup needs the key.
Mass actions
Controller\Adminhtml\Form\AbstractAjaxFormMassAction, the base of the Forms grid mass actions (delete, enable and
disable, duplicate, reference number mode), takes a single context object. The context also carries the role's form
access: before the grid selection is applied, the action is limited to the forms the admin's role can reach, so forms
of other roles aren't touched.
A class that extends the base class and declares its own constructor takes the context first, passes only the context to the parent, and adds its own dependencies after it. A class without its own constructor needs no change.
// 3.x
public function __construct(
\MageMe\WebForms\Api\FormRepositoryInterface $repository,
\MageMe\WebForms\Model\ResourceModel\Form\CollectionFactory $collectionFactory,
\Magento\Ui\Component\MassAction\Filter $filter,
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
\Magento\Backend\App\Action\Context $context
)
// 4.0
public function __construct(\MageMe\WebForms\Controller\Adminhtml\Form\MassAction\Context $context)
use MageMe\WebForms\Controller\Adminhtml\Form\MassAction\Context;
public function __construct(Context $context, MyService $service)
{
parent::__construct($context);
$this->service = $service;
}
- The protected members a subclass reads stay the same:
$repository, and$collectionwith$filterand$jsonFactoryfromController\Adminhtml\AbstractAjaxMassAction. Controller\Adminhtml\AbstractAjaxMassActionnow takes a requiredPsr\Log\LoggerInterface $loggerafter its three 3.x arguments, and so do its 3.x subclasses for submissions and quick responses. A mass action of your own that extends one of them directly passes the logger on.- The narrowing is applied in
execute()to whatevergetCollection()returns, so a subclass that builds its own collection keeps it. A subclass that overridesscopeCollection()must call the parent method. - The 3.x bases of the field, section and logic rule mass actions are gone, with the 3.x edit pages of fields,
sections and logic rules:
Controller\Adminhtml\Field\AbstractAjaxFieldMassAction,Controller\Adminhtml\Fieldset\AbstractAjaxFieldsetMassActionandController\Adminhtml\Logic\AbstractAjaxLogicMassAction. A class that extends one of them has no replacement base.
Magento models
WebForms reads and writes Magento's own models (customer, newsletter subscriber, admin user, API integration, admin
role, email template) through their resource models, instead of the deprecated load() and save() of the model.
The model events still fire (model_load_after, customer_save_after and the like). But a plugin of your own on the
model's load() or save(), for example on Magento\Customer\Model\Customer::save(), no longer runs for these
calls. Observe the event or plug into the resource model instead.
Pages that list submissions
A submission names the cache tag webforms_result_<id>. While it is approved, or was approved before the save, it
also names webforms_form_results_<form_id>. So saving, approving, unapproving or deleting it cleans the pages tagged
with that list. Approving or unapproving in bulk from the grids cleans the tag once the change is committed. The
Results widget declares the tag.
A block of your own that prints the submissions of a form:
- declares
webforms_form_results_<form_id>in itsgetIdentities(), or the page cache keeps the old list after an approval; - also declares
webforms_result_<id>of each submission it prints, if it lists submissions that aren't approved: the list tag covers approved submissions only; - doesn't rely on the form's tag
webforms_form_<id>: storing a submission doesn't clean it.
Settings that are gone
These configuration paths have no setting in 4.0, and nothing reads them. A bin/magento config:set on them in a
deployment script either fails or has no effect, so remove such lines:
webforms/general/ajaxwebforms/general/use_uidwebforms/general/preview_enabledwebforms/accessibility/accessible_calendarwebforms/images/cachewebforms/email/async_sendingwebforms/email/sending_limit
webforms/images/grid_thumbnail_width, webforms/images/grid_thumbnail_height,
webforms/images/email_thumbnail_width and webforms/images/email_thumbnail_height have no field in the admin of 4.0,
but the Image and Gallery fields still read them. A value set in 3.x or with config:set keeps sizing their
thumbnails. When nothing is set, they are 100 pixels wide in the submissions grid and on the form, and 200 in emails.
REST and GraphQL
REST. The six 3.x REST routes (/V1/webforms/...) keep their URLs and methods, and require the role rights of the API
block (step 8 of Running the upgrade from 3.x in UPGRADE.md). But 4.0 serves them from the MageMe_WebFormsApi module: a store that calls them needs that module installed
and enabled. See REST API.
A form with a Terms field is sent through POST /V1/webforms/form/:id/submit, and its values changed through the REST
value updates, without an acceptance. The call is made with an admin or integration token, which can't accept for the
customer. The Terms value and token in the body aren't read, no acceptance is recorded, and a submission sent this way
reads No Acceptance Record. An acceptance the customer already gave is kept. For an acceptance, the customer's own
browser or headless storefront sends the form.
GraphQL. While webformsSubmitForm posts the submission, the request's URL query string is empty, unlike 3.x.
Observers and plugins on the submission no longer read URL parameters on GraphQL submissions. Take such values from
the mutation's arguments (formData).
A headless storefront submits a form with a Terms field through webformsSubmitForm, with the consent token of the
wording it showed. Ask for terms on the form's fields, in webformsForm or webformsLogicVisibility:
fieldsets { fields { field_id terms { checkbox_label text revision token is_available } } }
Details: GraphQL. In short:
- Show
checkbox_labelandtextof the field'stermsexactly as they come: the acceptance records this wording. For a Terms field the field's owntextisn't the wording to show. - Send the ticked field and the token in
formData, both keyed by the field id (field_id), not by the field code:{"field": {"12": "1"}, "terms_token": {"12": "<token>"}}. - Ask for the form and send it under the same
Storeheader. A token of another store view is refused with "The terms acceptance could not be verified. Please reload the form and try again." - The token stays valid until the wording changes. After a change the submission is refused with "<field name>: the terms have been updated. Please review the new text and accept it again.": ask for the form again.
termsisnullfor other field types, andis_availableisfalsewhen the wording is missing. An answer that asks fortermsis never kept by the page cache.- When a customer edits, by
result_id, a submission that has no acceptance, they must send the ticked field and a token again, as in the customer account.
An admin or integration token can't accept for the customer. Its webformsSubmitForm on a form with a Terms field is
saved without an acceptance, as on the admin edit page: the Terms value and the token it sends aren't read, no
acceptance is recorded, and the submission reads No Acceptance Record. Such a caller gets the wording and the
token like anyone else; the token just does nothing in its own submission.
Add-on classes
The add-ons' controllers, option sources and settings modifiers take the core's context objects, and constructor
arguments they didn't use are gone. A subclass or a di.xml argument passes the new signature.
- Integration add-ons and Cart Quote. The 3.x plugins named
GetSerializableFields, which registered each add-on's serialized columns, are removed from Freshdesk, HubSpot, Klaviyo, Mailchimp, Salesforce, Zendesk, Zoho and Cart Quote. Code that referenced them usesMageMe\WebForms\Api\IntegrationDefinitionInterface(integrations, see Add-on integration contract) orMageMe\WebForms\Api\ResultSerializedColumnsInterface(Cart Quote, see Submission data). - Cart Quote.
Helper\CartQuoteProductsHelpertakes a singleHelper\CartQuoteProducts\Contextinstead of the store manager, the request and the URL builder of 1.x. A subclass that declares its own constructor takes the context and passes only it to the parent. - Product Options.
- The submissions grid columns plugin
PrepareColumnstakesproductFormIds(Model\ResourceModel\Magento\ProductFormIdReader) instead ofproductCollectionFactory. - It hands the order item's form and submission to the options block through the core holders: the plugin
RenderConfigureResultsetsMageMe\WebForms\Model\Context\CurrentFormandCurrentResultinstead of the Registry keys, andBlock\Adminhtml\Options\Logictakes the two holders instead of the Registry. Block\Adminhtml\Optionsis a template block that shows the answer fields of the submission edit form as the UI componentwebformsproductoptions_result_form, instead of a subclass of the edit form.- The files of a product option and the lines of a formatted answer are printed through templates:
Helper\OptionsHelperand the pluginPlugin\MageMe\WebForms\Model\Field\Type\AbstractOption\FormatValueForResulttakeMageMe\WebForms\Model\Field\ValueRendereras their last constructor argument. Block\FormtakesMagento\Catalog\Helper\Dataafter the core form context;Block\Options(and its Hyvä subclass) andHelper\GetProductHelpertake it in place of the Registry.- It no longer rewrites the printed
<form>of its options into a<div>. The form template does it when the form block carriesBlock\Form\Element\Form::INLINE_CONTAINER. A theme that keeps its own copy ofform/element/form.phtmlorform/multistep/form.phtmltakes over the$_inlinebranches of the module's template, or the product options form prints as a<form>inside the add-to-cart form. The same holds for a theme whose ownform/default.phtmlprints a<form>tag itself: it prints a<div>instead when$block->getFormBlock()carries the flag.
- The submissions grid columns plugin
- Product Request.
Helper\DataandBlock\ButtontakeMagento\Catalog\Helper\Datain place of the Registry. - Hyvä companion. The Gallery plugin
Plugin\MageMe\WebForms\Model\Field\Type\Gallery\GetValueHtmltakesMageMe\WebForms\Model\Field\ValueRendererlast.
What's next
- Upgrading from WebForms 3: the upgrade of the store itself.
- Extension points: what WebForms 4 lets your module build on.
- Events reference: the events WebForms 4 dispatches.