How to create custom VBO (Views Bulk Operation)

Step 1: Implement hook_action_info

/**
* Implementation of hook_action_info().
*/
function example_action_info() {
return array(
'example_action' => array(
'label' => t('Example'),
'type' => 'user',
'configurable' => FALSE,
'triggers' => array('any'),
),
);
}

Step 2: Implement your action

/**
* Action function for example_action.
*/
function example_action(&$entity, $context = array()) {
// Your code here
}

If you want to add form in your custom VBO then follow the below steps:

Step 3: Change configurable setting

'configurable' => TRUE,

Step 4: Implement action form

/**
* Action form function for example_action.
*/
function example_action_form($context) {
$form['group_name'] = array(
'#type' => 'textfield',
'#title' => t('Group Name'),
'#size' => 50,
'#maxlength' => 128,
'#required' => TRUE,
);
return $form;
}

/**
* Action form validation function for example_action.
*/

function example_action_validate($form, $form_state) {
if (!$form_state['values']['group_name']) {
form_set_error('group_name', t('You should put group name.'));
}
}


/**
* Action form submit function for example_action.
*/
function example_action_submit($form, $form_state) {
return array('group_name' => $form_state['values']['group_name']);
}

Use Link instead l() in Drupal 8

l() and url() are removed in favor of a routing based URL generation API

\Drupal::l has been deprecated (as of Drupal 8.0.0). Use \Drupal\Core\Link instead.

use Drupal\Core\Link;
use Drupal\Core\Url;

// Internal URL
$url = Url::fromRoute(‘test.hello’);
$link = Link::fromTextAndUrl(t(‘Test URL’), $url)->toString();

// External URL
$url = Url::fromUri(‘https://somansarker.wordpress.com’);
$link = Link::fromTextAndUrl(t(‘Test URL’), $url)->toString();

Switch php version in ubuntu

##From PHP 5.6 => PHP 7.1

Default PHP 5.6 is set on your system and you need to switch to PHP 7.1. Run the following commands to switch for Apache and command line.

#Apache:-

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1
$ sudo service apache2 restart

#Command Line:-

$ sudo update-alternatives –set php /usr/bin/php7.1
$ sudo update-alternatives –set phar /usr/bin/phar7.1
$ sudo update-alternatives –set phar.phar /usr/bin/phar.phar7.1

==================================

##From PHP 7.1 => PHP 5.6

Default PHP 7.1 is set on your system and you need to switch to PHP 5.6. Now run the following commands to switch for Apache and command line.

#Apache:-

$ sudo a2dismod php7.1
$ sudo a2enmod php5.6
$ sudo service apache2 restart

#Command Line:-

$ sudo update-alternatives –set php /usr/bin/php5.6
$ sudo update-alternatives –set phar /usr/bin/phar5.6
$ sudo update-alternatives –set phar.phar /usr/bin/phar.phar5.6

Drupal 8 services

1. Create a file /modules/custom/mymodule/mymodule.services.yml and paste the below code:

services:
mymodule.test_first_service:
class: Drupal\mymodule\Service\TestFirstService
arguments: [‘@current_user’]

3. Create a file /modules/custom/mymodule/src/Service/TestFirstService.php and paste the below code:

namespace Drupal\mymodule\Service;
use Drupal\Core\Session\AccountInterface;

class TestFirstService {

private $currentUser;
private $rand_number = [1, 2, 3, 4, 5];

/**
* Part of the DependencyInjection magic happening here.
*/
public function __construct(AccountInterface $currentUser) {
$this->currentUser = $currentUser;
}

/**
* Returns a a Drupal user as an owner.
*/
public function whoIsYourOwner() {
return $this->currentUser->getDisplayName();
}

/**
* Returns a random number.
*/
public function getRandNum() {
return $this->rand_number[array_rand($this->rand_number)];
}

}

3. Execute the below code form devel:

$our_service = \Drupal::service(‘mymodule.test_first_service’);

$user_name = $our_service->getDisplayName();
ksm($user_name);

$rand_num = $our_service->getRandNum();
ksm($rand_num);

Drupal 8 block users

$result = \Drupal::entityQuery(“user”)
->condition(‘login’, strtotime(‘-6 months’), ‘execute();

$storage_handler = \Drupal::entityTypeManager()->getStorage(“user”);

foreach ($result AS $user) {
$entity = $storage_handler->load($user);
$entity->block();
$storage_handler->save($entity);
}

Drupal 8 update user programmatically

use Drupal\user\Entity\User;

// $uid is the user id of the user
$user = User::load($uid);

// Update password
$user->setPassword($password);

// Update email
$user->setEmail($mail);

// Update username
$user->setUsername($username);

// The crucial part! Save the $user object, else changes won’t persist.
$user->save();

Drupal 8 Create a new user

Create a new user:

use Drupal\user\Entity\User;
/**
* Helper function to create a new user.
*/
function create_new_user(){
$user = User::create();

//Mandatory settings
$user->setPassword(”);
$user->enforceIsNew();
$user->setEmail(”);

//This username must be unique and accept only a-Z,0-9, – _ @ .
$user->setUsername(”);

//Optional settings
$language = ‘en’;
$user->set(“init”, ’email’);
$user->set(“langcode”, $language);
$user->set(“preferred_langcode”, $language);
$user->set(“preferred_admin_langcode”, $language);
$user->activate();

//Save user
$user->save();
drupal_set_message(“User with uid ” . $user->id() . ” saved!\n”);
}

Drupal 8 Simple Form Example

1. Create a info file your_proejct/modules/custom/module_name.info.yml and paste the below code:

name: ‘module_name’
type: module
description: ‘Form Example’
core: 8.x
package: ‘Custom

2. Create a routing file your_proejct/modules/custom/module_name.routing.yml and paste the below code:

module_name.simple_form:
path: ‘/simple-form’
defaults:
_form: ‘\Drupal\module_name\Form\SimpleForm’
_title: ‘Simple Form Example’
requirements:
_permission: ‘access content’

3. Create a form class file your_proejct/modules/custom/module_name/src/Form/SimpleForm.php and paste the below code:

namespace Drupal\module_name\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
* Implements a simple form.
*/
class SimpleForm extends FormBase {

/**
* Build the simple form.
*
* @param array $form
* Default form array structure.
* @param FormStateInterface $form_state
* Object containing current form state.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$var = \Drupal::state()->get(‘test_first_var’, ”);

$form[‘title’] = [
‘#type’ => ‘textfield’,
‘#title’ => $this->t(‘Title’),
‘#description’ => $this->t(‘Title must be at least 15 characters in length.’),
‘#required’ => TRUE,
‘#default_value’ => $var,
];

// Group submit handlers in an actions element with a key of “actions” so
// that it gets styled correctly, and so that other modules may add actions
// to the form. This is not required, but is convention.
$form[‘actions’] = [
‘#type’ => ‘actions’,
];

// Add a submit button that handles the submission of the form.
$form[‘actions’][‘submit’] = [
‘#type’ => ‘submit’,
‘#value’ => $this->t(‘Submit’),
];

return $form;
}

/**
* Getter method for Form ID.
*
* The form ID is used in implementations of hook_form_alter() to allow other
* modules to alter the render array built by this form controller. it must
* be unique site wide. It normally starts with the providing module’s name.
*
* @return string
* The unique ID of the form defined by this class.
*/
public function getFormId() {
return ‘test_simple_form’;
}

/**
* Implements form validation.
*
* The validateForm method is the default method called to validate input on
* a form.
*
* @param array $form
* The render array of the currently built form.
* @param FormStateInterface $form_state
* Object describing the current state of the form.
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$title = $form_state->getValue(‘title’);
if (strlen($title) setErrorByName(‘title’, $this->t(‘The title must be at least 15 characters long.’));
}
}

/**
* Implements a form submit handler.
*
* The submitForm method is the default method called for any submit elements.
*
* @param array $form
* The render array of the currently built form.
* @param FormStateInterface $form_state
* Object describing the current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
/*
* This would normally be replaced by code that actually does something
* with the title.
*/
$title = $form_state->getValue(‘title’);

\Drupal::state()->set(‘test_first_var’, $title);

drupal_set_message($this->t(‘You specified a title of %title.’, [‘%title’ => $title]));
}

}

4. Enable the module and clear cache.
5. Browse http://your-project/simple-form

Drupal 8 State API

The state API is a simple system to store this information, which previously would have been stored in the variables system.

Typical usage:

Get a value:
$val = \Drupal::state()->get(‘key’);

Get multiple key/value pairs:
$pairs = \Drupal::state()->getMultiple($keys);

Set a value:
\Drupal::state()->set(‘key’,’value’);

Set multiple values:
\Drupal::state()->setMultiple($keyvalues);

Delete a value:
\Drupal::state()->delete(‘key’);

Note: Drupal 8 removed drupal_get, drupal_set, drupal_del so we can use state API.

Drupal 8 create a block programmatically

1. Create a file FirstTestBlock.php file under modules/custom/module_name/src/Plugin/Block

2. Copy and paste the below code.

namespace Drupal\module_name\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
* Provides a ‘FirstTestBlock’ block.
*
* @Block(
* id = “first_test_block”,
* admin_label = @Translation(“First test block”),
* )
*/
class FirstTestBlock extends BlockBase {

/**
* {@inheritdoc}
*/
public function build() {
$build = [];
$build[‘first_test_block’][‘#markup’] = ‘Implement FirstTestBlock.’;

return $build;
}

}

3. Clear drupal cache.