Create custom blocks - Drupal 8 Example

Blocks can be displayed in regions (such as footer or sidebar) on your page.

Here we will expand the functionality of “hello module” to provide a block and create a block that displays the information about the current user logged in user.

Before starting this example, assuming you have read our previous example  Create A Custom Module In Drupal 8.

In our example we will display some specific information about a user when  user logged In.

(a) UserName

(b) Language

(c) E-mail Address

(d) Time zone

(e) Account Creation date

(f) Account Updation date

(g) Last logged in date

(h) User assigned role

In a case in which user is not logged in, it means this user is a anonymous user.

So it will simply display date and time.

To understand block directory firstly we will create” plugins directory ” under “src” directory.

Blocks are also known as Plugin in drupal 8 so here create a new directory named as “ Block ” in the ” plugin directory” inside you hello world module.

The structure is given below :

hello \ src  \ Plugin \ Block

Create custom block folders in custom module drupal 8

Within the “Block directory“, we will create a new file named as “HelloBlock.php” file.

Custom block files

In ” HelloBlock.php ” file, add the following code.


<?php   

	//include block directory
	namespace Drupal\hello\Plugin\Block;
	
	//include blockbase class
	use Drupal\Core\Block\BlockBase;
	
	/**
	* Provides a user details block.
	*
	* @Block(
	* id = "hello_block",
	* admin_label = @Translation("Hello!")
	* )
	*/
	
	class HelloBlock extends BlockBase {
	
		/**
		* {@inheritdoc}
		*/
		
		//generating the block output.
		public function build() {
			
			return array(
			
					 //t()used for print value
					 '#markup' => $this->t("Hello World!"),
				);
		}
	}
?>

Place block in region

Upadated block plugin code is :


<?php

	//include hello block.
	namespace Drupal\hello\Plugin\Block;
	
	// include user entity to get user related objects
	use Drupal\user\Entity\User;
	

	//include blockbase class.
	use Drupal\Core\Block\BlockBase;
	
	/**
	* Provides a user details block.
	*
	* @Block(
	* id = "hello_block",
	* admin_label = @Translation("Hello!")
	* )
	*/
	
	class HelloBlock extends BlockBase {
		
			/**
			* {@inheritdoc}
			*/
			
			//retuns the output generated by populate_markup function
			public function build() {
				
				   return array(
				   
					  '#markup' => $this->_populate_markup(),
					);
			 } 
			        
			private function _populate_markup() {
				
				// Get current loged in user id and load user object    
				$user = User::load(\Drupal::currentUser()->id());
				
				// if user id <1 then its a guest user
				if ($user->get('uid')->value < 1) {
					
					//displays output with t().
					 return t('Welcome Visitor! The current time is: ' . date('m-d-Y h:i:s', time()));
					
				} else {
					
					$user_information = 'User Name: ' . $user->getUsername() . "<br/>";
					$user_information .= 'Language: ' . $user->getPreferredLangcode() . "<br/>";
					$user_information .= 'Email: ' . $user->getEmail() . "<br/>";
					$user_information .= 'Timezone: ' . $user->getTimeZone() . "<br/>";
					$user_information .= 'Created: ' . date('m-d-Y h:i:s', $user->getCreatedTime()) . "<br/>";
					$user_information .= 'Updated: ' . date('m-d-Y h:i:s', $user->getChangedTime()) . "<br/>";
					$user_information .= 'Last Login: ' . date('m-d-Y h:i:s', $user->getLastLoginTime()) . "<br/>";
					$roles = NULL;
					
					foreach($user->getRoles() as $role) {
						
							$roles .= $role . ",";
							
					}
									
					$roles = 'Roles: ' . rtrim($roles, ',');
								
					$user_information .= $roles;
					
					//returns user information.
					return $user_information;
			  }
		  }
	  
  }
?>

see output in dashboard :

Show custom block in website sidebar

Here  in the above code we have added a new function named as _populate_markup().

This function retrieves the current user information through the User :: load method.