Wednesday 16 September 2015

Drupal 8 - How building modules is different now

Drupal 8 is in alpha now, so its a good time to dip your feet in it and notice the major differences Drupal 8 introduced after adopting some Symfony low-level components such as HttpKernel, Routing, EventDispatcher, DependencyInjection, and ClassLoader, for a higher level changes see Hector Iribarne’s presentation on Drupal 8 changes.
In this blog post I will try to build a D8 module and walk through the basic steps.
In this example series we will develop a module and build on it during the coming blog posts.
Lets start.
In brief, our module is basically is a greeting box, visitors come to the site and leave you their greetings and comments, you as an admin can look at these greetings and delete the ones that you do not like. So the basic required architecture is: - A table in the database to hold the greetings. (Model or schema API) - Menu callbacks (Routes) - Controllers to handle the logic.
A good point to note here is that custom and contributed modules/themes now live inside /themes or /modules in the root folder, but still you can place them inside sites/all/modules or sites/all/modules themes.
Like any module in Drupal 7, modules in Drupal 8 need a .info file but this time in a YML format, so we create our hello.info.yml inside our hello directory that we create.
name: Hello
type: module
description: "Hello Drupal 8"
version: 1.x
package: Custom
core: 8.x
Alright, the form is ready to work.
Now lets create the admin page that will display the greetings. First we need to define our route in hello.routing.yml
name_list:
  path: 'list/names'
  defaults:
    _content: '\Drupal\hello\Controller\ListNames::content'
    _title: 'People'
  requirements:
    _permission: 'administer greetings'
The route needs a controller to handle it, so in the controllers directory we create the file ListNames.php and we define content() method 
namespace Drupal\hello\Controller;

class ListNames {
  public function content() {
    $people = HelloStorage::getAll();
    $output = l('+ Add name', 'add/name');
    $output .= '<table><tr><td>Name</td><td>Delete</td></tr>';
    foreach ($people as $person) {
      $output .= '<tr><td>' . $person . '</td><td><a href="delete/' . $person . '">Delete</a></td></tr>';
    }
    $output .= '</table>';
    return $output;
  } 
}

No comments:

Post a Comment