Drupal 8 Custom Block Module

By | January 12th 2019 11:25:11 AM | viewed 109 times

Create a folder usercount8 in the location:projectname/modules/ or projectname/modules/custom/

Create a file usercount8.info.yml in the location:projectname/modules/usercount8/ and add tho following code

name: User Count
type: module
description: Defines a custom block.
core: 8.x
package: WebWash
libraries:
  - 'my_block_example/global-style'
  - 'my_block_example/global-scripts'
dependencies:
  - block
 

Note:After colon must use one space(like name:space User Count),any para after colon must start after two space(like after libraries colon new para start with space space-space'my_block_example/global-style'). it is important for every .yml file

Create a file usercount8.libraries.yml in the location:projectname/modules/usercount8/ and add tho following code

global-scripts:
  version: VERSION
  js:
    js/jquery-1.7.2.js: {}
global-style:	
  css:
    theme:
      css/demos.css: {}

Create a file MyBlock.php in the location:projectname/modules/usercount8/src/Plugin/Block/ and add the following code

 <?php

/**
 * Provides a 'My Block Example' Block
 *
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 * )
 */

namespace Drupal\usercount8\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a 'User Count Block' with a simple text.
 *
 * @Block(
 *   id = "user_count",
 *   admin_label = @Translation("User Count Block"),
 * )
 */
class MyBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
   public function build() {
   
	    $result = db_select('users')
		 ->fields('users')
		 ->execute();
	    $count = count($result->fetchAll());
	    $form = array();

		$form['table'] = array(
		        '#prefix' => ''
		    );
		
		return $form;
}
  
   
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }

  
 public function blockForm($form, FormStateInterface $form_state) {
           //$form = \Drupal::formBuilder()->getForm('Drupal\brandinfo8\Form\BrandForm');
           //return $form;
       $form[] = null;
       return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
       $form_state->getValue('form_field');
	   return true;
  }
}

 

Note: In the above @Block annotation is important for block module naming

Add necesary css, js files in the location:projectname/modules/usercount8/css/,projectname/modules/usercount8/js/

Login the as administrator and go to extention-> module-> install them to go structure->block layout-> region->place block->search block by name and select and save

bONEandALL