Skip to content

Instantly share code, notes, and snippets.

@jmolivas
Last active August 5, 2019 20:01
Show Gist options
  • Select an option

  • Save jmolivas/8d8660d0318538a6817b6ef244c14c4c to your computer and use it in GitHub Desktop.

Select an option

Save jmolivas/8d8660d0318538a6817b6ef244c14c4c to your computer and use it in GitHub Desktop.
Render a form on a page via a Controller on Drupal8.

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

@RobertoCGarcia

Copy link
Copy Markdown

Good Example, just for learning, but good example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment