All of the existing examples in the form_api_example module display the form as the content of a route. However, sometimes you need to display the form elsewhere. This is done by using the form builder service and inserting the returned render array into the page wherever you want the form to display.

For example, the user login block. Or the search form block.

This adds a block to the form_api_example module that displays the Drupal\form_api_example\Form\SimpleForm in the block. Doing so demonstrates how to use the form builder service to retrieve the render array representation of a form and have it displayed.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

eojthebrave created an issue. See original summary.

Mile23’s picture

Status: Needs review » Needs work

This would be a nice addition.

  1. +++ b/form_api_example/src/Plugin/Block/SimpleFormBlock.php
    @@ -0,0 +1,72 @@
    +    return $output;
    

    Is there a way to show this form handling validation and submit? The test will need an update to verify that it works.

  2. +++ b/form_api_example/templates/description.html.twig
    @@ -28,4 +28,6 @@ Description text for the Fapi Example.
    +<p>This module also provides a block, "Example: Display a form" that demonstrates how to display a form in a block. This same technique can be used whenever you need to display a form that is not the primary content of a page.</p>
    

    Let's wrap this so it's easier to read as twig.

eojthebrave’s picture

Validation and submit both work without any additions. So, I'm not really what else there is to show in the code other than maybe adding to the comments that someone should fill out the form to see it in action. There's already a test that verifies the form displays in the block. And, I feel like adding tests for whether submitForm works might just replicate the tests already in place for the SimpleForm form.

E.g.:

  /**
   * Check routes defined by form_api_example.
   */
  public function doTestSimpleFormExample() {
    $assert = $this->assertSession();

    // Post a title.
    $edit = ['title' => 'My Custom Title'];
    $this->drupalPostForm(Url::fromRoute('form_api_example.simple_form'), $edit, 'Submit');
    $assert->pageTextContains('You specified a title of My Custom Title.');
  }

Though, if you think it's worthwhile to have independent tests for the form being submitted from the block I can write those. Thoughts?

Mile23’s picture

Status: Needs work » Needs review
FileSize
5.8 KB
3.06 KB

Minor improvements to description text, CS, converted class name string literals.

  • Mile23 committed 8711680 on 8.x-1.x authored by eojthebrave
    Issue #2945435 by Mile23, eojthebrave: Add example of displaying a form...
Mile23’s picture

Status: Needs review » Fixed

And done. Thanks!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.