You are here

Introduction to the Drupal 8 Console

The Drupal Console is a suite of tools that you run on a command line interface (CLI) to generate boilerplate code and interact with a Drupal 8 installation. It's functionality overlaps and complements drush. However, it introduces a lot more generators and inspection tools (similar to rails).

With Drupal 8, the way we do development has changed significantly. Using the new console will significantly decrease your overall learning curve and help you do development more efficiently. Below are some simple examples of some things you can do. Check out the rather entertaining DrupalCon LA presentation for more.

Examples

Little-rMBP:drupal-8.0.0-beta12 jason_little$ drupal

Drupal Console version 0.7.15

Usage:
  command [options] [arguments]

Options:
  -h, --help             Display this help message
  -q, --quiet            Do not output any message
  -V, --version          Display this application version
      --ansi             Force ANSI output
      --no-ansi          Disable ANSI output
  -n, --no-interaction   Do not ask any interactive question
  -d, --drupal[=DRUPAL]  Path to Drupal root.
  -s, --shell            Launch the shell.
  -e, --env[=ENV]        The Environment name. [default: "prod"]
      --no-debug         Switches off debug mode.
      --learning         Generate a verbose code output.
  -v|vv|vvv, --verbose   Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  -gc, --generate-chain  Print execution options and arguments as yaml output to be used in chain command

Available commands:
  chain                             Chain command execution
  drush                             Run drush from console.
  help                              Displays help for a command
  init                              Copy configuration files to user home directory.
  list                              Lists commands
  self-update                       Update the console to latest version.
 cache
  cache:rebuild                     Rebuild and clear all site caches.
 config
  config:debug                      Show the current configuration.
  config:edit                       Edit the selected configuration.
  config:export                     Export current application configuration.
  config:override                   Override config value in active configuration.
 container
  container:debug                   Displays current services for an application.
 generate
  generate:authentication:provider  Generate an Authentication Provider
  generate:command                  Generate commands for the console.
  generate:controller               Generate & Register a controller
  generate:entity:config            Generate a new "EntityConfig"
  generate:entity:content           Generate a new "EntityContent"
  generate:form:config              Generate a new "ConfigFormBase"
  generate:module                   Generate a module.
  generate:permissions              Generate module permissions
  generate:plugin:block             Generate a plugin block
  generate:plugin:imageeffect       Generate image effect plugin.
  generate:plugin:rest:resource     Generate plugin rest resource
  generate:plugin:rulesaction       Generate a plugin rule action
  generate:service                  Generate service
  generate:theme                    Generate a theme.
 migrate
  migrate:debug                     Display current migration available for the application
  migrate:execute                   Execute a migration available for application
  migrate:load                      Generate a migration entity.
 module
  module:debug                      Display current modules available for application
  module:download                   Install module or modules in the application
  module:install                    Install module or modules in the application
  module:uninstall                  Install module or modules in the application
 password
  password:hash                     Generate a hash from a plaintext password.
  password:reset                    Reset password for a specific user.
 rest
  rest:debug                        Display current rest resource for the application
  rest:disable                      Disable a rest resource for the application
  rest:enable                       Enable a rest resource for the application
 router
  router:debug                      Displays current routes for the application
  router:rebuild                    Rebuild routes for the application
 site
  site:maintenance                  Switch site into maintenance mode
  site:mode                         Switch system performance configuration
  site:new                          Create a new Drupal project
  site:status                       View current Drupal Installation status
 test
  test:debug                        List Test Units available for the application.
 yaml
  yaml:merge                        Merge one or more YAML files in a new YAML file. Latest values are preserved.
  

Troubleshooting Routes/Paths

In the old days, troubleshooting all the paths registered in hook_menu could be a bit of a pain. Now you can easily output all the routes.

Little-rMBP:pizza jason_little$ drupal router:debug

 Route name                            Class path                                                                                                                                                            
 block.admin_add                       /admin/structure/block/add/{plugin_id}/{theme}                                           
 block.admin_demo                      /admin/structure/block/demo/{theme}                                                       
 block.admin_display                   /admin/structure/block                                                                   
 block.admin_display_theme             /admin/structure/block/list/{theme}                                                       
 block.category_autocomplete           /block-category/autocomplete                                                             
 block_content.add_form                /block/add/{block_content_type}                                                           
 block_content.add_page                /block/add                                                                               
 block_content.type_add                /admin/structure/block/block-content/types/add                                           
 comment.admin                         /admin/content/comment                                                                   
 comment.admin_approval                /admin/content/comment/approval                                                           
 comment.approve                       /comment/{comment}/approve                                                               
 comment.new_comments_node_links       /comments/render_new_comments_node_links                                                 
 comment.node_redirect                 /comment/{node}/reply
 ...
 

Making a Module

Making a module is as easy as calling generate:module. The console will then walk you through a friendly wizard.

Little-rMBP:drupal-8.0.0-beta12 jason_little$ drupal generate:module

 Welcome to the Drupal module generator 

Enter the new module name: pizza
Enter the module machine name [pizza]: 
Enter the module Path [/modules/custom]: 
Enter module description [My Awesome Module]: Configure your own pizza!
Enter package name [Other]: 
Enter Drupal Core version [8.x]: 
Do you want to generate a default Controller [no]? yes
Do you want to add a composer.json file to your module [no]? yes
Would you like to add module depencencies [yes]? no
Do you want to generate a unit test class [yes]? yes
Do you confirm generation [yes]? 

 Generated or updated files 

Site path: /Users/jason_little/dd/drupal-8.0.0-beta12
1 - modules/custom/pizza/pizza.info.yml
2 - modules/custom/pizza/pizza.module
3 - modules/custom/pizza/composer.json
4 - modules/custom/pizza/src/Controller/DefaultController.php
5 - modules/custom/pizza/pizza.routing.yml
6 - modules/custom/pizza/Tests/Controller/DefaultControllerTest.php

Add a Configuration Form

There is a handy wizard to generate your form's routes and controller classes. Note that it really doesn't like it when you put in apostrophes which it does not properly escape. I did that initially and that's probably why the screenshot below is a little goofy.

Little-rMBP:pizza jason_little$ drupal generate:form:config

Enter the module name: pizza
Enter the Form Class name [DefaultForm]: PizzaToppings
Enter the Form id [pizza_toppings]: 
Do you want to load services from the container [no]? 
Do you want to generate a form structure [yes]? 
  Input label: Name
  Input machine name [name]:     
  Type [textfield]: 
  Maximum amount of character: 30
  Width of the textfield (in characters): 30
  Description: Hawaiian, Serious Meat, Veggie Delux
  Input label: Crust   
  Input machine name [crust]: 
  Type [textfield]: radios
  Input options separated by comma: Thin,Hand Tossed
  Description:              
  Input label: Toppings
  Input machine name [toppings]:   
  Type [textfield]: checkboxes
  Input options separated by comma: pepperoni,ham,sausage,shrooms,pickles,elderberries,ghost peppers,very small rocks,broccoli,durian,pineapple,little chocolate donuts,bass
  Description: Configure your pizza toppings
  Input label: Sauce
  Input machine name [sauce]: 
  Type [textfield]: radios
  Input options separated by comma: Regular,White,BBQ,Bass-O-Matic
  Description: Do not choose Bass-O-Matic.
  Input label: 
Update routing file [yes]? yes

 Generated or updated files 

Site path: /Users/jason_little/dd/drupal-8.0.0-beta12
1 - modules/custom/pizza/src/Form/PizzaToppings.php
2 - modules/custom/pizza/pizza.routing.yml

[+] Rebuilding routes, wait a moment please
[+] Done rebuilding route(s).

Little-rMBP:pizza jason_little$ cat pizza.routing.yml

...snip...
pizza.pizza_toppings:
  path: '/admin/config/pizza/pizzatoppings'
  defaults:
    _form: '\Drupal\pizza\Form\PizzaToppings'
    _title: 'PizzaToppings'
  requirements:
    _permission: 'access administration pages'

Little-rMBP:pizza jason_little$ cat src/Form/PizzaToppings.php

config('pizza.pizzatoppings_config');
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      '#description' => $this->t('Hawaiian, Serious Meat, Veggie Delux'),
      '#maxlength' => 30,
      '#size' => 30,
      '#default_value' => $config->get('name'),
    );
    $form['crust'] = array(
      '#type' => 'radios',
      '#title' => $this->t('Crust'),
      '#description' => $this->t(''),
      '#options' => array($this->t('Thin') => $this->t('Thin'), $this->t('Hand Tossed') => $this->t('Hand Tossed')),
      '#default_value' => $config->get('crust'),
    );
    $form['toppings'] = array(
      '#type' => 'checkboxes',
      '#title' => $this->t('Toppings'),
      '#description' => $this->t('Configure your pizza\'s toppings'),
      '#options' => array($this->t('pepperoni') => $this->t('pepperoni'), $this->t('ham') => $this->t('ham'), $this->t('sausage') => $this->t('sausage'), $this->t('shrooms') => $this->t('shrooms'), $this->t('pickles') => $this->t('pickles'), $this->t('elderberries') => $this->t('elderberries'), $this->t('ghost peppers') => $this->t('ghost peppers'), $this->t('very small rocks') => $this->t('very small rocks'), $this->t('broccoli') => $this->t('broccoli'), $this->t('durian') => $this->t('durian'), $this->t('pineapple') => $this->t('pineapple'), $this->t('little chocolate donuts') => $this->t('little chocolate donuts'), $this->t('bass') => $this->t('bass')),
      '#default_value' => $config->get('toppings'),
    );
    $form['sauce'] = array(
      '#type' => 'radios',
      '#title' => $this->t('Sauce'),
      '#description' => $this->t('Don\'t choose Bass-O-Matic.'),
      '#options' => array($this->t('Regular') => $this->t('Regular'), $this->t('White') => $this->t('White'), $this->t('BBQ') => $this->t('BBQ'), $this->t('Bass-O-Matic') => $this->t('Bass-O-Matic'), $this->t('pickles') => $this->t('pickles'), $this->t('elderberries') => $this->t('elderberries'), $this->t('ghost peppers') => $this->t('ghost peppers'), $this->t('very small rocks') => $this->t('very small rocks'), $this->t('broccoli') => $this->t('broccoli'), $this->t('durian') => $this->t('durian'), $this->t('pineapple') => $this->t('pineapple'), $this->t('little chocolate donuts') => $this->t('little chocolate donuts'), $this->t('bass') => $this->t('bass')),
      '#default_value' => $config->get('sauce'),
    );

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('pizza.pizzatoppings_config')
      ->set('name', $form_state->getValue('name'))
      ->set('crust', $form_state->getValue('crust'))
      ->set('toppings', $form_state->getValue('toppings'))
      ->set('sauce', $form_state->getValue('sauce'))
      ->save();
  }

}

Trying Out

Little-rMBP:pizza jason_little$ drush en pizza

The following extensions will be enabled: pizza
Do you really want to continue? (y/n): y
pizza was enabled successfully.  

 

Categories: Engineering

About the author

Jason Little

Runs Engineering Web Services and organizes the Drupal group.