How to get the currently logged in user's roles in Drupal 8

/** 
* 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 
);

 

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

How to use drupal behaviors on drupal 8?

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";
 
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Awesome Article

Submitted by admin on Mon, 10/08/2018 - 20:44

Where does it come from? 
Contrary to popular Wei. Lorern 1psum Is not ssmply random text. It 45 8C. ck, a Latin professor rr=s7ur:12fs)==ters'ir7roCsis'a Lorem Ipsum passage, Hampden-Sydney es-Sydney Co f gong through the cites of the woro in classical lileretu  to 
.10.33 of 'de Extremes of Good a. ExiS by Cicero...nes in 45 BC. Ttriri:bosoeict sections treatise on the theory of etni 
ar 

How to disable cache for a custom page with programmetically

If you want to disable cache for a custom controller (Custom module), You have no_cache option (module_name.routing.yml).

File : example_module.routing.yml

example_module.first_page:
  path: '/mymodule/mypage'
  defaults:
    _controller: '\Drupal\example_module\Controller\Pages::index'
    _title: 'No cache page'
  requirements:
    _access: 'TRUE'
  options:
    no_cache: 'TRUE'

Disable cache for a specific content type:

function example_module_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'content_type_name' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

Disable cache from a controller.

Note : This will work in no cache on page level (not working for anonymous users for example).

Set cache max age on rederer array.

$output = [];
$output['#cache']['max-age'] = 0;

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

How to search Entities when using Domain Access in drupal8?

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) 

    // Call the account switcher service
    $accountSwitcher = \Drupal::service('account_switcher');
    // Switch to the admin user
    $accountSwitcher->switchTo(new \Drupal\Core\Session\UserSession(['uid' => 1]));
    
    $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>';
    
    // Switch back to old session.
    $accountSwitcher->switchBack();

     

     

    Add new comment

    Plain text

    • No HTML tags allowed.
    • Lines and paragraphs break automatically.
    • Web page addresses and email addresses turn into links automatically.

    How to render a form in custom twig/template in drupal 8?

    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

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

    namespace Drupal\custom_module\Form;

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

    class CustomModuleForm extends FormBase {

        public function getFormId() {
            return 'custom_form';
        }

        public function buildForm(array $form, FormStateInterface $form_state,) {
              $form=array();
             $form['first_name'] = array(
                '#type' => 'textfield',
                '#title' => t('First Name'),
                '#required' => TRUE,         );

             $form['last_name'] = array(
                '#type' => 'textfield',
                '#title' => t('Last Name'), 
                '#required' => TRUE,
              );

              $form['email'] = array(
                '#type' => 'email',
                '#title' => t('Email'),
                '#required' => TRUE,

               );

               $form['submit'] = array(
                '#type' => 'submit',
                '#value' => $this->t('Submit'),
              );
              $form['#theme'] = 'custom_form';
            
            return $form;
        }

        public function validateForm(array &$form, FormStateInterface $form_state) {
            
        }

        public function submitForm(array &$form, FormStateInterface $form_state) {
            
        }   

    }

    custom_module.module 

    /**

    * Implplements hook_theme().

    */

    function custom_module_theme(){

    }

    custom-form.html.twig 

    {{ form.form_build_id }}
    {{ form.form_token }}
    {{ form.form_id }}
    {{ form.tags_fieldset }}


        {{ form.first_name }}


        {{ form.last_name }}


        {{ form.email }}


        {{ form.submit }}


     

    Add new comment

    Plain text

    • No HTML tags allowed.
    • Lines and paragraphs break automatically.
    • Web page addresses and email addresses turn into links automatically.

    How to render form in drupal 8

    Create custom form

    namespace Drupal\mymodule\Form;

    use Drupal\Core\Form\FormBase;

    use Drupal\Core\Form\FormStateInterface;

    class ExampleForm extends FormBase {

    public function getFormId() {

    // Unique ID of the form. return 'example_form';

    }

    public function buildForm(array $form, FormStateInterface $form_state,$param=null) {

    // Create a $form API array.

    $form['phone_number'] = array(

    '#type' => 'tel',

    '#value' => $param,

    '#title' => $this ->t('Your phone number'),

    );

    $form['submit'] = array(

    '#type' => 'submit',

    '#value' => $this ->t('Save'),

    );

    return $form;

    }

    public function validateForm(array &$form, FormStateInterface $form_state) {

    // Validate submitted form data.

    }

    public function submitForm(array &$form, FormStateInterface $form_state) {

    // Handle submitted form data.

    }

    }

     

    Render Custom form

     

    $param = '612-123-4567';

    $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $param);

    Add new comment

    Plain text

    • No HTML tags allowed.
    • Lines and paragraphs break automatically.
    • Web page addresses and email addresses turn into links automatically.

    How to get the currently logged in user's role in Drupal 7?

    $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 
    } 
    

     

    Add new comment

    Plain text

    • No HTML tags allowed.
    • Lines and paragraphs break automatically.
    • Web page addresses and email addresses turn into links automatically.