Skip to content

Instantly share code, notes, and snippets.

@msankhala
Forked from jmolivas/README.md
Created February 23, 2018 17:49
Show Gist options
  • Save msankhala/325d6e33c17a8aa2631875fbf9829d07 to your computer and use it in GitHub Desktop.
Save msankhala/325d6e33c17a8aa2631875fbf9829d07 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

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