Drupal

/** 
* Get current loged user's roles
*/ 
$current_user = \Drupal::currentUser(); 
$roles = $current_user->getRoles();
 //Will return an array like this:
 Array (
 [0]=> authenticated,
 [1]=> administrator,
 [2]=> editor,
 [3]=> developer 
);

 

 

Submitted by : admin
on Thu, 07/12/2018 - 09:01

What is drupal behaviors ?
Drupal behaviors allow to execute javascpts in particular context and / or pass data from drupal to client side java script.

/** 
* Implements hook_js_settings_alter(). 
* @inheritdoc 
*/ 

function custom_module_js_settings_alter(array &$settings, 
\Drupal\Core\Asset\AttachedAssetsInterface $assets) {

 $settings['custom_module']['text'] = "The text";
 
}
Submitted by : admin
on Wed, 07/11/2018 - 21:13

Entity query without changing user session

$query = \Drupal::entityQuery('node');
$query->condition(DOMAIN_ACCESS_FIELD, 'domain_id');// Set the domain id hear 
$query->condition('type', 'article'); 
$query->condition('status', 1);
$nids = $query->execute(); 
echo '<pre>';print_r($nids);echo '</pre>';// return all node type article

    Entity query using user session (admin session) 

    Submitted by : admin
    on Fri, 08/17/2018 - 22:09

    custom_module.routing.yml

    custom_module.form.page:
      path: '/custom-form'
      defaults:
        _form: '\Drupal\custom_module\Form\CustomModuleForm'
        _title: 'Custom Form'
      requirements: 
        _permission: 'access content'

     

    CustomModuleForm.php

    <?php

    /**
     * @file
     * Contains \Drupal\custom_module\Form\CustomModuleForm.
     */

    namespace Drupal\custom_module\Form;

    Submitted by : admin
    on Tue, 07/31/2018 - 08:47

    Create custom form

    namespace Drupal\mymodule\Form;

    use Drupal\Core\Form\FormBase;

    use Drupal\Core\Form\FormStateInterface;

    class ExampleForm extends FormBase {

    public function getFormId() {

    Submitted by : admin
    on Tue, 07/31/2018 - 08:32
    $GLOBALS['user']->roles;
     or 
    global $user; 
    $check = array_intersect(array('authenticated user', 'administrator'), array_values($user->roles)); 
    
    if (empty($check) ? FALSE : TRUE) { 
    	// is admin
    } else {
     	// is not admin 
    } 
    

     

    Submitted by : admin
    on Thu, 07/26/2018 - 22:08