Create file at ~/console/chain/generate-controller-form-render.yml
containing:
command:
name: 'generate:controller:form:render'
description: 'Controller + Form generator'
commands:
- command: 'generate:module'
options:
module: example
machine-name: example
module-path: /modules/custom
description: 'My Awesome Module'
core: 8.x
package: Custom
module-file: true
- command: 'generate:form'
options:
module: example
class: DefaultForm
form-id: default_form
inputs:
-
name: full_name
type: textfield
label: 'Full Name'
options: ''
description: ''
maxlength: '64'
size: '64'
default_value: ''
weight: '0'
fieldset: ''
path: /example/form/default
- command: 'generate:controller'
options:
module: example
class: DefaultController
routes:
-
title: 'Render form'
name: example.default_controller_renderForm
method: renderForm
path: /example/form
services:
- form_builder
cd to path/to/drupal/site
Execute new custom chain command to generate code
drupal generate:controller:form:render
Install new gereated module
drupal module:install example
Open controller class generate:controller:form:render
and update build method with
public function renderForm() {
$form = $this->formBuilder->getForm('Drupal\example\Form\DefaultForm');
return [
'#type' => 'markup',
'#markup' => $form
];
}
Rebuild cache
drupal cr all
Open your browser an load URL /example/form
NOTE: You must install DrupalConsole
public function renderForm() is problematic for several reasons.
First, why use a _controller if all it does is print a form? Instead it should have
_form: Drupal\example\Form\DefaultForm
in the routing definition.Second, if you do need to return a form from a controller (uncommon but useful), you don't need to call render() on it.
You can return the form array directly, or nest it within a render array.