0

I have a custom module that creates a form. I want to display a message to a user, but I don't want to use the normal drupal_set_message method. I want to add a div with text and images to the top of the form after submission.

A user may be submitting this form multiple times. So after submission, I want to still be on this page. It's just that after the form is submitted, a new div will appear at the top.

I don't really know how to detect that the form was submitted. It's similar to replacing the form and displaying a thank you message.

What is the best way to achieve that with Drupal 8?

1

You can request a rebuild in form submit and then add the message to the top of the form:

  public function buildForm(array $form, FormStateInterface $form_state) {

    if ($form_state->isRebuilding()) {
      $name = $form_state->getValue('name');
      $form['header'] = [
        '#type' => 'container',
        '#attributes' => ['class' => ['form-header-message', 'alert', 'alert-success']],
        'message' => [
          '#markup' => $this->t('Thank you for submitting this form, %name!', ['%name' => $name]),
        ],
      ];
    }

    $form['name'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Name'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }


  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }
  • Perfect. Thank you. And bonus for the "container" element. I wasn't aware of that one until now. – xpersonas Aug 4 '17 at 13:20
  • The only minor issue I have is that the form is rebuilt with all the previously submitted data. I would prefer if the form were a clean slate. If you have any additional insight on a Drupal form way to do that please let me know. – xpersonas Aug 4 '17 at 14:35
  • 1
    If you don't want to keep the form values then it doesn't make much sense to rebuild the form. The main reason to do this is to refine the form on each submit dependent on the input data. If you want a clean form on each submit, let the form redirect to itself as is set by default. You can still display the message inside of the form by storing it in your own session variable instead of $_SESSION['messages'] which drupal_set_message does. – 4k4 Aug 4 '17 at 14:53
  • That's true. Both responses have been valuable. I've decided to set a session variable on submit. $post_status = \Drupal::service('user.private_tempstore')->get('event_pusher'); $post_status->set('event_posted', TRUE); – xpersonas Aug 4 '17 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.