How to create a Drupal Entity programmatically in Drupal 8

Entities have been introduced late in Drupal 7. Drupal entity is an instance of a particular instance type. For example, the entity type for taxonomy terms is named taxonomy_term and the class name Term. We include a class like  Drupal\taxonomy\Entity\Term. Here taxonomy is a core module name, and Term is the class name of Entity.

Related: How to Create Custom Entity in Drupal 8 for Content Management

A. How to create a user programmatically.

The fields to be created are as follows:

  1.  Username
  2.  Email address
  3.  Password
  4.  Status
  5.  Roles
  6.  Picture
  7.  Timezone

If you want to create a Drupal user programmatically we can create it the way as given below:

a) This is the first method

  The output is shown below:user create

Related: How to Create Configurable Block programmatically In Drupal 8

The use of Drupal\user\Entity\User; is to include the class User.

User::create()is used to create a user where it takes the details about the user.

Here name is the username whose account is to be created.

Here mail is the email id of the user and pass is the password for the user.

The status tells you if the user account is active or blocked. If it is 1 then the user account is active and if it is 0 then the account is blocked.

The roles mention which roles is given to the user. To give the user more than one role simply pass an array of roles.

The timezone mentions a timezone set for the user.

The user_picture accepts the image’s file id to get the user image. To get the file id we have passed a static image here in $file_image='/var/www/html/drupal/sites/default/files/2017-04/images.jpeg'; The file_get_contents() reads a file into a string. $directory is the name of the folder where you want to save the uploaded image. file_prepare_directory($directory, FILE_CREATE_DIRECTORY); The above line creates the folder if it doesn't exist. The file_save_data saves the files details. The first parameter takes the file content, the second parameter takes the name of the folder you want to save your image and the name of the file, the third parameter tells you to replace the file if it already exists.

b) This is the second way to create user  

The first parameter of entity_create accepts the entity type that we want to create and the second parameter accepts an array of values to be used to create that entity. The user created is saved to finally create the user.

Related: How to add Product Programmatically to Drupal Commerce Cart

B. How to create a node programmatically

If you want to create a drupal node programmatically we can create the way as given below:

a) This is the first way to do this:

 

node create

 This will be the output.

Here the use \Drupal\node\Entity\Node; is used to insert the class Node.

Node::create() is used to create a node.

Inside Node::create() the node details is passed.

The type tells you the content type whose node is to be created.

The title is the node title, body is the body part of a node.

The field_mail is the email id to be entered if you have a field for email.

The field_link allows you to add a link if you have any link field and field_date holds the value of date field.
 

b) This is the second way to create the node   

  The entity creates function takes two parameters where the first parameter tells you which entity to create and the second parameter should be an array of the node details. 

C. How to create a taxonomy term programmatically

If you want to create taxonomy term programmatically we can create the way as given below:

a) This is the first way to create term

  The output is shown below:

term create

   In above code use Drupal\taxonomy\Entity\Term; is used to insert the class Term

  Term::create has been used to create the term where Term is the class name.

 

Here name and vid are machine names where name represents the name of the new term you want to create, and vid is the name of the taxonomy term whose term you want to create.

b) This is the second way to create a term 

The entity create function takes two parameter where the first parameter tells you which entity to create and the second parameter should be an array of the term details.

 It should contain the term name and the taxonomy name whose term you want to create. You can add the term description but it’s optional.

D. How to create a custom menu

Create a form inside the Form folder as given in the code below.In Drupal 8 modules we write a form inside a Form folder.

Create a routing file which is module_name.routing.yml  Here menu.route is the routing name and _form is the path of the form. 

In module_name.links.menu.yml file write the code for the menu as shown below:

  links.admin is the name of the menu.

The title will appear as the menu name.

The parent tells you the place where the menu will be created like system.admin will create the menu in the main navigation. If the parent is not mentioned then the menu will be created in the tools.

Related: How to create a custom block programmatically in Drupal 8

  The route name is the name of the routing file of whose menu you want to create.

The output is as follows.

menu

  Here TechX is the menu created.

E. How to create a custom permission

 Taking the example of the module above, create a file and name it as module_name.permissions.yml

  Write the following code into it:

 Here 'Menu permission': is the name of the permission that we mention in the routing file ,

 The title gives you the name displayed in the drupal's permissions page. In routing file under _permission we mention this permission name. So whichever role has this permission can view the form.

This is how drupal permissions are given to a particular page when you don’t want to show the page for every user or role.

So here we have learnt how to create entities in drupal 8 programmatically. In drupal 8 you can create node, user, taxonomy without code, but sometimes due to various project requirements and we need to create these programmatically.

Related:

How to send mail programmatically in Drupal 8

How to add Custom JS / CSS to Drupal 7 page in theme for a better user experience

Adding JS adds dynamic presentation effects to a theme for a better user experience.

In One of the project when i had been asked to display a custom error message to the User login page, when user tried with 3 or more failed attempt. On the other hand we can handle the error using form_set_error or drupal_set_message. What if we want to include that error message to be displayed on specific position.there comes add_js into picture. I have created a hook_form_alter inside that called a custom form validation. Under that custom form validation by checking the user login count, calling an js to the user page. Sleek and simple way to do the JS

When we work with theming or module development we required to add  custom js / css to our theme or module and Adding own CSS/JS to the Drupal page is easy and multiple approach is available in drupal to do this. But the best approach to do is to get the exact requirement and understand what is best way to handle css/ js for that period of time.

Below are the list of approach

  • drupal_add_css(), drupal_add_js()
  • including in .info file
  • [‘#attached’] attribute
  • drupal_add_library()
  • hook_css_alter(&$css), hook_js_alter(&$js)
  • drupal_add_html_head()
     

Including as html in .tpl.php
 

1. drupal_add_css(), drupal_add_js()

In Drupal, drupal_add_js() & drupal_add_css() are functions to add JS/CSS to the module or theme layer. This method is used by most of the developer. Which is easy to use and can be inserted wherever you want, can be inserted online, can be added file as cache easy to find documentation. On the other hand it can be found anywhere in the codebase where it is difficult to search sometimes and you are not expecting to be there. Adding multiple file can lead to a big mess. And also require proper naming convention if you make change in js or css file. You need to add the same name to everywhere in  the code where you have used drupal_add_js() & drupal_add_css().

drupal_add_js(drupal_get_path(‘module’, ‘example’) . ‘/example.js’);

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

drupal_add_css(drupal_get_path('module', 'example') . '/example.css');

drupal_add_library('example', 'drag-and-drop');

 

2. including in .info file

Custom Javascript file can be added to module/theme under info file. It ‘s always a better way to let the other Developer know how many more  file you are going to attached with your module or theme. Once it is has been declared & added to module/ theme file. It automatically get added to all the page. No need to declare in any of the preprocessor. Most of the themer use this approach for theming. On the other hand unusual css /js get added to un required pages.  No control over addition of css/ js to specific page. Can not be removed or set weight in .info file.

name = My theme

description = Theme developed by me.

core = 7.x

engine = phptemplate

 

scripts[] = mytheme.js

3. Form API [‘#attached’] Property

On of the best way to make sure which files you are going to add. Works great with CSS, JS, library. Easy to include in any of the drupal form and we have ability to add multiple files. It can be used any kind of attached data. A keyed array of type => value pairs, where the type (most often 'css', 'js', and 'library') determines the loading technique, and the value provides the options presented to the loader function.

$form['#attached']['css'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
);
$form['#attached']['js'] = array(  

    drupal_get_path('module', 'ajax_example') . '/ajax_example.js',

);

4. drupal_add_library()

Adding a multiple JavaScript or CSS files at the same time.

The library defines collection of JavaScript and/or CSS files, optionally uses settings, and optionally requiring another library. For example, a library can be a jQuery plugin, a JavaScript framework, or a CSS framework. This function allows modules to load a library defined/shipped by itself or a depending module, without having to add all files of the library separately. Each library is only loaded once. It allow you to reuse styles/scripts on different pages, Path and file names are stored in one function, easy to include in multiple files. On elibrary can use other library too. On the other side a Bit more code to write. And include all the files in library.

Parameters

$module: The name of the module that registered the library.
$name: The name of the library to add.
$every_page: Set to TRUE if this library is added to every page on the site. Only items with the every_page flag set to TRUE can participate in aggregation.

Return value

TRUE if the library was successfully added; FALSE if the library or one of its dependencies could not be added.


5. hook_css_alter(&$css), hook_js_alter(&$js)

hook_css_alter() is designed to act on .css file before they are being included on the page .  using this hook you can easily stop a .css file or group of files from being added to the page.


function demo_css_alter(&$css) {

  $path = drupal_get_path('module', 'node') . '/node.css';

  unset($css[$path]);

}

The $path variable you see above stores the path to the node.css file found in the Node module folder and is used in the unset() function to identify which array element we want to unset.

Parameters:

$css: An array of all CSS items (files and inline CSS) being requested on the page.

hook_js_alter() Perform necessary alterations to the JavaScript before it is presented on the page.


function hook_js_alter(&$javascript) {

  // Swap out jQuery to use an updated version of the library.

  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';

}

Parameters:

$javascript: An array of all JavaScript being presented on the page.


These above two hooks help you to rearrange elements by weight. we can delete files you don’t need before aggregation. Easy to replace path to a specified file. And Possible to re configure the aggregation. On the other hand Adding files here is possible but a bad choice and you end up by  messing up with files here.


6. drupal_add_html_head()

This is not the  recommended way to adding your custom css/js to the page as Using this functionality we adds output to the HEAD tag of the HTML page.This function can be called as long as the headers aren't sent. Pass no arguments (or NULL for both) to retrieve the currently stored elements. It’s is very difficult for understand where the code is included.


/**

 * [THEME] Preprocess function for the html theme hook.

 */

function themename_preprocess_html(&$variables) {

  $front_page = drupal_is_front_page();

  if ($front_page) {

    $variables['head_title'] = 'Jesús Heredia | Web Developer';

    // Add the description meta tag to the header

    $meta_description = array(

      '#type' => 'html_tag',

      '#tag' => 'meta',

      '#attributes' => array(

        'name' => 'description',

        'content' => "Jesús Heredia's personal website. Web Development on HTML5, CSS3, JavaScript, PHP, and Drupal.",

      )

    );

    drupal_add_html_head($meta_description, 'meta_description');

  }

}

Syntax: drupal_add_html_head($data = NULL, $key = NULL)


Parameters

$data: A renderable array. If the '#type' key is not set then 'html_tag' will be added as the default '#type'.

$key: A unique string key to allow implementations of hook_html_head_alter() to identify the element in $data. Required if $data is not NULL.
 

7. Including as html in .tpl.php
Yes we can add as html file in .tpl.php or printing it. Hope those methods come in handy for you. Make sure to use them in dependence of conditions you meet.

Conclusion: I personally feel to use drupal_add_library and [‘#attached’]. The form attached is really awesome and it’s very easy to understand what’s going on without scrolling through all the code.If you have any other idea just share across us over comment. want to find out more.

How Heatmap Tracking Tools can increase website traffic using website analytics for digital publishers?

Most of the media companies are competing in content marketing in the online world and battling with the question, whether their content is faring well than the others. Analytics and metrics give deep insights on number of visits, visitors, duration of a visitor’s visit, the entry and exit points, but misses on the granular data such as the engagement level and interaction on the content page.

To measure the missing connect, publishing companies have moved towards heatmap tracking tools; to understand how people interact with the content on the website. Heatmap is a visual overlay that has the appearance of an infrared display with colour variations indicating high and low levels of activity. These heatmap tracking tools are very useful when preparing website navigation, layout and  in designing user friendly interface.

Heatmaps can measure - click, move and scroll, that means it can track where users have clicked on a page, how far they have scrolled on a page, and have also been used to display the results of eye-tracking movements and these results are displayed in real time.

When used along with other analytical tools, these heat map tracking tools give a good result in optimising website, understanding the aggregated behaviour of site visitors on content,  generating content performance and driving higher conversion rates.

The most popular website heat maps used by media companies are the following:

1. Crazy Egg: Crazy Egg is one of  the most popular heat map tools. It offers click, mouse cursor, and scroll heatmaps. It offers another useful feature called confetti heat map. Confetti heatmap divides the data into traffic sources, enabling the user to figure out where the most profitable traffic is arriving from. The clicks can be separated by a number of variables, such as device, region, or campaign, thus, giving a better insight. WPMU Dev used Crazy Egg’s confetti report to see how their visitors were interacting with content on their product page and identified the important parts of the navigation menu and redesigned the product page. 

Crazy Egg also gives a comparison of mobile versus desktop visitors to see how the two different groups interact with the content. Unlike other heatmap tracking tools, it does not limit usage to per site, this means one can use the same account on multiple websites. What goes amiss here is that there is no screen-capture recording of the visitors and they do limit the number of active pages. However, Crazy Egg has been utilised by most companies to drive sales. For instance, Softmedia, a world’s leading provider in penny auction software used Crazy Egg heatmaps to identify problem areas on their website. They successfully identified distractions that were preventing visitors from completing  the desired actions. After removing these, conversions increased by 51%, and also improved their user interface.

2. Mouseflow: Mouseflow is another easy to use heatmap tool for WordPress users. Mouseflow offers click, scroll, movement and attention heatmap. It also offers recording of website visitor activity. Sticker Gigant, an emerging social media beauty brand from Germany, approached Mouseflow on relaunch of their website to engage users better and to drive performance. With the help of Mouseflow, Sticker Gigant was able to identify issues in the user interface immediately after relaunching the website. After relaunch, Mouseflow improved the average shopping basket value by 78%, increased orders with iOS devices by 26%, and raised cross-selling with first orders by 18%. These numbers are evidence of how effective heat maps are and these are great tools for tracking website traffic.

Another useful feature offered by Mouseflow is form analytics, which allows one to see why users are abandoning forms. It also tracks funnels, custom funnels can be setup to understand the different sources of traffic and their behaviour. Media companies using Wordpress tend to use their WordPress plugin as it provides support for WordPress multi-sites, which lets one watch the analytics from various domains through a single source; giving insights not only on visitor demographics but also visitor activity.

3. Inspectlet: is a very powerful session recording and heatmap service. It displays how people interact on web-pages employs eye-tracking, shows clicking as well as scrolling on the heatmaps. Their conversion funnel analytics is ideal for those selling products online and their engagement heatmaps are also impressively detailed, tracks all interactions including visitors comments. They also offer conversion funnel analytics with  powerful tagging filtering feature along with form analytics to understand and optimise lead generation. This feature has been helpful for those driving multiple websites in e commerce.

Blue Kangaroo, a social retail website, features trending products and deals from thousands of stores. Prior to Inspectlet, Blue Kangaroo relied solely on analytic charts and graphs to better understand their users. With Inspectlet, Blue Kangaroo could compare how much time their audience was spending on similar products. Taking these inputs into account, Blue Kangaroo improved their algorithm and design, leading to an 84% increase in total clicks.

Heatmap tracking tools give detailed overview of how well users are engaging with the website along with how these are used as tools for tracking website traffic. Heatmaps show both - qualitative and quantitative behavioural metrics.

Media companies are using these heat maps not only to understand the user interface but also using it to get a broader view social media impressions. For, instance-'one million tweet map', is used to see how often people are tweeting around the world and the top trending topics they're tweeting about. Such heat maps provide an idea of when and where specific conversations are/were at their peak. It helps companies to track trending conversations, understand where exactly these conversations are taking place, also use these tools for tracking website traffic as well as track the success of a particular online campaign.

The visual representation makes it easier to analyse the data and gives a direction  to improve search rankings, performance and deliver better user experience.

Discalimer : Image used above is no a real time tracked one, but just for reference.



 

 

Object-Oriented Programming Concepts in PHP - Part 1

PHP is a server-side scripting language, mainly used for web development but also used as a general-purpose programming language. Object-Oriented Programming (PHP OOP),  is a type of programming language principle added to php5, that helps in building complex, reusable web applications.

In this blog, we will be explaining some of the Object-Oriented Programming concepts in PHP with some examples.

The  PHP Object-Oriented Programming concepts are:

 

  • Class 
  • Objects
  • Inheritance
  • Interface
  • Abstraction
  • Magic Methods

Class  & Object:

  • Class is a programmer-defined data type, which includes local methods and local variables.
  • Class is a collection of objects. Object has properties and behaviour.
  • First we have to define a php class, where classname should be same as filename.

Example for simple class:

 

 

Output:

Drupal book

900 Rs/-

In the basics of object-oriented, let see how to define a class and create an object:

Creating Objects in PHP

When class is created, we can create any number of objects in that class. The object is created with the help of the new keyword.

Calling Member Function

When the object is created we can access the variables and method function of the class with the help of operator ‘->, accessing the method is done to get the information of that method. Also, look into how we can access object properties via variables

 

Output for the above code 

Samsung S8

Iphone S7

MI4

90000

65000

15000

Inheritance

When the properties and the methods of the parent class are accessed by the child class, we call the concept has inheritance. The child class can inherit the parent method and give own method implementation, this property is called overridden method. When the same method of the parent class is inherited we call as inherited method. Now let us see types of inheritance supported in Object Oriented Programming and corresponding Php inheritance examples.



 

 

 

 

Types Of Inheritance

  1. Single Level Inheritance
  2. Multilevel Inheritance

Single Level Inheritance:  In Single Level Inheritance the Parent class methods will be extended by the child class. All the methods can be inherited.



Single Level Inheritance

Single Level Inheritance

Example for Single Level Inheritance

 

Output

Hi : Pavan

I am from valuebound

Hi: savan

I am from ABC

MultiLevel Inheritance :  In MultiLevel Inheritance, the parent class method will be inherited by child class and again subclass will inherit the child class method. 

MultiLevelInheritance

 

Output

Class A is 80

Class B is 50 

Class C 20

 

INTERFACES:

  • An interface is a description of the actions that an object can do.
  • Interface is written in the same way as the class the declaration with interface keyword.

Rules of Interfaces:

  • All methods declared in an interface must be public; this is the nature of an interface.
  • All methods in the interface must be implemented within a class; failure to do so will result in a fatal error.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface
  • Interfaces can be extended like classes using the extends operator.

Example for the interface class

Output:

Describing Mango tree

2) Interface can be extended with another interface using extends keyword

 

Output:

division of 10/2 is 5

multiplication of 2*3 is 6

Note on Interfaces:-

  • We cannot create objects to interface, but the class implementing the interface can have objects
  • We cannot define a variable in an interface.
  • If we extend interface all the methods of the interface must be implemented in the child class.

 

Abstract Classes:

  • An abstract class is a class that contains at least one abstract method. The abstract method is function declaration without anybody and it has the only name of the method and its parameters.
  • There can be any number of methods in the class and we have to declare the class as abstract only when there is an abstract method

Example for Abstract class



Output for the above code is:

Maruthi Suzuki

720000

Hyundai

300000

Notes on Abstract classes:

  • Objects cannot be created for the abstract classes.
  • If a class has only one method as an abstract, then that class must be an abstract class.
  • The child class which extends an abstract class must define all the methods of the abstract class.
  • If the abstract method is defined as protected in the parent class, the function implementation must be defined as either protected or public, but not private.
  • The signatures of the methods must match, optional parameters given in the child class will not be accepted and error will be shown.
  • Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).

Now Let us see the difference between abstract class and interface.

Abstract classInterface
It can have constants, members, method stubs (methods without a body), methodsIt can only have constants and methods stubs.

Methods and members can have public or protected  visibility

 

Methods of interface should only be public not any other visibility

The concept of multiple inheritances not supported.

 

An interface can extend or a class can implement multiple other interfaces.

 

Child class must implement all the abstract method of parent class when extend keyword is used.

 

No need of implementing methods from parent interface when interface  is extending another interface

In the end, now we are able to create a class, define objects for the class, and create methods. We also learned about different topics of object-oriented like inheritance, interface, and abstraction. The basic concepts of OOP are explained in this blog. 

Related: Understanding PHPUnit and How to write Unit test cases

 



Revolutionize Your Business: Embrace PHP OOP for Growth

 

How to create custom Form with CRUD (Create, Delete, Update) operations in Drupal 8

Custom form with CRUD Operations is basically building the form with different fields like UID, Name, Mobile Number, Address, Email id etc. The CRUD operations for these fields is Deleting the value of the fields from the database or updating the existing value with new value, and printing the updated value. 

How To Create a Custom form with CRUD Operations?

To create a custom form with CRUD Operations, we need to follow the following folder structure as shown in the image. To perform the same operation of crud in drupal we need to follow the following folder structure.

CRUD Folder Structure



 

The data from the database will be displayed in the form of a table and the table will contain operations as a new column. The role of operations column is to perform edit(update) operation or the delete operation. The edit operation is used to update the present value into new values and delete operations is used to delete the entire row. The following files and procedures help us to create a custom form with CRUD operations. Create the files as shown in the image.

mydata.info.yml:

The .info.yml files is most important part of Drupal Modules. The .info.yml file is a collection of static text file, used to define and configuring a module. First, we have to create info.yml file which contains metadata about the project like the name of the module, description, core, package.

mydata.install:

mydata.install helps to create a table in the database. I have created a table called mydata in the database.hook_schema helps to store the values into the database. In our custom form the crud database will be stored in mydata as the table name. If the value is stored in the database, it helps in performing CRUD operations,like edit or delete. I have stored the fields as name, id, mobile number, email, age gender. Id is autoincrement with the help of serial type.

mydata.routing.yml

mydata.routing.yml helps to transfer the function to the Controller to display of data in table format, to create form and placing that form in blocks. When '/mydata/hello/table' is passed to the url the Controller  DisplayTableController is called and the controller will display the data from database in table format. Similarly when the ‘/mydata/form/mydata’ is passed to the url the form containing credentials like name, id , age etc is shown to the user. The user has to enter the details.



When the path  '/mydata/form/delete/{cid}' is passed to url DeleteForm.php is called. By this file you can delete the fields present in the database row by row.

Controller

In the src/Controller create a file called 

DisplayTableController :

In this file, we will display the output in the table format. We have used the standard way of displaying the values of the row in table format.

The code for displaying the value in table format. The $header_table must be defined, like what are the column values that need to be displayed in the table format.

Form

In the src create a folder called Form, In the form folder, we will create a file which will help to create form fields like Textfield, checkbox, select list, number etc..

MydataForm:

In this file, we will create the form fields for  UID, Name, Mobile Number, Email, age etc. For more info on form API, visit https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api . The complete code for the Mydata form is shown below

In the above file we have performed both Insert and update operations. If the user clicks the edit operations then it will call the update functions or it will be insert operation.We have used three methods to perform the operation

  • Buildform: It is the method which is used to construct the form with different types like text field email, select checkbox etc
  • ValidateForm : In this method we provide validation conditions for the form, that has to be validated before the form values get submitted
  • Submit form : In this method the values will be submitted to the database so, it can be retrieved. 

   2.  DeleteForm.php :

In this file we will perform delete operation. I have followed certain standards to delete operation, we can also user db_delete operation. The complete code for the delete operation is shown below

Note : cid is the current value form the url and cid is stored in this->id(current id).

BLOCK



1 MydataBlock:

This block helps to place the form fields anywhere in the UI. Placing the block can be done by going to admin/Structure/block and placing the block in any of the regions. The code of MydataBlock is shown below

The output of the above module is shown below

CustomForm

The above screenshot displays all the form fields that are to be entered by the user .It is a block that is placed 

CrudOperationPage(output page):  

It display the option for delete or edit

Output of CRUD

 

Reference : https://github.com/pavanBS/drupal-module-crud

 

 

Valuebound's awesome weekend at Drupal Camp Mumbai 2017

We had an awesome weekend at Drupal Camp Mumbai 2017. Met a lot of wonderful people and discussed and planned a host of community activities for the Bangalore Drupal community.


The one above was the first group photo post lunch. The Drupal Camp Mumbai 2017 was held at IIT Bombay, with a footfall of around 500 Drupalers, college students, and experts. Valuebound was one of the Gold sponsors for the event along with Acquia and we are glad to help with T-shirt and ID cards. Who doesn’t like an event Tee!

 

 

We had a tremendous response from the participants of the Drupal Camp. Valuebound had a booth where we saw a lot of participants register for an ongoing hiring process.

 

 

Drupal 8 was the main attraction for the booth since Valuebound only works with Drupal 8. Aaaaand! We are still HIRING. Find out more about opportunities with Valuebound. 

 

 

We had five sessions altogether in the camp, Rakesh James & Manoj Kumar presented sessions on How to start Contributions, PHPUnit for Drupal, Drupal 8 Migration and Creating Drupal 8 Modules using the Drupal Console. It was a jam-packed session (see the tweet below!) but unfortunately, we weren't there to click a pic :(

 

 

We also were a part of the CXO meeting - discussed how to improve the market share of Drupal, increase awareness for Drupal. CSI and Acquia to help promote FOSS and Drupal in colleges.

 

 

Meeting Vijay, the only Indian in the Drupal core maintainers list.

 

 

Awesome code-sprint, lots of participants and a room full of enthusiasm!

 

 

Photo-session after a great workshop with Rakesh and Manoj

 

 

We discussed bringing all Drupal Camps to once place or one umbrella to avoid clashes for the camp dates.

 

 

Meeting Sudheesh Sudhakaran from TCS, we had a long chat and discussed Drupal Camp Bangalore. Yes, it might be happening sooner than you think!

 

 

It was a great experience for us all and we look forward to being great hosts once again like the 2015 Bangalore Drupal Camp. We took with us a lot of inspirations, good works, great memories, a lot of pals, and ideas for more community contributions and Collaborations.

 

How to Sync Blocks Between different environments in a Drupal 8 website

A custom block is made of two entities, one for the placement and one for the actual content. Only the actual placement can be exported with cim. The content can not. Therefore this will result in "Block description Broken/Missing" error on site where the config is imported. And since there is no option to disable custom blocks from being exported through Configuration management, this will break the functionality.

Steps to reproduce

On Site A:

Create custom block

Assign this custom block to any region

Export configuration of the site

On Site B:

Import configuration from site A

Go to Block layout and you will see custom block in correctly assigned region, however block won't work or actually show anything.

Edit that block, you will see this messages:

Block description Broken/Missing

   This block is broken or missing. You may be missing content or you might need to enable the original module.

Go under Custom block library and you won't see custom block.

Block layout got exported but block content didn't resulting in broken relationship.

Block In Local Instance

In the above image a drupal block named “Block Content test” is added in content region in a local instance.

Block In Dev Instance

The above image shows that the block is missing after importing configuration using Drush command “drush cim”.

Way 1: Using Database Sync

  1. Create Custom Block in Site B.

  2. Replace db of Site A with Site B using drush sql-sync

  3. Now the block is available in Site A. So will place it in a region.

  4. Use drush cex to export config and commit to Site B.

  5. Use drush cim in Site B and the block will be placed in the region.

Way 2: Use Drupal drush functions to export config and hook_update_n & block uuid to update content.

  1. Create block B4 Test in Site A.

  2. Place the block in some region.

  3. Export using drush cex.

  4. Commit and run drush cim in site B

  5. Block error will be shown in Site B

  6. Write hook_update_n and  commit. Take Update in Site B and run update.php in Site B to add the block.

  7. Check Site B if the block is placed or not.

We have used Drush Commands “drush cex” to export block configurations and “drush cim” to import the configurations.

So Once drush cim is done in site B write a hook_update_N in your custom module's .install file use the block uuid to update the database of Site B.

After running update.php the block will be placed in the region

The first method can be used where the database size is less as it will take less time to sync the database. The 2nd method can be used where the database size is huge.

Reference: https://www.drupal.org/node/2756331


Depending on the scenario we can use any one of the methods. In this blog I have explained the two methods which we can use for updating blocks from one environment to another.

How to build a simple form using AJAX in Drupal 8

Ajax is a script on the client side communicating asynchronously with the server without a complete page refresh.The best description I came across about Ajax as “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”

In our project, while creating a new account if we give the existing username, on submitting the page it will throw an error. But, instead of reloading the page, we can just update certain parts of DOM. This can be achieved using AJAX. So, here is the example how to implement this ajax in drupal 8 forms.

In order to build a simple form using AJAX in Drupal 8 , we created a form with Username field. Using ajax we are going to validate that field. To achieve this, create a custom module ajax_example it requires 3 files which are ajax_example.info.yml, ajax_example.routing.yml, src\Form\AjaxExampleForm.php. The steps were listed below, how to validate the text field using AJAX.

Step 1: Create .info.yml

Let's create a yml file. A yml file is a file that specifies the configuration for a file i.e., to store metadata information about the project

Step 2: Creating .routing.yml Let’s create a .routing.yml called ajax_example.routing.yml. Each route is defined as a machine name in the form of module_name.route_name

Step 3: Create AjaxExampleForm.php

Create a new file called AjaxExampleForm.php inside of src/Form/{AjaxExampleForm.php}.

getFormId() function is used to create a unique id to the form.

buildForm() function is used to create the form and it has a textfield to validate the username using #ajax. Drupal provides the property ‘#ajax’ to a form element in your form array, to trigger an Ajax response.

checkUserEmailValidation() is the callback function to handle the server side of the ajax event i.e., to check the user or email is already exists in the database or not.

Drupal provides user_load_by_name() function for getting the username and user_load_by_mail() function for getting the Email. To return commands, you need to set up an object of class Drupal\Core\Ajax\AjaxResponse and the addCommand method is used to add the individual command to it.

Step 4: Here is our Ajax output in drupal 8 Form. The main objective of this blog is to validate the existing username or email without reloading the page.

Ajax output in drupal 8 Form

In drupal 8, we can achieve this by using ‘#ajax’ attribute and return the ajax response using the object of the class Drupal\Core\Ajax\AjaxResponse and added the individual command using addCommand method with the object of the class Drupal\Core\Ajax\HtmlCommand to show the message.

So, in this article, we have see an example regarding AJAX, to just update certain part of DOM, instead of reloading the whole page.

How to use Configuration Split Module to Split Configurations in Drupal 8

The configuration Split module allows users to define sets of configuration that will get exported to separate directories when exporting and get merged together when importing.

  • Drupal split module depends on Config Filter for the integration with the import/export pipeline of the Drupal UI and drush.

  • It is possible to define in settings.php which of these sets should be active and considered for the export and import

                                Here are a few things that are considered configuration:

Configuration split exposes a configuration entity which controls what you want to split off. Currently, you can

 

  • Blacklist modules: Any configuration that this drupal split module owns will automatically be blacklisted too.
  • Blacklist configuration: settings or configuration entities. These will be removed from the activesync directory.
  1.  Download and Enable Drupal configuration split module :- drush en config_split -y
  2.  Go to configuration  -> Configuration Split settings

Configuration Split Setting

  • Click on 'Add configuration split'. Naming is important, so we'll enter 'Dev split' as the name for this configuration. We'll also create a directory called 'sync-dev-split'. (where the config file will go from activesync directory)
  • Select Module’s from which configuration file (yml files ) will get split into another folder in root directory of your module .

Configuration Split Setting

  • There is an status Option which should be active (Checked)
  • Save

3. Doing exports and imports on dev or live .

From now on, if you want to import new settings whether it's on your dev or live environment, you can not use the drush core commands anymore. Use following commands: Go to Terminal 

A) Export your configuration in other folder

  • drush csex dev_split
  • sync-dev-split
  • Y/N option will be there =>Y
  • List of yml files => ls sync-dev-split
  • # to export on your dev environment ->    @dev:/home/drupal/drupal-core$ drush csex dev_split
  • # to export on your live environment ->     @live:/home/drupal/drupal-core$ drush csex live_split

B) Import Your configuration

  • In local -> drush csim dev_split
  • In dev site - drush @pantheon.config-split.dev csim dev_split
  • # to import on your dev environment ->    @dev:/home/drupal/drupal-core$ drush csim dev_split
  • # to import on your live environment ->    @live:/home/drupal/drupal-core$ drush csim live_split

                                                                                    OR

C) You can directly Import your Configuration

Go to Configuration-> Configuration Synchronization - If you have added multiple split config settings, then it will be shown like this in Configuration Synchronization

Synchronize Configuration Setting

There you can see Multiple Split configuration option like dev split & live Split

If you want to use “Dev split” go to your settings.php file

  • $config['config_split.config_split.dev_split']['status']= TRUE;
  • $config['config_split.config_split.live_split']['status']= False;
  • $config['config_split.config_split.test_split']['status']= False;

Result :

Synchronize Configuration Setting

References :

How to Create Configurable Block programmatically In Drupal 8

Blocks are the boxes of content that can be displayed in regions like sidebar first, sidebar second, content. This functionality is provided by the Block module in drupal 8. Here describing to creating Configurable Block programmatically in drupal 8 by using the drupal console.

Configurable Block module & skeleton files created by following drupal console commands:

$drupal generate: module

Generate_Module

By using drupal console to generate configurable block module it create configure_block.info.yml file like,

structure_info_file

Configure_block.info.yml file contain the following information:

info.yml_file
The .info.yml file contains metadata about the project like the name of the project (configure_block), type (module), description (This is an example of configurable block programmatically in drupal 8), core (8.x), packages (Custom) and dependencies etc.

 

Next, we need to create a plugin for Block Module. Create folder Plugin under src, create Block folder under Plugin then create DefaultBlock.php file under Block folder.

  • The path should be /src/Plugin/Block/DefaultBlock.php

(or)

Next, we need to generate Block module using following drupal console command,

 

$drupal generate:plugin:block

generate_plugin_block

After generated configurable block module by using drupal console, it should be like,

 

structure_plugin_block

 

The Configurable block module Skeleton in drupal 8 is like this:

  • module/custom/configure_block/src/Plugin/Block/DefaultBlock.php
  • module/custom/configure_block/configure_block.info.yml

where configure_block is a module name for our custom configurable block. The plugin of configurable block module file will have following code where we are defining our configurable fields in drupal 8.

 

DefaultBlock.php:

 

Here we take three fields of the configurable block which are hello_block_name, mobile_number and address. The message is to be displayed, based on what you enter in those fields of block module in drupal 8.

 

Next, install your configurable block module in drupal 8.

 

Goto

Extend >select install module>select your module name>click install.

install_block

 

Next place the configurable Block module in any regions are presented in drupal 8.

 

Goto

      Structure>Block Layout>click place block icon>select your block name>select region>save block.

Goto

    Configuration block>enter in the following field what you need to display output.

 

Configure_Block

Then go to the main page,

 

Configurable block Module displayed in some region (selected region example: sidebar second). It shows following output.

 

final_output

 

I hope this was helpful in getting you started with Custom configurable block in Drupal 8.


Reference: https://github.com/munavlakshmi/create-configure-block-in-drupal-8

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