improvements-2.x-dev/modules/improvements_form/improvements_form.tracking_submit.inc
modules/improvements_form/improvements_form.tracking_submit.inc
<?php use Drupal\contact\MessageForm; use Drupal\Core\Ajax\SettingsCommand; use Drupal\Core\Form\FormStateInterface; /** * @see improvements_form_form_alter() */ function improvements_form_tracking_submit_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void { // Add tracking form submit if (!empty($form['#tracking_submit'])) { $form_object = $form_state->getFormObject(); // For contact message form if ($form_object instanceof MessageForm && isset($form['actions']['submit'])) { $form['actions']['submit']['#submit'][] = 'improvements_form_tracking_submit'; } // For other forms else { $form['#submit'][] = 'improvements_form_tracking_submit'; } } } /** * Tracking forms submit callback. * * @see improvements_form_tracking_submit_form_alter() */ function improvements_form_tracking_submit(array $form, FormStateInterface $form_state): void { $session = \Drupal::request()->getSession(); $submitted_forms = $session->get('submitted_forms', []); $form_id = $form_state->getFormObject()->getFormId(); if (!in_array($form_id, $submitted_forms)) { $submitted_forms[] = $form_id; } $session->set('submitted_forms', $submitted_forms); } /** * Return submitted forms from session and clear session. */ function improvements_form_get_submitted_forms(): array { if ($session = \Drupal::request()->getSession()) { $submitted_forms = $session->get('submitted_forms', []); if ($submitted_forms) { $session->remove('submitted_forms'); } return $submitted_forms; } return []; } /** * Implements hook_page_attachments(). */ function improvements_form_page_attachments(array &$page): void { // Add to js info about submitted forms. // @TODO Add support page cache if ($submitted_forms = improvements_form_get_submitted_forms()) { $page['#attached']['drupalSettings']['submittedForms'] = $submitted_forms; $page['#attached']['library'][] = 'core/drupalSettings'; } } /** * Implements hook_ajax_render_alter(). */ function improvements_form_ajax_render_alter(array &$data): void { // Add submitted forms ids to drupalSettings if ($submitted_forms = improvements_form_get_submitted_forms()) { $command = new SettingsCommand(['submittedForms' => $submitted_forms]); $data[] = $command->render(); } }