Installing Drupal with Drush, the Basics

Drush is a command-line interface that helps us to speed up administrative and development tasks for Drupal sites. After installing this Drush, we’ll be able to perform useful action simply by typing a command into a terminal —actions that would usually take multiple steps in a web browser. Drush runs on Drupal 6, 7 well as 8.

Note:  Drupal 8, works only with Drush 8.

Couple of tasks which can be done using Drush easily are :
    Download Drupal
    Download contrib modules
    Drush Install Drupal
    Update Drupal and contrib module versions
    Run updatedb
    Clear the cache
    Run cron
    Run Drupal with a lightweight webserver
    Import, export and merge configuration
    Add users and set their roles
    Add permissions to roles
    Back up and restore Drupal
    Copy your database and files to a remote server
    Compile twig templates

The first step is to open up a terminal window. Linux & macOS users should be no stranger to the command line or terminal, but if you use Windows, you might not have used this very much.

The terminal is pre-installed on Linux and MacOS, but you will probably need to install additional software to use Drush if you are using Windows. We would recommend to install “Git Bash” for this. If you haven't had it already, download and install the Git for Windows package from Google. This is the best terminal available for the Windows platform.

Once you have your terminal window open, you will need to become familiar with a few shell commands. If you are new to the command line, try
ls to list the files in the current directory,
cd to change directory, and
pwd to show which directory you are currently in (print working directory).
The command line might feel awkward at first, but as you get used to it, it will really help to speed up your tasks.

How to Install:
Drupal 8 development as it requires Drush 8. Using Composer is far and away the easiest method to install Drush.

First, install Composer globally.

$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer

Now add Composer's directory to your path by editing your .bash_profile

$ export PATH="$HOME/.composer/vendor/bin:$PATH"

Reload your terminal or just re-source the configuration you just added.

$ source ~/.bash_profile

Now that you have Composer working, you can install the latest Drush.

$ composer global require drush/drush:dev-master

Keep Drush up to date.

$ composer global update

However, it will install the latest version 8.0.3

Then you can check if the update has been successful by executing:

$ drush --version

Now, let’s begin with Drush. First, we'll use Drush to download, install and run Drupal 8:

Step 1:     To download the latest D8 branch available
               Drush dl drupal-8 --select

Drush Download D8

Select the appropriate branch for the development, as I had selected 2 and hit Enter key

To download D7 branch
drush dl drupal-7 --select

similar to d8, select branch for the development and hit Enter key.

Drush Download D7

Once we have done with branch selection we’ll get detailed information about the profile and available module on that branch.

Drupal 8 Downloaded

Step 2: Next step is to create a database. We can use the command line for login to MySQL and create the database

mysql -u root -p

Create database dbname;

Drupal 8 Database Creation

Step 3: Now we have created the database, let's install Drupal.

drush si standard --db-url=mysql://[db_user]:[db_pass]@[ip-address]/[db_name]

In this line we are passing a standard profile, name of the drupal profile to install along with MySQL username, password, and newly created database name.

Once we run the above command, we will get prompt with message

You are about to create a /var/www/html/drupal-8.0.2/sites/default/settings.php file and DROP all tables in your 'd802' database. Do you want to continue?

where d802 is a newly created database name.

Pressing  “y” will start the drupal installation with the standard profile.
Drush generate the random password and display the message -

Installation complete.  User name: admin  User password: HUoe2kei4o   [ok]                                                  
Congratulations, you installed Drupal!

Drupal 8 Successfully Downloaded with random password

Step 4: For security reasons provide 766 / 777 permission to  settings.php/files folder respectively.

chmod 755 settings.php
chmod 777 files

We completed all the steps to install Drupal using Drush. Now we can see our newly installed Drupal in browser.

Drupal 8 Home Page

 

Building Configuration Form in Drupal 8

The primary mechanism for collecting input from users is Form, without them Drupal wouldn't be so much useful. This is also one of the first things Developer should learn when they start development using Drupal. Forms are fundamental to creating Drupal modules, whether asking someone to leave a comment or Administrator has option to turn the module configuration ON/OFF.

The configuration system / state system has replaced the variable system in D8. There is no variable table and no more variable_get() / variable_set() /  variable_del() calls. Configuration is stored in the database and synced with YML files on the disk for deployment purposes.

The $config object handles CRUD (Create/Read/Update/Delete) for YML files, so you simply use ::get(), ::set(), and ::save() methods and your data will be stored in the {module}.settings.yml file.

When we defined PageExampleForm, which is our new class. extend the FormBase class; simple implementation of the FormInterface which provides an interface for a form.

Drupal 8 provides an alternate class, ConfigFormBase, which enables additional functionality at the cost of increased complexity in the method. The primary benefit of this class is, improved interaction with the configuration system.

Lets Code:

The first thing you'll need to do is create a route for your form. In our example, it looks like this:

Step 1: In your_module.info.yml file, you define the configuration route:

    configure: your_module.admin_settings
ex: xai.settings.form


Step 2: In your_module.routing.yml file, you define the route:

The only difference between this route and one that displays non-form content on a page is the _form key instead of the usual _controller key. Here _form tells Drupal the location of the class that it should use when constructing our form object.

Note: We simply specify the class name here and not the method, like SettingsForm::buildForm. Because we've defined this route as a form, Drupal will call buildForm whenever someone requests /admin/config/system/xai.

...
   your_module.admin_settings:
          path: '/admin/config/your_module'
          defaults:
      _form: '\Drupal\your_module\Form\ModuleConfigurationForm'
      _title: 'your_module configuration screen'
          requirements:
     _permission: 'administer site configuration'

Step 3: Define tform  in your_module/src/Form/ModuleConfigurationForm.php :

SettingsForm extends ConfigFormBase

Also note that we've opted to extend the Drupal\Core\Form\ConfigFormBase class which provides some additional boilerplate code for system settings forms. There is a Drupal\Core\Form\FormBase class also.

Git Hib source code for configuration page

Once you have done withSettings.php form. you can access configuration page by visiting
url: https://example.com/admin/config/xai/settings

 

Configuration page setting

Source Code: https://github.com/xaiwant/D8ConfigForm

1’st Meetup of Drupalchix in Bangalore - A Career Network for Women in Drupal

After postponing couple of times, the first Meetup of Drupalchix (Women in Drupal), in Bangalore was held on 23’ Jan 2016, and was organized by us in association with the Bangalore Drupal User group. The main aim of this innovative Meetup was to introduce Drupal as an easy to use CMS and let the participants interact and explore the various career options that Drupal has to offer. Drupalchix is a unique and active female professional network with regular meetups and events across different locations, and is intended to encourage more women to learn and work with Drupal.

The event in Bangalore was a perfect blend of fun and learning, and was also attended by 10+ Drupal developers from prominent corporate firms such as TCS, Mindtree, Valuebound amongst others from a few colleges. They gave rich insights into using Drupal and its various career options. It was designed to introduce the basics of Drupal in a well-structured and easy to understand manner, so that it gives the attendees a perfect introduction into one of the most popular, widely used and comprehensive open-source CMS (Content Management System) technologies used globally. The event was a perfect opportunity for participants from different educational and technical backgrounds to network and share their views on career prospects in Drupal.

Drupalchix

We at Valuebound are leaders in the field of Drupal consulting, and have also been using our rich domain experience in designing training programs that essentially focus on learning from a practical usage perspective, thereby adding much value and utility to the learners. The first meetup in Bangalore that was organized by us was a perfect success, and we aim to organize many such events across Bangalore so as to have maximum participation and exposure in our quest for making Drupal an excellent career choice for girls.  Our training camps and events are especially designed to share our seasoned Drupal best practices with a unique focus on real-time usage, thereby giving participants a much needed advantage in their career and networking opportunity.

We wish that our readers and participants spread the word on our training programs and the Drupalchix (Women in Drupal) community events, so that we can work towards increasing the awareness of Drupal amongst female professionals and students. Please feel free to share the word amongst your friends and colleagues and do contact us for more information.

Drupal 8 installation in Windows with XAMPP

Installation of Drupal requires a Web server. We will be employing XAMPP package for the same purpose. XAMPP is a free and open source web server solution stack. It stands for (X-cross platform), (A-Apache HTTP Server), (M-MariaDB), (P-PHP), (P-Perl).  XAMPP is hassle free and is widely used by developers all over to create a local web server.

To install XAMPP, one can download it via the below provided link
https://www.apachefriends.org/download.html

On the basis of requirement of individual system and configuration one can install the XAMPP.

XAMPP for Windows 5.5.30

To begin installation, Open/double-click .exe file

XAMPP installation

Step 1: On opening the file, a XAMPP set up wizard will initiate:

XAMPP setup wizard

Step 2: Click next, a screen will appear where you can choose the components you wish to keep, on clicking next here you will be getting default components provided by XAMPP.

XAMPP select component

Step 3: Select the location in your system where you wish to install the XAMPP.

XAMPP - choose install location

Step 4: Click on next to begin installation

Bitnami for XAMPP

Step 5: On successful completion of Installation, following screen should appear.

Completing XAMPP setup wizard

Keep the box checked (Do you want to start the Control Panel now),
Click on finish to complete the process, control panel screen will automatically launch.


XAMPP control panel

The above steps would concluded the installation of a local web server in your system, Apache and MySQL is running as we can see from the control panel. To check type 127.0.0.1/dashboard/ or localhost/dashboard/

XAMPP dashboard

Now since we have a local web server in our system, we can begin with Drupal 8 installation. We can download the latest Drupal 8 package from the below link:

Ref URL: https://www.drupal.org/news/drupal-8.0.0-released
Version: drupal 8.0.1
drupal-8.0.1.zip

Drupal 8 zip

Click on Save file.
The next step is to install drupal in the system. It includes following steps:

Step 2.1: Copy the drupal .zip file in “C:\xampp\htdocs” folder.
The path should look like this

s30

Step 2.2: Extract .zip file.
Step 2.3: On your web browser, type 127.0.0.1/drupal-8.0.1, where drupal-8.0.1 is the extracted folder name.
The step to copy and paste the default.settings.php into settings.php and similarly create a “Files” folder under sites/default and give read write execute permission for all type of user.

Following above steps will take you to the drupal installation page

Drupal installation - Choose language

One can choose the language of installation by clicking on the drop down box where default language is English.

Step 2.4: Click on next and a profile selection page is opened, Standard profile is the default profile.

Drupal installation - select installation profile

Step 2.5: Click on Save and Continue

Drupal installation - Requirements review

A requirements review page opens up that informs us about the requirements on various parameters viz web server, PHP version, library, holder permission, settings.php which are needed for the drupal to operate in our system.

Click on continue anyway which is at the bottom of the installation page

Step 2.6: To install drupal 8, we need a database which can be created by visiting URL localhost/phpmyadmin/serverdatabases.php

The above URL corresponds to phpmyadmin which functions as a data administrator for MySQL from where we can create, modify or delete databases; also execute SQL statements and manage users and permissions.

Phpmyadmin - Create databse

Any human-readable name could be given as database name, here we have provided our database name as ‘drupal8’. One can provide any similar name however it is suggested that a simple name is given. Underscores (_) may also be used.
After providing the name click on ‘create’.

Drupal installation - Database configuration

Please note that the name ‘drupal8’ given by us while creating the database becomes the name of the database name while installing drupal. The database username is root as we can see in the above screenshot, which is a default database username.
The password section is to be left blank in case there is no password assigned already.


Click on save and continue. Installation should start.

Installing Drupal

After installation, configure site page will open which will need some details from us viz site name/site email address/username/password/Country/Time zone and update notification check boxes.

Details provided by us in this case are;
Site name -MyName (one can give any site name)
Site address - myname@gmail.com
username - admin(one can provide any username they like)
Password - choose a strong password.
Country - India
Timezone - Asia/Kolkata

checkbox for updates notification are ticked default.

Database configuration page

Click on save and continue.


Drupal installation completion

A window like above will appear that will notify that the Drupal has been installed in your system.

The URL for same is localhost/drupal-8.0.1  where drupal-8.0.1 is the folder name.

 

How to pass page callback arguments in Drupal 8

In earlier blog post, we have seen how to pass arguments in views pages in Drupal 8. But not all the time we have to use views. What if we have a custom page created where we have to pass arguments to a page thru’ url. We are going to explore how to do the same in this blog post. Before we get into passing argument to a page, i would like to go through small introduction of Controller

In earlier versions of Drupal (D7), there was hook_menu. Hook menu actually managed a few different features. In addition to handling incoming requests, it provided menu links, access control, action links, and a number of other features that are all very tightly coupled together.

But in Drupal 8 By using Symfony2 Routing component, we are able to split out the route handling aspect, and get a much improved and feature-rich solution. the main reason for using Symfony2 Routing was to be able to create routes on more than just the path, for example make a request for JSON, XML or HTML while still using the same path.

If you wants to grab more info on controller please visit here [https://www.drupal.org/node/2116767]. In order to pass the page argument using url, we need to  create one new controller under modules/custom//src/Controller with name called “ControllerName.php”     

Step 1: Created controller

addition.form:
    path: '/resume/addition/{first-arg}/{second-arg}/{third-arg}'
    defaults:
      _controller: '\Drupal\\Controller\::’'
    requirements:
      _permission: 'access content'

Where,
path:
path: '/resume/addition/{first}/{second}/{third}'
path name should be any generic name with three different argument.

Controller:
_controller: '\Drupal\resume\Controller\AdditionController::add'
To accessing a specific controller use _controller path with Controller name and accessible function name. In my case AdditionController is my controller with add function.


Step 2: Now lets create another Controller AdditionController for additional functionality, where we are going to pass three different argument & performing addition for three numbers.
Once these arguments has passed on. we perform addition of three numbers & storing the output to an array.

$total[] = $first + $second + $third;

To render the output we are using theme function.

 $render_array['addition_arguments'] = array(
      // The theme function to apply to the #items
      '#theme' => 'item_list',
      // The list itself.
      '#items' => $total ,
      '#title' => $this->t('Addition of 3 values'),
    );
return $render_array;

Code Base for Controller:

namespace Drupal\resume\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for page example routes.
 */
class AdditionController extends ControllerBase {

  public function add($first, $second, $third) {

    $total[] = $first + $second + $third;

    $render_array['resume_arguments'] = array(
      // The theme function to apply to the #items
      '#theme' => 'item_list',
      // The list itself.
      '#items' => $total ,
      '#title' => $this->t('User Information'),
    );
    return $render_array;
  }
}

Once we have done with controller and routing system. we can visit the page by passing three argument and  we can see the data on renderable page. Below is the attached screenshot

Where i’m passing 20,30,40 as argument and i’m getting sum of those numbers: 90 on that page
URL: example-name/addition/20/30/40

addition page by passing 3 argument

What we have seen above is very simple demonstration of how to to pass arguments from URL to page and making use of the same to calculate some values.

Source code: https://github.com/xaiwant/D8-passing-arg-to-page

Power of Drupal Console in Drupal 8

Drupal Console is command line tools, help us to speed up the development tasks for Drupal websites. After installing console, you will be able to perform actions simply by typing commands into a terminal, actions that usually takes multiple steps in a web browser (Drupal Installation/ Field addition on Bundle), or Writing a basic code.
Just to add here, Drupal Console works with Drupal 8 only, whereas Drush runs on Drupal 8.

Below are the syntax for Console, With Drupal Console you can generate boilerplate code for modules, themes, controllers, forms, blocks, and much more.
        
        Node
              drupal create:nodes
        Controller
              drupal generate:controller
        Entity
        Form alter hook
        Module
              drupal generate:module
        Block
              drupal generate:plugin:block
        Field type, widget and formatter
        Image effect
        Rest resource
        Service
        Theme

              drupal generate:theme
        Switch maintenance mode on or off
              drupal site:maintenance on
        Run unit tests

There are few similar tools available e.g.

Module Builder: (Generates Drupal 6, 7, or 8 module scaffolding)
Drupal Module Upgrader: (Converts modules from Drupal 7 to Drupal 8; generates static help file with links to relevant change records)
Drupal 8 Tools: (Drupal code generator written in bash)
Drush: (Interact with Drupal installation via CLI, create aliases, create custom commands)

Why it’s Unique?

Drupal Console use modern PHP practices introduced into Drupal 8, includes object-oriented PHP. Console isn't a Drupal module, but was built with the Symfony Console Component and other libraries, such as Twig, to generate PHP, YAML, and other file types used in Drupal 8 module development.

It is a designed for anyone using or planning to use Drupal 8. At the moment, it is used via a CLI, but there are plans to make it accessible through the Drupal administration interface.

Drupal Console provides a number of commands for creating module temporary structure and boilerplate code. For any command, you will be asked a series of questions about what you want. In that case files are created and inside these files, classes — complete with namespacing and use statements — are created for you with the naming convention you specified in the command's prompts.


Let’s Have a look

For installation please refer here.
Once you have done with installation type drupal in terminal and you’ll get below list

s1

To pull out all the commands and option for console type drupal list & you will get list of options and available commands.

s2

As i’m going to show you how can we create boilerplate code “Generating Custom form in Module
Before we start with building a custom form we need to generate a module first

Step 1: Run drupal generate:module

s3

// Welcome to the Drupal module generator

 Enter the new module name:
 > Contact us

 Enter the module machine name [contact_us]:
 > [you can provide own machine name or else it will take default [contact_us]]

 Enter the module Path [/modules/custom]:
 > [you can provide own path or else it will take default [/modules/custom]]

 Enter module description [My Awesome Module]:
 > Creating custom contact us form with few fields

 Enter package name [Custom]:
 > [you can provide own choice or else it will take default [Custom]]

 Enter Drupal Core version [8.x]:
 > [you can provide own Core version or else it will take default [8.x]]

 Do you want to generate a .module file (yes/no) [no]:
 > [you can provide own choice or else it will take default [no]]

 Define module as feature (yes/no) [no]:
 > [you can provide own choice or else it will take default [no]]

 Do you want to add a composer.json file to your module (yes/no) [yes]:
 > [you can provide own choice or else it will take default [yes]]

 Would you like to add module dependencies (yes/no) [no]:
 > [you can provide own choice or else it will take default [no]]

 Do you confirm generation? (yes/no) [yes]:
 > [you can provide own choice or else it will take default [yes]]

Once we pressed yes we will get below files

Generated or updated files
 Site path: /var/www/html/drupal-8.0.2
     1. modules/custom/contact_us/contact_us.info.yml
     2. modules/custom/contact_us/contact_us.module
     3. modules/custom/contact_us/composer.json

s4

Finally we have done with module creation using Drupal Console. using Console we can reduce the time and energy to develop custom module or site configuration, which takes more when we go through step by step procedure in ui level.

Git Source: https://github.com/xaiwant/D8ConsoleForm/tree/master/contact_us

How to use if else statement in twig Drupal 8?

It is really exciting to work with twig in Drupal 8. Here we are going to find out how to use if else condition in twig in page.html.twig or any *.twig files. 

We are having a region called ‘banner’, which is already defined in your theme.info.yml. In the page.html.twig we need to check that if there is any content is present in the ‘banner’ region. For that, we need to use the if-else condition in our *.html.twig file. So we need to use the following code on your page.html.twig file.

{% if page.banner is empty  %}
   

Please place a block in the banner region.

{% else %}    {{ page.banner }} {% endif %}

From the above code snippet, you can understand the following points, 

How to check the if empty the region in drupal 8 twig?

   {% if page.banner is empty  %}

How to print the region in drupal 8 twig?

  {{ page.banner }}

How to use the if else condition in drupal 8 twig?

  {% if page.banner is empty  %}

Please place a block in banner region.

  {% else %}     {{ page.banner }}  {% endif %}

How to use nested if else condition in drupal 8 twig?

 {% if page.header  %}

    {{ page.banner }}

  {% elseif  page.banner %}

    {{ page.banner }}

  {% else %}

Please pace a block in either header or banner region.

  {% endif %}

 

Below is the CodeBase from page.html.twig from one of the "Bartik" Theme

s18

So we understood how to use the if else in twig drupal 8.

Related

How to Render Twig Blocks

Twig: An Introduction to theming in Drupal 8?

What is Twig?

Twig, a modern template engine for PHP, is part of the Symfony2 framework and is a direct replacement for PHPTemplate. Twig is created by SensioLabs, people who developed the Symfony2 framework itself. Drupal 8 uses Symfony2 codebase. Because Twig is natively supported by Symfony2, Twig compiles templates to optimize PHP code. Now the overhead compared to regular PHP code was reduced to the very minimum. Drupal 8 themes are much more secured,PHP calls no longer exist in theme files. This will also make theming easier to understand for non-programmers.

In Twig templating system one of the major change is, all of the theme_* functions and PHPTemplate based *.tpl.php files have been replaced in by *.html.twig template files.

In this article I’m giving you the basic introduction to Drupal 8 theme Template “Twig”. which holds basic introduction, advantage over Drupal 7 PHPTemplate, File naming convention  and basics of Twig syntax.

Drupal 7 PHPTemplate Vs Drupal 8 Twig

Let's do compare two snippets from Drupal 7 and Drupal 8.

Docblock:
PHPTemplate:

  /**
   * @file
   * File description
   */
?>

Syntax: D7

Drupal 7 Mixes up data types including strings, objects and arrays. It has many different ways to printing variables, object , array etc.

Printing a variable:
      

Printing a hash key item:
      

Assigning a variable:
       comments; ?>

Assigning an array:
        $author, '!date' => $created); ?>

Conditionals Structure:
    if  condition is TRUE
    comments): endif; ?>

    if is not empty.
    comments)): endif; ?>

    if variable is SET
    comments)): endif; ?>

    if condition is TRUE | FALSE
    0): endif; ?>

Control structures:

{% for user in users %} {% endfor %}

Filters:

Check_plain:

Translate:

Translate with substitutions:
$user->name)); ?>

There is also different way to printing variable in drupal 7 print() or print render()    

Drupal 7 node.tpl.php file:

11

Docblock:

Twig:
  {#
  /**
   * @file
   * File description
   */
  #}

Syntax: D8

In Drupal 8 uses common pattern to access all variables consistently.
In twig we don’t have to rendered your renderable. you can use
{{just print here}}

Printing a variable:
   

{{ content }}

Printing a hash key item:
   {{ item['#item'].alt }}

Assigning a variable:
   {% set custom_var = content.comments %}

Assigning an array:
   {% set args = {'!author': author, '!date': created} %}


Conditionals Structure:

   if condition is TRUE
   {% if content.comments %} {% endif %}

   if it is not empty
   {% if content.comments is not empty %} {% endif %}

   if it is not SET
   {% if content.comments is defined %} {% endif %}

   if condition is TRUE | FALSE
   {% if count > 0 %} {% endif %}


Control structures:

for each loop
Twig: {% for user in users %} {% endfor %}

Filters:

Check_plain:
          {{ title|striptags }}

Translate:
          {{ 'Home'|t }}


Translate with substitutions:
          {{ 'Welcome, @username'|t({ '@username': user.name }) }}


Drupal 8 node.html.twig

12

 

Inconsistency:

Sometimes Drupal 7 relies on template files, other times it relies on theme functions. This can make it hard to understand how to override some parts of the Drupal core. In Drupal 7 we use to create multiple template file and theme function to override the markup.

Drupal 8 only uses template files for rendering. kind of less template.

Redundancy:

Drupal 7 would have multiple files with the same lines of code, including:
Drupal 8 uses lines like this: {% extends "node.html.twig" %}. Twig integration eliminates the need for copying and pasting base or parent theme template files into your custom templates. This means you can use proper inheritance inside your theme files and eliminate a lot of duplicate code.

Security:

Drupal 7 would often prints unsanitized data. You could even run database queries from directly inside the theme files. Drupal 8 can automatically sanitize variables and won't permit unsafe functions to run.

File Naming Conventions for Drupal.

The naming convention for all theme templates has changed from *.tpl.php to *.html.twig.

HTML template

           Base template: html.html.twig
                                  location: core/modules/system/templates/html.html.twig

            Page template:
                              Pattern: page--[front|internal/path].html.twig
                              Base template: page.html.twig
                               location: core/modules/system/templates/page.html.twig

             Regions:
                             Pattern: region--[region].html.twig
                             Base template: region.html.twig
                             location: core/modules/system/templates/region.html.twig

             Blocks:
                             Pattern: block--[module|-delta]].html.twig
                             Base template: block.html.twig
                             location: core/modules/block/templates/block.html.twig

             Nodes:
                              Pattern: node--[type|nodeid]--[viewmode].html.twig
                              Base template: node.html.twig
                              location: core/modules/node/templates/node.html.twig

         
Twig templating engine will be a fresh air to themers and developers. Cleaner and more secure code will promote good practice and enable us to produce better work.

How to use Contextual Filter in Drupal 8

Contextual filters in Views are powerful, but getting them to work perfectly can be a tricky sometimes. This will hopefully save some people from the headache I had gone thru’. Contextual Filters in Drupal 8 are similar to the Drupal 7 with advance feature and more dynamic compared to normal filter. A Contextual Filter provides more convenient way to fetch the data either from variables sent programmatically or URL.

 For example: 
 A contextual filter for a node author would be able to display all nodes written by the currently logged in user.


My goal was to have a page of Articles that could be filtered  based on logged in user. In this tutorial we will use author relationship to get the name of the author and use it in a Display summary to list all the users with some additional information.

Step 1: We have to go through basic View Page creation by visiting /admin/structure/views/add

Fill up View Basic information, Page settings detail and click on Save and edit. 

I have created a view with below input.

View Basic Information
         View name: Article_by_You
         Description: listing article created by logged in User

View Settings
         Show: Content
         of Type: Article
         
Page Settings
        Page Title: Article_By_You
        Path: article_By_You

Page Display Settings
         Display format: Table

s11

Step 2: Once we have done with Step1, next we would be redirected to View Settings Page. Here I have added Body, Authored by & Authored on under Fields Section. Now click the Advanced Section on extreme right and click on CONTEXTUAL FILTERS “Add” button.

FIELDS
     Content: Body
     Content: Authored by (Authored by)
     Content: Authored on (Authored on)

s12
 

Step 3: Search For “Authored by” and click on Apply (all displays).

s13

Step 4: Select “Provide default value” under WHEN THE FILTER VALUE IS NOT IN THE URL & Select Type asUser ID from logged in user” and click on Apply (all displays).

s14

Step 5: So, we are done with view creation. It’s time to review by visiting
 the URL: example.com/d8/article-by-you

This page is showing articles created by logged in users and we don’t have to pass any additional argument. Try logging with some other user credentials and visit article-by-you page to test the view we have created just now. 

s15

Free Drupal Training by Valuebound, Bangalore on Drupal Global Training Days on Feb 6th 2016

We are happy to announce that we are running Drupal training sessions on Saturday, Feb 6th 2016 as part of the Global Training Days. The initiative is run by the Drupal Association to introduce newcomers to Drupal.

Come and join us to learn about what Drupal does and how it can help you. We will learn about Drupal and build our first website live.

What is a Drupal Global Training Day?

Drupal Global Training Days is a worldwide initiative to increase the adoption of Drupal. All across the world, people are teaching and learning Drupal, and sharing that open source love.

What is it? 

It's a full day introduction to Drupal. Attendees will leave having successfully built a Drupal site. Part of the Drupal Global Training Day initiative by the Drupal Association.

What we are going to do -

  1. Install Drupal 8 using Acquia Cloud - https://www.acquia.com/drupal-8
  2. Familiarize ourseleves with the new User Interface and options
  3. Learn about how to create content
  4. Experiment with the inbuilt views as well as image handling
  5. Create new blocks and understand about regions
  6. Manage users
  7. Q&A

Whose it for? 

  • It's for those interested in taking up Drupal as a career path.
  • Web developers/designers willing to get started with Drupal.
  • Project managers managing or considering Drupal projects.
  • Decision makers evaluating Drupal. 

Cost? It's FREE. Venue provided by Valuebound.

WHY IS THIS SESSION FREE?

Introducing Drupal among students and amateur designers free of cost is one of the many ways by which we thank this open source community.

Valuebound Interactive is solely dedicated in helping organizations and individuals to adopt Drupal in their operations in the most effective manner. At Valuebound, we believe in giving result oriented training sessions which will help you to build impeccable websites.

Limited availability to ensure personal guidance throughout the day.

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch