Add a Form in to a Basic Controller | Drupal 8

Add a Form in to a Basic Controller

Submitted by editor on Mon, 11/28/2016 - 11:23

How to add a form using FormBase in to a page like ControllerBase ?

NOTE: I don't know this is the best practice, anyway it's working !!!.

Here an Example To add A Exposed filter to a EntityListBuilder.

1. Create the Form using FormBase. (How to create a Form, here ID = my_test_form_id).
2. Create the basic page (or, here EntityListBuilder) (How to create a Simple Page).
3. Insert the form into the page (Tuto).
4. Handle form submit using \Drupal::request()


class MyEntityExposedFilters extends FormBase {

  public function getFormId() {
    return 'my_test_form_id';

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = array();
    $form['filters']['text'] = array(
      '#title' => $this->t('Text'),
      '#type' => 'textfield',
      '#default_value' => \Drupal::request()->get('text'),
    $form['filters']['submit_apply'] = [
      '#type' => 'submit',
      '#value' => t('Filter'),

    return $form;

  public function submitForm(array &$form, FormStateInterface $form_state) {
    //Handle Submit on MyExposedListBuilder.

class MyExposedListBuilder extends EntityListBuilder {

  public function render() {
    //Exposed form
    $form = \Drupal::formBuilder()->getForm('my_test_form_id');
    $build['form'] = $form;

    //Result table
    $build += parent::render();
    return $build;

   * Loads entity IDs using a pager sorted by the entity id.
  protected function getEntityIds() {
    $form_id = \Drupal::request()->get('form_id');
    if ($form_id && $form_id === 'my_test_form_id') {
      $query = \Drupal::entityQuery($this->entityTypeId);
      $text = \Drupal::request()->get('text');
      $query->condition('text', $text, 'CONTAINS');
      if ($this->limit) {
      $res = $query->execute();
    else {
      $res = parent::getEntityIds();
    return $res;


Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.