Form in controller does not render as usual In Drupal 8.4.3, I tried to render a form inside a controller's method, but it does not render as usual.


The value of #default_value is not taken into account
Fields have no name attribute (which causes them not to be sent)


This is the smallest code I've been able to write to reproduce the issue.

public function list() 
{
  $render = array(
    '#type' =&gt; 'form',
    'search' =&gt; array(
      '#type' =&gt; 'textfield',
      '#title' =&gt; 'Search',
      '#default_value' =&gt; 'Lorem ipsum'
    ),
    'actions' =&gt; array(
      '#type' =&gt; 'actions',
      'submit' =&gt; array(
        '#type' =&gt; 'submit',
        '#value' =&gt; 'Apply'
      )
    )
  );

  return $render;
}


The rendered markup is the following.

&lt;form method="post" accept-charset="UTF-8"&gt;
  &lt;div class="js-form-item form-item js-form-type-textfield form-type-textfield js-form-item- form-item-"&gt;
    &lt;label&gt;Search&lt;/label&gt;
    &lt;!-- No name attribute, nor a value --&gt;
    &lt;input type="text" size="60" maxlength="128" class="form-text"&gt;
  &lt;/div&gt;
  &lt;input type="submit" name="op" value="Apply" class="button js-form-submit form-submit"&gt;
&lt;/form&gt;


The sent data is the following. Obviously, the search field is not sent as it does not have a name.

op=Apply


I can overcome the missing name attribute with a #name key, but I cannot understand why it is needed here, but no where else.  

This is the most basic route/controller pattern.  

What could interfere in my context?
It's not possible to use form elements in a controller directly, only render elements. You find a complete list of both types here: https://api.drupal.org/api/drupal/elements/8.4.x

To use form elements in a page controller you need a form route:

example.routing.yml:

example.form:
  path: '/example-form'
  defaults:
    _title: 'Example form'
    _form: '\Drupal\example\Form\ExampleForm'
  requirements:
    _permission: 'access content'


And then build the class ExampleForm by extending FormBase. See https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api

This is the most basic route-controller pattern for forms.