public function AutosaveFormBuilder::buildForm in Autosave Form 8
Builds and processes a form for a given form ID.
The form may also be retrieved from the cache if the form was built in a previous page load. The form is then passed on for processing, validation, and submission if there is proper input.
Parameters
\Drupal\Core\Form\FormInterface|string $form_arg: The value must be one of the following:
- The name of a class that implements \Drupal\Core\Form\FormInterface.
- An instance of a class that implements \Drupal\Core\Form\FormInterface.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
array The rendered form. This function may also perform a redirect and hence may not return at all depending upon the $form_state flags that were set.
Throws
\Drupal\Core\Form\FormAjaxException Thrown when a form is triggered via an AJAX submission. It will be handled by \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber.
\Drupal\Core\Form\EnforcedResponseException Thrown when a form builder returns a response directly, usually a \Symfony\Component\HttpFoundation\RedirectResponse. It will be handled by \Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber.
Overrides FormBuilder::buildForm
See also
File
- src/
Form/ AutosaveFormBuilder.php, line 96
Class
- AutosaveFormBuilder
- Provides form building and processing with AutosaveForm enabled.
Namespace
Drupal\autosave_form\FormCode
public function buildForm($form_id, FormStateInterface &$form_state) {
$form = parent::buildForm($form_id, $form_state);
if ($form_state::hasAnyErrors()) {
// Under circumstances it might happen that the form is submitted but
// returned with validation errors and the form alter hooks are executed
// thus leading to the autosave form alter code being executed as well and
// putting the autosave resume/discard message to the form, which should
// not happen if the form is being returned to the browser with validation
// errors. In order to prevent this we have to add the resume/discard
// message and options only on HTTP GET requests or on POST requests if
// restore or reject submit operations have been performed or in a more
// complex case if the message has not been yet confirmed but other
// AJAX / POST requests are being triggered in the background. As we could
// not detect the last case we still put the form elements into the form,
// but on the client side we will not show the message if the form is
// returned with validation errors.
$form['#attached']['drupalSettings']['autosaveForm']['formHasErrors'] = TRUE;
// Additionally unset the form elements and settings which might have been
// added, but aren't actually needed.
unset($form['#attached']['drupalSettings']['autosaveForm']['message']);
unset($form[AutosaveFormInterface::AUTOSAVE_RESTORE_ELEMENT_NAME]);
unset($form[AutosaveFormInterface::AUTOSAVE_REJECT_ELEMENT_NAME]);
unset($form['autosave_restore_discard']);
}
return $form;
}