Tập tành Overriding the default handlers for any entity in Drupal 9 Webform
29th May 2022In Drupal 9 Entities declare handlers which takes care of different functions like Access, Storage , List building, View building, form etc.
Let’s take an example of Webform Entity. Below are the handlers declared in Webform Entity annotation.
* handlers = { * "storage" = "\Drupal\webform\WebformEntityStorage", * "view_builder" = "Drupal\webform\WebformEntityViewBuilder", * "list_builder" = "Drupal\webform\WebformEntityListBuilder", * "access" = "Drupal\webform\WebformEntityAccessControlHandler", * "form" = { * "add" = "Drupal\webform\WebformEntityAddForm", * "duplicate" = "Drupal\webform\WebformEntityAddForm", * "delete" = "Drupal\webform\WebformEntityDeleteForm", * "edit" = "Drupal\webform\WebformEntityElementsForm", * "export" = "Drupal\webform\WebformEntityExportForm", * "settings" = "Drupal\webform\EntitySettings\WebformEntitySettingsGeneralForm", * "settings_form" = "Drupal\webform\EntitySettings\WebformEntitySettingsFormForm", * "settings_submissions" = "Drupal\webform\EntitySettings\WebformEntitySettingsSubmissionsForm", * "settings_confirmation" = "Drupal\webform\EntitySettings\WebformEntitySettingsConfirmationForm", * "settings_assets" = "Drupal\webform\EntitySettings\WebformEntitySettingsAssetsForm", * "settings_access" = "Drupal\webform\EntitySettings\WebformEntitySettingsAccessForm", * "handlers" = "Drupal\webform\WebformEntityHandlersForm", * "variants" = "Drupal\webform\WebformEntityVariantsForm", * } * },
Now we want to override form handler for webform entity. We can use hook_entity_type_alter to alter the class for handler.
Create mymodule.module file add this code:
/** * @param array $entity_types */ function mymodule_entity_type_alter(array &$entity_types) { if (isset($entity_types['webform'])) { $webform_entity_type = $entity_types['webform']; $handlers = $webform_entity_type->getHandlerClasses(); $handlers['form']['settings_mymodule'] = 'Drupal\mymodule\EntitySettings\CustomFormHandler'; $webform_entity_type->setHandlerClass('form', $handlers['form']); } }
Now you can create your own Form handler at mymodule/src/EntitySettings/CustomFormHandler, You can either extend the WebformEntitySettingsBaseForm class or make what you want, in our case I extend WebformEntitySettingsBaseForm to add my own page settings .
And don't forget to add your own route like this:
entity.webform.mymodule: path: '/admin/structure/webform/manage/{webform}/settings/mymodule' defaults: _entity_form: 'webform.settings_mymodule'
Don't forget to rebuild your caches after this. To do this you can use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
Add new comment