Thursday 20 December 2018

How to add custom js file in custom module in drupal 8 ?

It is very simple way to add custom JQuery file in custom module, but we have few methods for this.

Method 1: Our custom libraries(js/css) will be apply on all pages of project.
If we want to add custom js file in whole pages of project then we have to use this method.

1. First we have to create js file like 'gallery.js' file in js folder in our custom module.
2. Then we have to create a 'hook.libraries.yml' file means there hook will be module name.
     
Example: Suppose our Module name will be 'gallery' So we will create file with name of     'gallery.libraries.yml' in custom module folder means this file should be placed with '.routing.yml' file.
3. The code for '.libraries.yml' file is..

image_gallery:
  version: 8.4.5
  js:
    js/gallery.js: {}   
  dependencies:
    - core/jquery
  css:
    theme:
      css/gallery.css: {}


Note: There is a library called image_gallery that when included in a page will deliver the 'js/gallery.js' and 'css/gallery.css' file.

4. Then we have to create '.module' file.

Example: Suppose our Module name is gallery so file name will be 'gallery.module'. There our code for attachment of this library to our module is..

<?php
function gallery_page_attachments(array &$attachments) {
   $attachments['#attached']['library'][] = 'gallery/image_gallery';
}
?>

5. Here 'gallery/image_gallery' means 'module name/libraries name' and in the time of controller function return of page will be written like..
return array('#markup' => t($html)); // here $html is return the result for page.   

Method 2: Our custom libraries(js/css) will be apply only on custom module pages of project.  
1. Whole process and file creation will be same but we will not use attachments code in '.module' file.
2. In this case we just have to create '.libraries.yml' file and apply code..

image_gallery:
  version: 8.4.5
  js:
    js/gallery.js: {}   
  dependencies:
    - core/jquery
  css:
    theme:
      css/gallery.css: {}

     
3. Then in the time of controller function return of page will be written like..
   
return [
    '#markup' => t($html),
    '#attached' => array(
        'library' => array(
            'gallery/image_gallery',
        ),
    ),
];       


here 'gallery/image_gallery' means 'module name/libraries name' and '$html' is the written result for page.

Note: If have any suggestions or issue regarding 'How to add custom js file in custom module in drupal 8 ?' then you can ask by comments.   

Wednesday 12 December 2018

How to disable or hide or exclude the cache from page in drupal 8 ?

Sometimes we want to face the issue that don't want to apply cache or disable cache for particular page on drupal 8. Here we have option that will help in that case and we are going to give an example with this.
First of all we want to show the name of Module that will help in that case that is "Cache Exclude" in drupal 8 or download by link "https://www.drupal.org/project/cacheexclude".
for this just install this module on project and go to the configure page of this module.

Cache Exclude




So juts put the page URL in that "Pages to exclude from caching" textarea as given example of `news`, we want to remove or disable cache from `news` page so put the URL here.
and Check the content type in "Content types to exclude from caching" that checklist. so that's the simple and effective process.

Note: If have any suggestions or issue regarding 'How to disable or hide or exclude the cache from page in drupal 8 ?' then you can ask by comments.   

Tuesday 11 December 2018

How to use country timezone in our Twig file ?

If we want to change the 'DATE' filter in you TWIG file, its easy to use Timezone.
here is the good example for this issue.

Example:
{{ "now"|date("m/d/Y H:i", "Europe/Paris") }}  //For Europe Paris region timezone
{{ "now"|date("m/d/Y H:i", "Asia/Calcutta") }}  //For Asia Calcutta region timezone
{{ "now"|date("m/d/Y H:i", "Europe/Berlin") }}  //For Europe Berlin region timezone

So same like we can use for other countries region time in our TWIG file.


Note: If have any suggestions or issue regarding 'How to use country timezone in our Twig file ?' then you can ask by comments.  

Monday 12 November 2018

How to add JS file using theme file in Drupal 8 ?

Sometimes we add Jquery file by libraries.yml but if we want to add JS file by `.theme` file in drupal 8 so we will add <script> code in `hook_page_attachments_alter`.
There we will create a variable and put the script code and then add in $page['#attached']['html_head'][].
We will add #tag is script and pass the script code variable using this code of line..

\Drupal\Core\Render\Markup::create($javascript_header)
 
here $javascript_header is our script code variable.

Example:
<?php
function hook_page_attachments_alter(array &$page) {   
   
$javascript_header = 'var hmt = hmt || [];
(function()
{
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?1236547890";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);
}
 )();';
        $page['#attached']['html_head'][] = [       
            [       
              '#tag' => 'script',         
              '#value' => \Drupal\Core\Render\Markup::create($javascript_header),       
              '#weight' => -1,
            ],       
            'key'
        ];
   
}
?>
So this is simple way to add JS file in header of project of Drupal 8.

Note: If have any suggestions or issue regarding 'How to add JS file using theme file in Drupal 8 ?' then you can ask by comments.  

Monday 29 October 2018

How to send email programmatically in Drupal 8?

Sometime we need to send email on any events or after creation of blog or article or in any e-commerce site for send confirmation mail after successful completion of order. So In this Blog we are going to explore how to send email programmatically in drupal 8.
We just have to use `hook_mail` function in '.module' file. here two simple steps for send email:

1. Define your properties like Subject, body, headers etc in hook_mail() function.
2. Use Mail Manager to send email.

When we need to send email programmatically, we need to specify the module name that implements hook_mail().
Now have a look of implementation.

<?php

/**
 * Implements hook_mail().
 */

function [module_name]_mail($key, &$message, $params) {
    $options = array(
        'langcode' => $message['langcode'],
    );
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
    switch ($key) {
        case 'create_event':
            $message['from'] = \Drupal::config('system.site')->get('mail');
            $message['subject'] = t('Notification: @subject', array('@subject' => $params['subject']), $options);
            $message['body'][] = SafeMarkup::checkPlain($params['message']);
            break;
    }
}
?>

Here $key is defines one template identified as test_message.
The two other arguments are $params and $message. here $parms is an array of data that needs to go in the email and that is passed from mail manager.
So here is final step for send mail via `mailManager`.

<?php
/**
* Implements hook_entity_insert().
*/

function [module_name]_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
    if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'event')) {
      return;
    }   
    $user_email = \Drupal::currentUser()->getEmail();
    $key = 'create_event';
    $module = <module_name>;
    // mail sending to reviewer users
    $msg1 = "Hello, <br /><br />";
    $msg1.= "Please check your content item, that is published by publisher.";
    $msg1.= "Kind regards";

    $mailManager = \Drupal::service('plugin.manager.mail');
    $to = $user_email;
    $params['message'] = t($msg1);
    $params['subject'] = "Project name workflow for published Notification.";
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $send = true;

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);   

    if ($result['result'] !== true) {
      drupal_set_message(t('There was a problem sending your message.'), 'error');
    }
    else {
      drupal_set_message(t('Your message has been sent.'));
    }   
}
?>

By default, PHPMail, which is use for default_mail() function in PHP. So this will triggered whenever any event will be created, here
$send = the boolean value which is indicating whether the email should be actually sent or not.
$key = template id.


Note: If have any suggestions or issue regarding 'How to send email programmatically in Drupal 8?' then you can ask by comments.  
   

Friday 12 October 2018

How to upload file using URL in drupal 8 programmatically?

Here is a simple way to upload file either file or image by URL in drupal 8. We are going to give an example for this query.
Example: First we need an url like..
        $fileurl = $fileurlval->url;             
        $name = str_replace(' ', '-', strtolower($meta_title).'.pdf');   //here meta_title is the name of your pdf or image
       
        //Get the uploaded file from the url.  
        $filedata = file_get_contents($fileurl);
       
        //Saves a file to the specified destination and creates a database entry.
        $file_directory_name = 'images'; // it means  upload folder name  
        $uploaded_file = file_save_data($filedata, "public://".$file_directory_name."/".$name, FILE_EXISTS_RENAME);
       
        // here "public://" means 'sites/default/files/' folder..
        // here $file_directory_name means we can set any folder where we want to upload..
        // here $name is name of file name..
                           
        if (!empty($uploaded_file)) { 
            $file_arr = array(
                "target_id" => $uploaded_file->id(),
                 "alt" => $uploaded_file->getFilename(),
            );       
       
            $node->field_resources_asset_tagging = $file_arr; // here field_resources_asset_tagging is file field..       
        }

So this is the way to upload file/image in drupal 8 programmatically.  


Note: If have any suggestions or issue regarding 'How to upload file using URL in drupal 8 programmatically?' then you can ask by comments.  
   

Thursday 4 October 2018

How to remove or unset META tag from web page?

If we want to hide or unset or remove META Tag from our web page then we have to use `hook_page_attachments_alter` in `.theme` file.
we have to create an array and pass the name of `META name` which we want to remove or unset from web page.
like..
$unset_meta = [
    'title', // Meta name "title"
    'description', // Meta name "description"
    'keywords', // Meta name "keywords"
    'Generator'     // Meta name "Generator"
];

then with the help of $page['#attached']['html_head'], page attachments html_head we have to check that meta name if exist then we have to unset this.
we are giving here an example for this..

Example:
function moldev_page_attachments_alter(array &$page) { // here moldev is my theme name.
 // Define an array of META tags to remove.
   $unset_meta = [
    'title', // Meta name "title" 
    'description', // Meta name "description"
    'keywords', // Meta name "keywords"
    'Generator'     // Meta name "Generator"   
   ];
  // Check values and delete.
   foreach ($page['#attached']['html_head'] as $key => $value) {
     if (in_array($value[1], $unset_meta)) unset($page['#attached']['html_head'][$key]);
   }
}

if you want to delete/remove/unset any link rel="alternate" and hreflang="en" or any language then follow the below given code.
foreach ($page['#attached']['html_head_link'] as $key => $attachment) {   
          if ($attachment[0]['rel'] == 'alternate' && $attachment[0]['hreflang'] == 'en') {
               unset($page['#attached']['html_head_link'][$key]);
          }
}

Note: If have any suggestions or issue regarding 'How to remove or unset META tag from web page?' then you can ask by comments.  

How to resolve max execution time error in drupal ?

When you found error regarding 'max_execution_time' exceed, then you can follow steps for resolve this error: Steps:   You can put t...