0

I created a Class form, then I can access to the page form and submit it. My form use the default template of my website.

When I submitted the form, I want redirect the user to the form page (the same page) and display some elements in front of page. Theses elements depends on the results of the form has been submitted.

I can easily do that with simples drupal messages, but instead, I would like to show more complex messages.

I think I can create a little template file and include it in my form. But I haven't any ideas how can I do that in Drupal 8, can you provide me a very simple example or tell me how I can include a sub-template in my form ?

I think my sub-template looks something like this (Pseudocode, not twig :) ) :

// the form return an array
    foreach formarray as element
        <h1>element1<h1>
        <p>property1 : {element[property1}</p>
        <p>property2 : {element[property2}</p>
        ...
    end foreach
// I include this template in the form, if the formarray is empty, nothing is displayed (when the user load the forme the first time)

Thanks for help !

1 Answer 1

3

Most likely you are looking at adding to the "render array" of the page (or form). A render array can refer to a "type" or Render Element, and that type can render into a template.

The scenario of rendering after form submission on the same form can be done within the Form itself by setting the form state to rebuild.

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

    // Set the rebuild state to TRUE to persist $form_state when the form is reloaded.
    $form_state->setRebuild();
    $form_state->set('display_extra', TRUE);
  }

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

    // Conditionally display something from form state.
    if ($form_state->has('display_extra') && $form_state->get('display_extra')) {
      // Structure the render array here including setting up a custom RenderElement ('#type'), which has a custom template defined in hook_theme().
      $form['display_something'] = [];

    }

    // Rest of form...

    return $form;
  }
2
  • Thank you =) Your "template" link refer to a "Drupal 7" doc, is it normal ? If not, how can I get form template name suggestion with my form and can I 'set' the name of the template used by my form ? Commented Sep 23, 2016 at 15:31
  • Thank you for the feedback! I fixed the link so that it should go to drupal.org/docs/8/theming instead. I forgot that clicking on the Theming Drupal link still goes to Drupal 7. Sorry.
    – mradcliffe
    Commented Sep 23, 2016 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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