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:



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)   {   $...