How to use REST Export with Views in Drupal 8

Why we need Web Services? 

We have an online shop showing product catalog and info. & we want to make Mobile app which can interact with website with CRUD functionality.
In that case we need is to extend Drupal to receive and send data in machine readable format so it would be easier for the Application developer to make the app. So we need to make Drupal support a Web Services.

How does it works?

In the website, we have a content type (example:“article”) with other info. We need the app to use our website using simple requests, which can be made using RESTful Web API. REST uses the HTTP methods for communication between 2 devices in machine-readable format (JSON / XML) and is widely used in the WWW.
I’m assuming you are familiar with Contributed Services & Services view module in Drupal 7. In this article i‘m going to show you How can we create Rest Export view in Drupal 8 with few simple step and this won’t require any contributed module unlike drupal 7.

s40

Drupal 8 Provides core RESTful Web Services & Serialization in one single package called WEB SERVICES & also Views (help us to create Rest Export View).

Here's a 5-step guide to using REST Export Services with Views.

Scenario: To create a REST Export View for Article Content with some additional fields.
and it should display node by passing node id.

Step 1: Enable RESTful Web Services & Serialization. once enabled the module you will get REST EXPORT SETTINGS option in Views creation page.

s41

Step 2: Fill up View Detail as provided below View name as ArticleByID with some Description. selected Article as the content type. Tick the box against "Provide a REST export" under "REST export settings". & provide a link under "REST export path". This link is the End point to fetch the data. Here, we are giving path "/json/article-by-id" click save and edit.

s42

Step 3: Once we landed to View Configuration page Click "Settings" next to "Format:Serializer". You will get the option to choose the format of output data ( json / xml ) at the given End point  "json/article-by-id". as i have selected json format.

s43

Step 4: Added Title/ Body/ Image under FIELDS section. Selected Article Content type under FILTER CRITERIA. and also added exposed Node id to filter based  on specific NID and saved the setting.

s44

Step 5: To view the formatted data we can test using any REST client. for google chrome. i have downloaded a plugin “JSONView”
ref url: https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?utm_source=chrome-app-launcher-info-dialog

Once we have done with installation of JSONView. we can visit the end point and view the output as below
End point: example-name/drupal-8.0.1/json/article-by-id?nid=5

Where nid is filter name with node ID

s45

 

Drupal 8 : How to create the local tasks[tabs] through custom module

Sometimes we need to add forms in a page which can be accessed using horizontal tabs. Default Drupal login forms already has few tabs e.g. Log in, Create new account & Reset new password. Either we can add additional tab here itself or we can also add tab if we need to show multiple form in a page using writing a small custom module.

What is module-defined local tasks?
Tabs on top of the page are called as Local task. you can view them easily on User Log-in page having Log in/ Create an account/ Reset your password

s1

Syntax to define local task in Drupal 8:

First of all, To create a static local tasks we need to define in our module should be static.

 

format: file name after your module.

E.g: if module name is "resume", the file will be resume.links.task.yml & placed in the root directory.

Here resume.links.task.yml define two tabs resume.tab_1 & resume.tab_2 route. the title of the tab will be shown in User Interface tab where base_route is same as the name of the route. we can also provide the weight for the tabs. by default negative weight appears on the left hand side.

Just to Display two quick tab in UI , i have added one additional form “Work Form”


s2

s3

To provide multiple levels of tabs, use the parent_id to relate a tab to its parent and use the same base_route to group the set of tabs together. Above are two quick tab “resume” , ”Work” which can visible while visiting resume/mypage

Conclusion: This tutorial tell us about basics of creating static local tasks[tabs]. by adding resume.links.task.yml in core directory. which required  mandatory route_name / title / base_route fields. & it doesn’t include Dynamic local task generation & Customising local task behaviour.

Source code:  https://github.com/xaiwant/D8custom-form-with-static-local-task

Creating a custom form in a block in two steps in Drupal 8

Lot of times we come across project requirement where standards form created using contact form or webform is not sufficient or overkill. In this article I am sharing the flexibility of Drupal 8 where I am creating a basic form and rendering the same form into a block

Step 1: Lets create a custom form - Add a file in resume/src/Form/WorkForm.php

Step 2: Now lets display the form we created in step 1 as block. For this create a new file  article/Plugin/Block/ArticleBlock.php

FormBuilder::getForm($form_arg)

This function should be used instead of self::buildForm() when $form_state is not needed (i.e., when initially rendering the form) and is often used as a menu callback.

Now you can check your page output “Article Block” is displayed in right side on the website.

s5

Source code: https://github.com/xaiwant/D8custom-form-rendring-in-block

Step by step method to create a custom form in Drupal 8

In Drupal 8 form API is similar to Drupal 7 Form API. forms still use array structure to render the data. but having separate validation and submission form. Drupal 8 has some new (HTML 5) elements available.    

New HTML 5 elements like

'tel','email','number','date','url','search','range' etc.

In Drupal 8 Form classes implement the\Drupal\Core\Form\FormBuilderInterface and the basic workflow of a form is defined by the buildForm, validateForm, and submitForm methods of the interface.

There are different classes to choose from depending on the type of form you are creating.

 

  • ConfigFormBase : For creating system configuration forms like the one found at admin/config/system/site-information.

  • ConfirmFormBase : For providing users with a form to confirm an action such as deleting a piece of content.

  • FormBase : The most generic base class for generating forms.

FIle structure:

s18
 

Step 1: Create .info.yml file

An essential part of a Drupal 8 module, theme, or install profile is the .info.yml file (aka, "info yaml file") to store metadata about the project.

In Drupal 8, .info file changes to .info.yml. Old .info files have been converted to YAML.

Added name, description, core, package, dependencies, type (The type key, which is new in Drupal 8, is required and indicates the type of extension, e.g. module, theme or profile.

Step 2: Creating .routing.yml

This routing system replaces the routing parts of hook_menu() in Drupal 7. The parts of hook_menu() that were used for creating menu entries, tabs.

A route is a path which returns some sort of content on.

For example, the default front page, '/node/2' is a route. When Drupal receives a request, it tries to match the requested path to a route it knows about. If the route is found, then the route's definition is used to return content. Otherwise, Drupal returns a 404.

In above code:

s31


1. {name} element in the URL is a path parameter and is available as $name in the controller method. e.g: resume.form

2. {path name} is url to access the page. e.g; /resume/my-form

3.  The {title} is title of the page. e.g: Application Form

4.  {module-name} is the name of our module. e.g: resume

Step 3: ResumeForm in the Drupal\resume\Form namespace, which implements the FormInterface and is defined in the file: modules/resume/src/Form/ResumeForm.php

In modules/resume/src/Form/ResumeForm.php. First we declare the namespace, the other classes we want to use, and extend the FormBase class. Some code:  

 s24 

Next we use to get code from some other classes, using the use PHP keyword and then the namespace, using the PSR-4 standard, which will autoload the classes in the files that correspond to these namespaces

s25

Now that we've our namespace, we'd like to use, we can declare our own class, ResumeForm extends the class FormBase, FormBase is the class we brought in as a dependency with this line: use Drupal\Core\Form\FormBase;

Form Creation: Which returns a Form API array that defines each of the elements your form is composed of.

Validation: After a user fills out the form and clicks the submit button it's common to want to perform some sort of validation on the data that's being collected. To do this with Drupal Form API we simply implement the validate form method from

\Drupal\Core\Form\FormBuilderInterface in our ResumeForm class.

Submission: Finally, we build the submit method. According to the FormInterface, we use: public function submitForm(array &$form, FormStateInterface $form_state).

Step 4: we are done with our drupal 8 Custom form. we can review the page by typing
d8/resume/myform

s21

Fill up all the required field and and click on save button.

s22

once you click on save button, you’ll get saved value info. as we are displaying this in the form.

s23

As per our Submit form source code it has to display all keys and values

s30

Conclusion: Going through from Drupal 7 form module to Drupal 8, I learned about more than just the Drupal 8 Form API. I've learned how hook_menu got replaced by routes and controllers, in YAML files and Controller.php files. I also learned how to use classes, and find the methods I could use by looking inside interfaces.
 

Git Source code: https://github.com/xaiwant/D8custom-form-with-field-data

Related:

How to create custom Form with CRUD operations in Drupal 8

Creating custom contact us block with a form field in Drupal 8

Feel Free to Talk to Us for your Enterprises

 

 

 

Drupal 8: Creating custom contact us block with form field

Before we jump into the custom block writing. I would like to go through the blocker, which came to my learning. Hope it would be clear and simplest way to explain.

Annotations based plugin discovery
Annotation is a meta data for our block. similar to hook_block_info did in drupal 7.

which carries machine readable name, admin label, category etc. drupal has Annotations-based plugin discovery mechanism which read the meta data and let the module knows that particular plugin is an implementation of block. Because of that it implement block plugin interface. it provides various method like build and block form, which drupal knows it exist & called up whenever  we require displaying content in our block.

Here's what the Drupal handbook has to say about plugins:

Most of the plugins in Drupal 8 will use annotations to register themselves and describe their metadata. Some of the plugins types provided by core are:

  1. Blocks (see */src/Plugin/Block/* for many examples)

  2. Field formatters, Field widgets (see */src/Plugin/Field/* for many examples)

  3. All Views plugins (see */src/Plugin/views/* for many examples)

   
Conditions( used for Block visibility in core)

s10
  • The 'id' property in annotation defines unique & machine readable ID for block, and the name of the block to be seen by other code.

  • The 'admin_label' annotation defines the human readable name of the block that will be used when displaying your block in the administration UI.

    s6
     

  • The ‘category’ defines the package for your custom block.

    s7



Plugin API

In Drupal 8 Plugin allow our module to provide additional functionality by reusing the code & implement the interface with different functionality. In Drupal every block consists of the same parts, label, content, and various settings related to visibility and cachability. How that label and content is generated is different varies from one module to another.

The plugin system has three base elements:

Plugin Types: Is the controlling class that defines how the plugins of this type will be discovered and instantiated. The type will describe the central purpose of all plugins of that type; e.g. blocks, etc.

Plugin Discovery: is the process of finding plugins within the available code base that qualify for use within this particular plugin type's use case.

Plugin Factory: The Factory is responsible for instantiating the specific plugin(s) chosen for a given use case.

In this Custom block i’m going to add some fields(org name/ org location/ email id/ phone/ address). i’m saving theses values to my block configuration page. and also validating one of the field (org name) should not be numeric.

Defines a base block implementation that most blocks plugins will extend.

This class provides the generic block configuration form, default block settings, and handling for general user-defined block visibility settings.

$form = parent::blockForm($form, $form_state);

It creates a form array and get all the data from the parent method.

s12

saves the block configuration data.

s13

Process the block's submission handling if no errors occurred.

s14

Get the block configuration.

s15

To add validation for a specific block type, override BlockBase::blockValidate().

Once we have done with block build, block form, save configuration, get configuration, validate and submit. we will find our custom block to be listed in our block listing page.

Below is the Block form layout of our custom Block module


s16

After filling up all the detail save the block. and our custom block start displaying in the specified region.

s17

Git Source code: https://github.com/xaiwant/D8custom-block-with-field-data

Drupal 8: How to create a custom block programatically

In Drupal 8 Blocks are made up of two separate API. Block Plugin API, is a reusable API and Block Entity API, use for block placement and visibility control.

Before we begin with custom Block module development. We assume that you’ve better understanding of Plugin API & Annotation-based plugins.

Creating a custom block require following steps:

  1. Create a block plugin using Annotations

  2. Extend the Drupal\Core\Block\BlockBase class.

In Drupal 8, We need to keep the keep our custom,  contributed module in root directory

modules/custom

module/contrib

Step 1:  An essential part of a Drupal 8 module, theme, or install profile is the .info.yml file (aka, "info yaml file") to store metadata about the project.

In Drupal 8, .info file changes to .info.yml. Old .info files have been converted to YAML.

Added name, description, core, package, dependencies, type (The type key, which is new in Drupal 8, is required and indicates the type of extension, e.g. module, theme or profile.

 

Step 2:  We should follow the PSR-4 standard code for custom block(s) & that has to be placed into article/src/Plugin/Block/ and named based on the class it contains. If we're going to define the class ArticleBlock this file would be article/src/Plugin/Block/ArticleBlock.php

s33

 

Create a file ArticleBlock.php under modules/custom/article/src/Plugin/Block folder structure

Annotation contains just the id and label:

  1. The 'id' property in the annotation defines the unique, machine readable ID of your block.

  2. The 'admin_label' annotation defines the human readable name of the block that will be used when displaying your block in the admin interface.

  3. The 'Category' defines which section belongs to under block listing page.


     

The ArticleBlock extends BlockBase class. This class provides generic block configuration form, block settings and handling of user defined block visibility settings.

 

Where are we displaying markup in our block ?

Save the file and enable the module. To enable a block visit /admin/structure/block and click on “place block” under one of the region. i’m selecting “Sidebar Second” for my visibility or search for your block “Article block” click on “place block” and configure it.

s36

 

s37

So, we have done with configuration. it’s time to visit our page. as we set the block to  page.

s38

 

Git Source code: https://github.com/xaiwant/drupal8-block

Views Contextual Filters to Display Content by passing Raw value from URL in Drupal 8

As we all familiar with the basics of normal filter and contextual filter. In this tutorial i won’t touch basics of views but The Contextual filter.

If you’re not familiar with Views Contextual Filters, It’s also known as Views Arguments in Drupal 6 and then got renamed for Drupal 7 as well. Essentially, Contextual Filters intelligently filters content to reduce the result set in various ways and is pretty powerful.It makes your View scalable and one View can be used on many pages on your site rather than having to create many views, one for each page / block.

Lets’ Begin with Contextual Filter

Example of Books, my use case is something like this: I have a node type "Books" with some additional field (Title/ Authored by). The view example.com/basics/ lists all content belongs to specific user id and by adding a contextual filter I can filter the View to books relevant to a particular uid

i.e:  example.com/basics/ etc

Step 1: Under the "Advanced" area of the Views UI admin, expand that and you will see "Contextual Filters".

Advanced Filter

Step 2: We are going to add “Content Authored By”  & click on Apply (all displays)

Content Authored by

Step 3: Select Provide default value under Default actions “Type: Raw value from URL” WHEN THE FILTER VALUE IS NOT IN THE URL
below you will get the Path component. so, based on your requirement you can set the path component. for now i’m keeping default path to 1 and click on Apply (all displays)

THE FILTER VALUE IS NOT IN THE URL

Step 4:  Click on Save button and save the view page configuration. now you can visit the page example.com/basics/.

Now Keep changing the available uid to load the page based on their user id.

save view page configuration

E.g: with uid 3

UID 3

E.g: with uid 4

UID 4

Drupal 8 - A Milestone in Flexibility, Performance and Enhanced Experience!

Drupal 8 is the latest and greatest release of World’s most widely used enterprise CMS. The best of Drupal yet was released on 19th of Nov 2015. Being an active part of the Drupal community, Valuebound takes immense pleasure in the release of Drupal 8.

Many things have already been talked about the latest version of world’s fastest growing enterprise CMS that provide great digital experience. All being of course essential and important, it is also necessary to provide an insight into what’s there in our new protagonist because in the end it’s the functionality that makes something great!

Let’s start with mobile phone users. There are 3.2 billion internet users and when we double the number that is, around 7 billion, what we get is the number of mobile cellular subscriptions worldwide, not to mention it has large number of smartphone users at present and near future. The numbers are humongous and hence it was very important that this community is served well. Drupal 8 leaves no stones unturned when it comes to experience on mobile. It is snappy on mobile phones and features are completely mobile-friendly where REST API supports editing of large portfolio of sites.

For companies, it has become very important to know what their customers think of them and encourage engagement. Understanding this need the new Drupal 8 has extended its content structuring system by enabling site managers to attach more fields like phone number, email etc that will enhance dialogue.

With its ever increasing popularity globally and being an open source CMS it was essential that it address the multilingual community's needs and well to tell that drupal 8 not only speaks your language but it modifies itself according to the user while making sure it is completely secure with consistent updates from its ever increasing user communities.

Its file system-based configuration system will seamlessly assist in bringing new changes so important to stay relevant in the business. It also provides centralized control for rich Internet applications. Views which is one of the very popular Drupal add-on has been made more integrative by bringing it into the core CMS.

Users can export entities in JSON or XML. Enhanced authentication by HTTP. with much more modern and more focussed code i.e classes, interfaces also embracing the latest PHP standards and equipped with best of breed libraries (to write and debug codes easily). Features like new NavBar Module (for content administrators) and Quick edit makes it an apex performer.

Drupal 8 has set new standards in its area of operation which addresses previous concerns regarding scalability and efficiency. More we will explore with time. Thanks to all the sung and unsung heroes whose hard work has created it. Kudos!

Drupal Global Training Day: Valuebound does it with fun!

Valuebound, in association with Bangalore Drupal User Group conducted a Free Drupal Training on 21st Nov 2015 on the occasion of Drupal Global Training Day.

The Training was held as a part of fostering awareness about the World’s leading CMS platform, Drupal.

Keeping in view the Drupal popularity, Valuebound wanted the training to be all-inclusive and we made sure that there should be something for everyone to learn, i.e. not just for veteran coder but also for newbies and aspirants who might be looking its future in Drupal. It was attended by around 30 people which included Freshers, PHP Developers, Job seekers and of course Drupal developers. It turned out to be better than what was expected as many of the trainees came from outside of Bengaluru!

The session began at 10.30 am and was hosted by Aneesh, who is a Sr. Drupal Consultant at Valuebound and Malabya also Drupal Consultant at Valuebound. Training was provided on topics viz;

  • About Drupal
  • Drupal community and the career opportunities that exist in India
  • Building your first website in Drupal
  • Introduction to newly released Drupal 8 and its newly added features

We also celebrated the launch of Drupal 8 after the training session. The cakes and refreshments were welcomed by everyone. The celebration also included photo event to make the launch event memorable. Valuebound was very glad at the successful completion of the event and will look forward to take more of similar opportunities in future to make the Drupal community bigger.

My first experience and understanding of Drupal 8 theming

Drupal 8 which has now become the most leading drupal ever build and surely it will add more feature compare to other CMS which are out there. Technologies like Symfony, YAML, Twig, and Backbone.js are the main power of Drupal.

Theming in drupal has undergone a lot of changes since drupal 7, especially when talking about the twig template - a known template engine for PHP framework.

Many things has changed from Drupal 7 to Drupal 8 and we will discuss it in the following sections.

  • mytheme.info.yml
    The .info file which was used in drupal 7 to define the theme has been changed to .info.yml extension in drupal 8.
    YAML ()
     
  • mytheme.libraries.yml
    In this configuration file you will have all your stylesheets and javascript libraries included.
    Note: It will store the path of the css and js file which is to be used in your project.
     
  • mytheme.breakpoints.yml
    This is the file to set up the breakpoints of the responsive custom theme.
     
  • mytheme.theme
    This is the file where all of the preprocess functions is stored. Similarly to the template.php file used in drupal 7
     
  • Template (*.html.twig)
    The template pages like page.html.twig, html.html.twig has been introduced in drupal 8.

Theme folder new structure

Below is the screenshot of newly introduced theme folder structure in drupal 8 to be followed.

Add service

mytheme.info.yml

mytheme.info.yml file is similar to like .info file , which contains the information about the theme name, description , libraries regions ,settings etc…

name: mytheme
It contains the human readable name that will appear in the Appearance page in your drupal site. The name will be displayed in the theme list.

description:’A drupal 8 theme’ :
A short description of the theme that will appear in the appearance page.

type: theme
Keyword to differentiate between module, theme or profile.

package: Custom
Main function of package is that it allows to group the themes together which can be seen in the appearance page of your drupal site.

base theme: Classy
It act as an inheritance like in Object oriented programming where a child inherits the property of parent , similarly here our theme will inherit the properties of the classy theme.

core: 8.x
The core specifies the version of the drupal that your theme is compatible with.

screenshot: screenshot.png
The screenshot of the theme will be displayed on the appearance page.

libraries: mytheme/global-styling
The libarary is used to asset library which contains both CSS and JS to all the pages. It adds both the global and the custom CSS and JS file. We have used mytheme/global-styling, here mytheme (key) is the name of the custom theme and global-styling (value) is the reference to the library name that we use to define the assets.
We will discuss more about this section little later.

regions:
Regions are nothing but naming the sections in the webpage that will be formatted in the template page (page.html.twig) ...
e.g , header : Header :

Here on the left is the machine name which can be used for formatting and on the right is the human readable name for the regions that has been defined.

mytheme.libraries.yml

The file contains the location of the asset where the CSS and JS are located.

Below is the basic demonstration of the .libraries.yml file.

Here we have two asset containers, global-styling and custom-assets:

While including the libraries the format should be like

libraries: - mytheme/global-styling - mytheme/custom-assets

Proper spacing should be kept in mind as YML follows text indentation so the spaces should be specific.

Each of the CSS librarry should be written in this format -

css: theme: css/style.css: {} css/layout.css: {} css/print.css: { media: print }

Here we have added three css files style,layout and print.

Similarly the JS file is also included with the proper text indentation.

js: js/mytheme.js: {}

Here is subfolder of the css and js file which is included in the asset library

Add service

mytheme.breakpoints.yml

Breakpoints are the points where the theme will adjust its layout based on the browser width. Breakpoints are mainly given for the mobile tab desktop view . These breakpoints can be achieved through media queries in CSS.

In order to setup this configuration we need to create file mytheme.breakpoints.yml

In each label we have assigned a unique name as mytheme.mobile, mytheme.tab, mytheme.desktop with the following properties:

  • label
    Readable name for the breakpoints
  • mediaQuery
    Proper media query syntax which defines at what point the breakpoint should occur
  • weight
    The order in which the breakpoint should occur
  • multipliers
    Supports pixel resolution modifiers.

mytheme.theme

This file has the same functionality as template.php in drupal 7 . So all the hook preprocess functions are added here.

Below is an example of preprocess function for adding classes in the body tag when the page is loaded.

Here layout-two-sidebars css class will be added to the body when there is both the sidebar present in the page.

Twig template file

Twig templates are introduced in Drupal 8 replacing the php templates which was used earlier in Drupal 7 to theme the pages, nodes , taxonomy terms etc.

Given below is an example of twig template engine which is used as a base theme in classy.

Twig Syntax

{% ---%} : Checks the logical code
{{ -- }} : Print the region

This is just the part of the page.html.twig file to give demonstration of how the twig file works. To know more about twig templates you can visit the site twig.sensiolabs.org

This is list of Twig template files which can be modified for custom theme

HTML (template)

  • html.html.twig

Page template

  • page.html.twig
  • page–node.html.twig

Regions

  • region.html.twig
  • region–.html.twig, ie: region–right-sidebar.html.twig

Blocks

  • block.html.twig

Nodes

  • node.html.twig

Taxonomy terms

  • taxonomy-term.html.twig

Comments

  • comment.html.twig

Maintenance page

  • maintenance-page.html.twig

Search result

  • search-result.html.twig

Locating Template Files with Debugging

While adding the content we do need to override the template files. It’s important to know which template should be overridden to affect the theme.This can be done through by enabling the theme debug option in services.yml file.which is located in sites/default/services.yml

Search for twig.config and change the value of debug to true

Add service

And this wraps it up for now. In the process of experimenting I learned a lot about creating a custom theme in drupal 8 and working with twig. To develop a custom theme I will recommend to is to take classy or bartik or any core theme as a base theme so that customizing and overriding the template can be done easily.

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