Drupal 8 Create a custom page

For creating custom page in Drupal 8, there are two Steps.

Step 1:  First, you need to declare the routing in <module_name>.routing.yml.

Step 2: Secondly, you need to add a controller that returns the page body in    example/src/Controller/ExampleController.php.

Example are below for creating a simple page through custom module.

#Declaring a routes

The routing information is stored in example/example.routing.yml:






example.my_page

This is the machine name of the route. By convention, route machine names should be module_name.sub_name. When other parts of the code need to refer to the route, they will use the machine name.

path

This gives the path to the page on your site. Note the leading slash (/).

defaults

This describes the page and title callbacks. @todo: Where can these defaults be overridden? 

requirements

This specifies the conditions under which the page will be displayed. You can specify permissions, modules that must be enabled, and other conditions. 

#Add a controller (page callback)

The controller returns the page body. It must be either a class method or a registered service. It can be different depending on various conditions (HTTP vs. HTTPS, content headers, others) but that is beyond the scope of this introduction.

The Controller class ExampleController should be defined in example/src/Controller/ExampleController.php:

namespace

This declares the prefix needed to fully qualify the name of the class we are defining. Compare the file's doc block and the name of the class. The class auto-loader knows that, to find the class \Drupal\example\Controller\ExampleController, it should look for the file modules/example/src/Controller/ExampleController.php.

use

This allows us to use ControllerBase instead of the fully qualified name. This makes our class line much easier to read.

 myPage()

The method specified in the YAML file must be public. It should return a renderable array.



Drupal 8: How to create a custom block programmatically

 Blocks in Drupal 8 are instances of the block plugin.

The Drupal block manager scans your modules for any classes that contain a @Block Annotation 

Creating a custom block require following steps:

1. Create a block plugin using Annotations

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

The example snippet below makes use of the @Block annotation along with the properties "id" and "admin_label" to define a custom block.

Create the file src/Plugin/Block/TestBlock.php within the module skeleton created earlier and add the code below. You will, of course, need to rebuild the cache.



To add 'Test block' you can go to Structure -> Block Layout (admin/structure/block) and click on 'Place Block' button associated with each available region.

Clicking on 'Place Block' button for any given region a "Place Block" dialogue pop-up will appear, with a listing of all available blocks. To quickly find your block, simply use 'Filter by block name' option or use mouse-scroll to locate Test block'. This way you can add any number of instances of the custom block anywhere on your site.

Below is the Step to add twig template with custom created Block

Create your test .module file if you don't have one and add hook_theme() with defined variables names, and Twig template name.



Now clear cache and go to Structure -> Block layout. Find your block and place it in the region you want.

Next step is to create Twig file and render variables. In your themes folder open the theme that you use e.g. testtheme and open folder templates/block. Now, create a file block--test-custom.html.twig (we defined the namespace in the array 'template' in the first example). 

Render variables to Twig HTML:



How do I create a new theme in Drupal 8?

 The main difference between theming of Drupal 7 & Drupal 8 is theme engine. In Drupal 7 supports PHPTemplate and Drupal 8 leverages Twig engine.

Open your installed Drupal project folder in any editor you prefer. Under the themes folder create a folder with your desired theme name.

Step 1:  Create .info file

An Important part of Drupal theme or module is .info file. Through this file drupal will understand whether it is theme or module.

In Drupal 7 it was .info but in D8 it changes to .info.yml (called as yaml). So to create a theme, first create a folder and name it after the theme. In this case let’s say theme name is “Test”, So create a folder of name test. Notice that all letters are in small. Now in this folder create a file and save it as test.info.yml. This is our info file. The rest is same as Drupal 7 .info file

/*——————————— Code starts here ——————————————–*/

name: Test

type: theme

description: ‘This is D8 theme based on bootstrap’

core: 8.x

regions:

 top_header_first: ‘Top Header First’

 top_header_second: ‘Top Header Second’

 top_header_third: ‘Top Header Third’

 top_header_fourth: ‘Top Header Fourth’

 header: ‘Header’

 logo: ‘Logo’

 primary_menu: ‘Primary Menu’

 page_title: ‘Page Title’

 breadcrumb: ‘Breadcrumb’

 slider: ‘Slider’

 content: ‘Content’

 sidebar_right: ‘Sidebar Right’

 footer_first: ‘Footer First’

 footer_second: ‘Footer Second’

 footer_third: ‘Footer Third’

 footer_fourth: ‘Footer Fourth’

 footer_fifth: ‘Footer Fifth’

 footer_sixth: ‘Footer Sixth’

/*——————————— Code ends here ——————————————–*/

Now go to the Appearance section and you will see Test theme. Don’t enable it yet, we still have to define the layout of our theme.

Step 2: Create .libraries.yml file

Then comes the .libraries.yml file. The main purpose of this file is to include all the css and js files. In Drupal 7 these file were included in .info file directly. In Drupal 8 they are also included in .info.yml file but indirectly.

Now create test.libraries.yml file in root directory of theme folder.

/*——————————— Code starts here ——————————————–*/

custom:

 version: 1.x

 css:

   theme:

     includes/bootstrap/css/bootstrap.css: {}

 js:

   includes/bootstrap/js/bootstrap.js: {}

 dependencies:

   – core/jquery

   – core/drupal.ajax

   – core/drupal

   – core/drupalSettings

   – core/jquery.once

 global-style:

 version: 1.x

 css:

   theme:

     css/custom.css: {}

fonts:

 version: 1.x

 css:

   theme:

     ‘//fonts.googleapis.com/css?family=Montserrat’: {type: external}

     ‘//fonts.googleapis.com/css?family=Kaushan+Script|Courgette|Kalam’:{type:external}

     ‘//fonts.googleapis.com/css?family=Open+Sans+Condensed:300’:{type:external}

/*——————————— Code ends here ——————————————–*/

Consider custom in above code as container of the css and js files. In above file there are 3 containers custom, global-style and font. You can name the anything you want. Under these container we define the css and js files which we want to use in our theme.

Note: Use spacebar instead of tabs or it will throw an error.

Now define these containers to .info.yml file like this


libraries:

 – test/custom

 – test/global-style

 – test/fonts


By defining libraries section in .info.yml file we tell Drupal to look for .libraries.yml file and find there custom,global-style and fonts container.

So the here is how test.info.yml file will look like

/*——————————— Code starts here ——————————————–*/

name: Test

type: theme

description: ‘This is D8 theme based on bootstrap’

core: 8.x

libraries:

 – test/bootstrap

 – test/global-style

 – test/fonts

regions:

 top_header_first: ‘Top Header First’

 top_header_second: ‘Top Header Second’

 top_header_third: ‘Top Header Third’

 top_header_fourth: ‘Top Header Fourth’

 header: ‘Header’

 logo: ‘Logo’

 primary_menu: ‘Primary Menu’

 page_title: ‘Page Title’

 breadcrumb: ‘Breadcrumb’

 slider: ‘Slider’

 content: ‘Content’

 sidebar_right: ‘Sidebar Right’

 footer_first: ‘Footer First’

 footer_second: ‘Footer Second’

 footer_third: ‘Footer Third’

 footer_fourth: ‘Footer Fourth’

 footer_fifth: ‘Footer Fifth’

 footer_sixth: ‘Footer Sixth’

/*——————————— Code ends here ——————————————–*/

Next is test.theme file. In Drupal 7 this file was used to be template.php. Just the name is different.

Step 3: Create page.html.twig file

Now we have told drupal that this is theme for core version 8 and also specify the css and js file which we want to include in our .info.yml amd libraries.yml file. Now lets define the page layout of our theme. For this create template folder in the theme directory and create new file named as page.html.tiwg. In Drupal 7 this file used to be named as page.tpl.php.

This naming difference because we are using twig theme engine.

/*——————————— Code starts here ——————————————–*/

{% if page.explore_block or page.booking_block %}

<div class = “row”>

{% if page.explore_block %}

<div class = {{explore_block_class}} >

{{ page.explore_block }}

</div>

{% endif %}

{% if page.booking_block %}

<div class = {{ booking_block_class }}>

{{ page.booking_block }}

</div>

{% endif %}

</div>

{% endif %}

/*——————————— Code ends here ——————————————–*/

Let’s go through this file and see what’s going on. The first thing we notice are the two different types of code blocks (also called block delimiters). One type of code block is marked by double curly braces like so:


{{…}}   This is used to print a variable


{% … %} This is for usinf loop, function etc etc.


{# This is used for comments. #}


You will notice that in above piece of code the “if .. endif” goes inside the {% … %} braces and variable to print goes inside {{ … }}. so like above code define the HTML structure and print the variable using the appropriate braces.

Once the page.html.twig is completed, the theme is ready to use.

Implementing #autocomplete in Drupal 8 with Custom Callbacks

 Autocomplete on text fields like tags / user & node reference helps improve the UX and interactivity for your site visitors, In this blog post I'd like to cover how to implement autocomplete functionality in Drupal 8, including implementing a custom callback

Step 1: Assign autocomplete properties to textfield

As per Drupal Change records, #autocomplete_path has been replaced by #autocomplete_route_name and #autocomplete_parameters for autocomplete fields ( More details -- https://www.drupal.org/node/2070985).

The very first step is to assign appropriate properties to the textfield:

1: '#autocomplete_route_name':

2: for passing route name of callback URL to be used by autocomplete Javascript Library.

3: '#autocomplete_route_parameters':

4: for passing array of arguments to be passed to autocomplete handler.







Thats all! for adding an #autocomplete callback to a textfield. 

However, there might be cases where the routes provided by core might not suffice as we might different response in JSON or additional data. Lets take a look at how to write a autocomplete callback, we will be using using my_module.autocomplete route and will pass arguments: 'name' as field_name and 10 as count.

Step 2: Define autocomplete route

Now, add the 'my_module.autocomplete' route in my_module.routing.yml file as:








While Passing parameters to controller, use the same names in curly braces, which were used while defining the autocomplete_route_parameters. Defining _format as json is a good practice.

Step 3: Add Controller and return JSON response

Finally, we need to generate the JSON response for our field element. So, proceeding further we would be creating AutoCompleteController class file at my_module > src > Controller > AutocompleteController.php.




















We would be extending ControllerBase class and would then define our handler method, which will return results. Parameters for the handler would be Request object and arguments (field_name and count) passed in routing.yml file. From the Request object, we would be getting the typed string from the URL. Besides, we do have other route parameters (field_name and Count) on the basis of which we can generate the results array. 


An important point to be noticed here is, we need the results array to have data in 'value' and 'label' key-value pair as we have done above. Then finally we would be generating JsonResponse by creating new JsonResponse object and passing $results.


That's all we need to make autocomplete field working. Rebuild the cache and load the form page to see results.


Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...