Get the configuration setting in drupal 8

In drupal 8 we can get any of the configuration setting

$config =\Drupal::service(‘config.factory’)->get(‘module.settings’);
$form_mode_settings = $config->get(‘key’);

This will get you an array of your configuration settings

Advertisements

Age Validation with dob in Drupal 8

I was been given a situation where there was 2 fields one was cateogry and another was date-of-birth.

So the cateogry was dropdown consists of 4 options OBC ,General ,ST and SC.

The age should be between 35 to 45 for General and OBC and 35 to 48 for ST and SC.

So i have written some code in drupal 8 for age validation.

created a .module file and witten the below code which validates

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function modulename_form_alter(&$form, FormStateInterface $form_state, $form_id) {
 if($form_id == "your-form-id"){
     $form['#validate'][] = 'dob_form_validate';
 }
}

function dob_form_validate($form, FormStateInterface &$form_state) {
 $dob = $form_state->getValue('field_date_of_birth');
 if(isset($dob)){
   $birthDate = $dob[0]['value']->format('Y-m-d');
   $birthDate = new DateTime($birthDate);
   $to = new DateTime('2016-01-31');
   $age = $birthDate->diff($to);
   $years = $age->y;
   $months = $age->m;
   $days = $age->d;
 }
 $cateogry = $form_state->getValue('field_ap_category');
 if(isset($cateogry)){
  $cat = $cateogry[0]['value'];
  if($cat == "BC 1" || $cat == "BC 2" || $cat == "General"){
    if($years == 45 && ($months > 0 || $days>0))
    {
      $form_state->setErrorByName('field_ap_date_of_birth', t('Age must be between 35 and 45 for General and BC'));
    }
    else if($years < 35 || $years > 45 ){
      $form_state->setErrorByName('field_ap_date_of_birth', t('Age must be between 35 and 45 for General and BC'));
    }
  }
  else if($cat == "SC" || $cat=="ST"){
    if($years == 48 && ($months > 0 || $days>0))
    {
      $form_state->setErrorByName('field_ap_date_of_birth', t('Age must be between 35 and 48 for SC and ST'));
    }
    else if($years < 35 || $years > 48){
      $form_state->setErrorByName('field_ap_date_of_birth',t('Age must be between 35 and 48 for SC and ST'));
    }
  }
 }
}

Custom Submit handler in drupal 8

If we want to create our  custom submit handler to submit a form then we can easily use the below code

use Drupal\Core\Form;
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if($form_id == 'node_newmodule_form'){
    foreach (array_keys($form['actions']) as $action) {
     if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
       $form['actions'][$action]['#submit'][] = 'custom_form_submit';
     }
    }
  }
}

public function custom_form_submit(&$form, FormStateInterface $form_state){
   echo "It will invoke";
}

So we can easily choose which form id to invoke this submit handler.
The custom function custom_form_submit will be envoke when we submit the following form id

Drupal 8 Hooks hook_element_info_alter()

There are many hooks in drupal 8

So i will list the most important hooks which i have used so far

hook_element_info_alter()

Alter the element type information returned from modules.

A module may implement this hook in order to alter the element type defaults defined by a module.

example code:

function hook_element_info_alter(&$type) {
  // Decrease the default size of textfields.
  if (isset($type['textfield']['#size'])) {
    $type['textfield']['#size'] = 40;
  }
}

function mymodule_element_info_alter(array &$types) {
  //call the custom function after build.
  foreach ($types as $type => $info) {
    $types[$type]['#after_build'][] = 'my_custom_function';
  }
}

This hook is mainly used to alter the elements so $type contains all the elements.

 

Important Services in drupal 8

$contentTypes = \Drupal::service('entity.manager')->getStorage('node_type')->loadMultiple();

It will list all the content types of your current project.
It is very useful to call service(‘entity.manager’);

$type = $contentTypes->label();

This will get the Name of content type.

$type = $contentTypes->id();

This will get the slug of content type. Means the content type machine name

$form_modes = \Drupal::service('entity_display.repository')->getFormModes('node');

This will get the list of all content type form mode in current project

$form element with #type => ‘submit’ with custom submit and validate function

$form[‘copy_local’] = [
‘#type’ => ‘submit’,
‘#prefix’ => ‘<br>’,
‘#name’ => ‘public’,
‘#value’ => $this->t(‘Copy local public files to S3’),
‘#validate’ => [
[$this, ‘copyLocalValidateForm’],
],
‘#submit’ => [
[$this, ‘copyLocalSubmitForm’],
],
];

public function copyLocalValidateForm(){

//Code Here

}

When we click on this submit button then the #validate is called first and the #submit.It will check for the custom method in same class and then call that method.

 

 

 

 

 

Drupal 8 userful functions in users

$role_names = user_role_names();

It returns array of all the user roles like anonymous,authenticated,admin.

To check whether a username exists or email exists then drupal 8 provide the below functions to check

$username = “Mahtab”

$hasUsername = user_load_by_name($username);

the $hasUsername will return true or false, the same we can check for email by

$hasEmail = user_load_by_mail($email);

To get the current user id

$user = \Drupal::currentUser();
$uid = $user->id();