abstract class WebformHandlerFormBase in Webform 6.x
Same name and namespace in other branches
- 8.5 src/Form/WebformHandlerFormBase.php \Drupal\webform\Form\WebformHandlerFormBase
Provides a base webform for webform handlers.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, RedirectDestinationTrait, StringTranslationTrait
- class \Drupal\webform\Form\WebformHandlerFormBase uses WebformDialogFormTrait
Expanded class hierarchy of WebformHandlerFormBase
File
- src/
Form/ WebformHandlerFormBase.php, line 19
Namespace
Drupal\webform\FormView source
abstract class WebformHandlerFormBase extends FormBase {
use WebformDialogFormTrait;
/**
* Machine name maxlength.
*/
const MACHINE_NAME_MAXLENGTH = 64;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The transliteration helper.
*
* @var \Drupal\Component\Transliteration\TransliterationInterface
*/
protected $transliteration;
/**
* The token manager.
*
* @var \Drupal\webform\WebformTokenManagerInterface
*/
protected $tokenManager;
/**
* The webform.
*
* @var \Drupal\webform\WebformInterface
*/
protected $webform;
/**
* The webform handler.
*
* @var \Drupal\webform\Plugin\WebformHandlerInterface
*/
protected $webformHandler;
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'webform_handler_form';
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->languageManager = $container
->get('language_manager');
$instance->transliteration = $container
->get('transliteration');
$instance->tokenManager = $container
->get('webform.token_manager');
return $instance;
}
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param \Drupal\webform\WebformInterface $webform
* The webform.
* @param string $webform_handler
* The webform handler ID.
*
* @return array
* The form structure.
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* Throws not found exception if the number of handler instances for this
* webform exceeds the handler's cardinality.
*/
public function buildForm(array $form, FormStateInterface $form_state, WebformInterface $webform = NULL, $webform_handler = NULL) {
$this->webform = $webform;
try {
$this->webformHandler = $this
->prepareWebformHandler($webform_handler);
} catch (PluginNotFoundException $e) {
throw new NotFoundHttpException("Invalid handler id: '{$webform_handler}'.");
}
// Limit the number of plugin instanced allowed.
if (!$this->webformHandler
->getHandlerId()) {
$plugin_id = $this->webformHandler
->getPluginId();
$cardinality = $this->webformHandler
->cardinality();
$number_of_instances = $webform
->getHandlers($plugin_id)
->count();
if ($cardinality !== WebformHandlerInterface::CARDINALITY_UNLIMITED && $cardinality <= $number_of_instances) {
throw new NotFoundHttpException($this
->formatPlural($cardinality, 'Only @count instance is permitted', 'Only @count instances are permitted'));
}
}
// Add meta data to webform handler form.
// This information makes it a little easier to alter a handler's form.
$form['#webform_id'] = $this->webform
->id();
$form['#webform_handler_id'] = $this->webformHandler
->getHandlerId();
$form['#webform_handler_plugin_id'] = $this->webformHandler
->getPluginId();
$request = $this
->getRequest();
$form['description'] = [
'#type' => 'container',
'text' => [
'#markup' => $this->webformHandler
->description(),
'#prefix' => '<p>',
'#suffix' => '</p>',
],
'#weight' => -20,
];
$form['id'] = [
'#type' => 'value',
'#value' => $this->webformHandler
->getPluginId(),
];
$form['general'] = [
'#type' => 'fieldset',
'#title' => $this
->t('General settings'),
'#weight' => -10,
];
$form['general']['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Title'),
'#maxlength' => 255,
'#default_value' => $this->webformHandler
->label(),
'#required' => TRUE,
'#attributes' => [
'autofocus' => 'autofocus',
],
];
$form['general']['handler_id'] = [
'#type' => 'machine_name',
'#maxlength' => static::MACHINE_NAME_MAXLENGTH,
'#description' => $this
->t('A unique name for this handler instance. Must be alpha-numeric and underscore separated.'),
'#default_value' => $this->webformHandler
->getHandlerId() ?: NULL,
'#required' => TRUE,
'#disabled' => $this->webformHandler
->getHandlerId() ? TRUE : FALSE,
'#machine_name' => [
'source' => [
'general',
'label',
],
'exists' => [
$this,
'exists',
],
],
'#element_validate' => [
[
$this,
'validateMachineName',
],
[
MachineName::class,
'validateMachineName',
],
],
];
$form['general']['notes'] = [
'#type' => 'textarea',
'#title' => $this
->t('Administrative notes'),
'#description' => $this
->t("Entered text will be displayed on the handlers administrative page and replace this handler's default description."),
'#rows' => 2,
'#default_value' => $this->webformHandler
->getNotes(),
];
$form['advanced'] = [
'#type' => 'fieldset',
'#title' => $this
->t('Advanced settings'),
'#weight' => -10,
];
$form['advanced']['status'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Enable the %name handler.', [
'%name' => $this->webformHandler
->label(),
]),
'#return_value' => TRUE,
'#default_value' => $this->webformHandler
->isEnabled(),
// Disable broken plugins.
'#disabled' => $this->webformHandler
->getPluginId() === 'broken',
];
$form['#parents'] = [];
$form['settings'] = [
'#tree' => TRUE,
'#parents' => [
'settings',
],
];
$subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
$form['settings'] = $this->webformHandler
->buildConfigurationForm($form['settings'], $subform_state);
// Get $form['settings']['#attributes']['novalidate'] and apply it to the
// $form.
// This allows handlers with hide/show logic to skip HTML5 validation.
// @see http://stackoverflow.com/questions/22148080/an-invalid-form-control-with-name-is-not-focusable
if (isset($form['settings']['#attributes']['novalidate'])) {
$form['#attributes']['novalidate'] = 'novalidate';
}
$form['settings']['#tree'] = TRUE;
// Conditional logic.
if ($this->webformHandler
->supportsConditions()) {
$form['conditional_logic'] = [
'#type' => 'fieldset',
'#title' => $this
->t('Conditional logic'),
];
$form['conditional_logic']['conditions'] = [
'#type' => 'webform_element_states',
'#state_options' => [
'enabled' => $this
->t('Enabled'),
'disabled' => $this
->t('Disabled'),
],
'#selector_options' => $webform
->getElementsSelectorOptions([
'excluded_elements' => [],
]),
'#selector_sources' => $webform
->getElementsSelectorSourceValues(),
'#multiple' => FALSE,
'#default_value' => $this->webformHandler
->getConditions(),
];
}
// Check the URL for a weight, then the webform handler,
// otherwise use default.
$form['weight'] = [
'#type' => 'hidden',
'#value' => $request->query
->has('weight') ? (int) $request->query
->get('weight') : $this->webformHandler
->getWeight(),
];
// Build tabs.
$tabs = [
'conditions' => [
'title' => $this
->t('Conditions'),
'elements' => [
'conditional_logic',
],
'weight' => 10,
],
'advanced' => [
'title' => $this
->t('Advanced'),
'elements' => [
'advanced',
'additional',
'development',
],
'weight' => 20,
],
];
$form = WebformFormHelper::buildTabs($form, $tabs);
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Save'),
'#button_type' => 'primary',
];
// Add token links below the form and on every tab.
$form['token_tree_link'] = $this->tokenManager
->buildTreeElement();
if ($form['token_tree_link']) {
$form['token_tree_link'] += [
'#weight' => 101,
];
}
return $this
->buildDialogForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// The webform handler configuration is stored in the 'settings' key in
// the webform, pass that through for validation.
$subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
$this->webformHandler
->validateConfigurationForm($form, $subform_state);
// Process handler state webform errors.
$this
->processHandlerFormErrors($subform_state, $form_state);
// Update the original webform values.
$form_state
->setValue('settings', $subform_state
->getValues());
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state
->cleanValues();
// The webform handler configuration is stored in the 'settings' key in
// the webform, pass that through for submission.
$subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
$this->webformHandler
->submitConfigurationForm($form, $subform_state);
// Update the original webform values.
$form_state
->setValue('settings', $subform_state
->getValues());
$this->webformHandler
->setHandlerId($form_state
->getValue('handler_id'));
$this->webformHandler
->setLabel($form_state
->getValue('label'));
$this->webformHandler
->setNotes($form_state
->getValue('notes'));
$this->webformHandler
->setStatus($form_state
->getValue('status'));
$this->webformHandler
->setWeight($form_state
->getValue('weight'));
// Clear conditions if conditions or handler is disabled.
if (!$this->webformHandler
->supportsConditions() || $this->webformHandler
->isDisabled()) {
$this->webformHandler
->setConditions([]);
}
else {
$this->webformHandler
->setConditions($form_state
->getValue('conditions'));
}
if ($this instanceof WebformHandlerAddForm) {
$this->webform
->addWebformHandler($this->webformHandler);
$this
->messenger()
->addStatus($this
->t('The webform handler was successfully added.'));
}
else {
$this->webform
->updateWebformHandler($this->webformHandler);
$this
->messenger()
->addStatus($this
->t('The webform handler was successfully updated.'));
}
$form_state
->setRedirectUrl($this->webform
->toUrl('handlers', [
'query' => [
'update' => $this->webformHandler
->getHandlerId(),
],
]));
}
/**
* Validates the machine name for a webform handler instance.
*
* This method verifies the uniqueness of the machine name and updates the
* machine name with a count suffix if another handler with the same machine
* name already exists.
*
* @see \Drupal\Core\Render\Element\MachineName::validateMachineName()
*/
public function validateMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
// If the machine name matches the default machine name, it does not need to
// be validated (i.e. during handler edit form save).
if (isset($element['#default_value']) && $element['#default_value'] === $element['#value']) {
return;
}
$count = 1;
$machine_name = $element['#value'];
$instance_ids = $this->webform
->getHandlers()
->getInstanceIds();
while (isset($instance_ids[$machine_name])) {
$machine_name = $element['#value'] . '_' . $count++;
}
$element['#value'] = $machine_name;
$form_state
->setValueForElement($element, $machine_name);
}
/**
* Determines if the webform handler ID already exists.
*
* @param string $handler_id
* The webform handler ID.
*
* @return bool
* TRUE if the webform handler ID exists, FALSE otherwise.
*/
public function exists($handler_id) {
$instance_ids = $this->webform
->getHandlers()
->getInstanceIds();
return isset($instance_ids[$handler_id]) ? TRUE : FALSE;
}
/**
* Get the webform handler's webform.
*
* @return \Drupal\webform\WebformInterface
* A webform.
*/
public function getWebform() {
return $this->webform;
}
/**
* Get the webform handler.
*
* @return \Drupal\webform\Plugin\WebformHandlerInterface
* A webform handler.
*/
public function getWebformHandler() {
return $this->webformHandler;
}
/**
* Process handler webform errors in webform.
*
* @param \Drupal\Core\Form\FormStateInterface $handler_state
* The webform handler webform state.
* @param \Drupal\Core\Form\FormStateInterface &$form_state
* The webform state.
*/
protected function processHandlerFormErrors(FormStateInterface $handler_state, FormStateInterface &$form_state) {
foreach ($handler_state
->getErrors() as $name => $message) {
$form_state
->setErrorByName($name, $message);
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 3 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 3 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function | Returns a redirect response object for the specified route. | |
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
WebformAjaxFormTrait:: |
protected | function | Queue announcement with Ajax response. | |
WebformAjaxFormTrait:: |
protected | function | Add Ajax support to a form. | |
WebformAjaxFormTrait:: |
protected | function | Create an AjaxResponse or WebformAjaxResponse object. | |
WebformAjaxFormTrait:: |
protected | function | Get announcements. | |
WebformAjaxFormTrait:: |
protected | function | Get default ajax callback settings. | 1 |
WebformAjaxFormTrait:: |
protected | function | Get redirect URL from the form's state. | |
WebformAjaxFormTrait:: |
protected | function | Get the form's Ajax wrapper id. | 1 |
WebformAjaxFormTrait:: |
protected | function | Determine if Ajax callback is callable. | |
WebformAjaxFormTrait:: |
protected | function | Is the current request for an Ajax modal/dialog. | |
WebformAjaxFormTrait:: |
protected | function | Is the current request for an off canvas dialog. | |
WebformAjaxFormTrait:: |
protected | function | Handle missing Ajax callback. | |
WebformAjaxFormTrait:: |
protected | function | Replace form via an Ajax response. | 1 |
WebformAjaxFormTrait:: |
protected | function | Reset announcements. | |
WebformAjaxFormTrait:: |
protected | function | Set announcements. | |
WebformAjaxFormTrait:: |
public | function | Submit form #ajax callback. | 1 |
WebformAjaxFormTrait:: |
public | function | Validate form #ajax callback. | 1 |
WebformDialogFormTrait:: |
protected | function | Add modal dialog support to a confirm form. | |
WebformDialogFormTrait:: |
protected | function | Build webform dialog delete link. | |
WebformDialogFormTrait:: |
protected | function | Add modal dialog support to a form. | |
WebformDialogFormTrait:: |
public | function |
Cancel form #ajax callback. Overrides WebformAjaxFormTrait:: |
1 |
WebformDialogFormTrait:: |
public | function | Close dialog. | |
WebformDialogFormTrait:: |
protected | function |
Returns if webform is using Ajax. Overrides WebformAjaxFormTrait:: |
1 |
WebformDialogFormTrait:: |
public | function |
Empty submit callback used to only have the submit button to use an #ajax submit callback. Overrides WebformAjaxFormTrait:: |
|
WebformDialogFormTrait:: |
public | function | Validate callback to clear validation errors. | 2 |
WebformHandlerFormBase:: |
protected | property | The language manager. | |
WebformHandlerFormBase:: |
protected | property | The token manager. | |
WebformHandlerFormBase:: |
protected | property | The transliteration helper. | |
WebformHandlerFormBase:: |
protected | property | The webform. | |
WebformHandlerFormBase:: |
protected | property | The webform handler. | |
WebformHandlerFormBase:: |
public | function |
Form constructor. Overrides FormInterface:: |
2 |
WebformHandlerFormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
1 |
WebformHandlerFormBase:: |
public | function | Determines if the webform handler ID already exists. | |
WebformHandlerFormBase:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
WebformHandlerFormBase:: |
public | function | Get the webform handler's webform. | |
WebformHandlerFormBase:: |
public | function | Get the webform handler. | |
WebformHandlerFormBase:: |
constant | Machine name maxlength. | ||
WebformHandlerFormBase:: |
protected | function | Process handler webform errors in webform. | |
WebformHandlerFormBase:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
WebformHandlerFormBase:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
WebformHandlerFormBase:: |
public | function | Validates the machine name for a webform handler instance. |