Showing posts with label drupal 8. Show all posts
Showing posts with label drupal 8. Show all posts

Friday 30 April 2021

What is the difference between upgrade and update in Drupal?

It's easy to understand, what is upgrade and update, please have a look.

Update: If Drupal gives minor change version like Drupal 8.0.1 to 8.2.0, so that is update.

Upgrade: If Drupal gives major changes version like Drupal 6 to Drupal 8 or from Drupal 7 to Drupal 8,  that is upgrade.


Note: If have any suggestions or issue regarding 'What is the difference between upgrade and update in Drupal?' then you can ask by comments. 


Wednesday 5 August 2020

How to remove HTTP headers from drupal 8?

Sometimes client requirement is to remove HTTP headers from the website. By default, in Drupal website X-Generator, X-Drupal-Dynamic-Cache and X-Drupal-Cache HTTP headers is HTTP headers.
If we want to hide to remove from view source of page.
We can use Drupal module "Remove HTTP headers"
That will remove easily… 
headers_to_remove:
  - 'X-Generator' 
  - 'X-Drupal-Dynamic-Cache'
  - 'X-Drupal-Cache'
  
Important Note: if you get any issue/error, you can use this patch.

1. Go to your module and find folder route file - src/EventSubscriber/RemoveResponseHeadersSubscriber.php
2. find this function -
class RemoveResponseHeadersSubscriber implements EventSubscriberInterface {
    
   public function removeResponseHeadersItem(FilterResponseEvent $event) {
     $response = $event->getResponse();
+    $config = $this->configFactory->get('remove_meta_and_headers.settings');
 
     // If TRUE, fire event to remove X-Generator from Response.
-    if (1 == $this->configFactory->get('response_header_x_generator')) {
+    if ($config->get('response_header_x_generator')) {
       $response->headers->remove('X-Generator');
     }
   }

OR check this patch link…

   

Note: If have any suggestions or issue regarding 'How to remove HTTP headers from drupal 8?' then you can ask by comments. 

Monday 29 June 2020

How to protect file from public access in Drupal 8?

If we don't want to show any file or folder to 'Anonymous user', 'Authenticated user' then we have 2 options.

1. We can set the 'Permission' for this file or folder.
2. If we are using Pantheon server then we have 'pantheon.yml' file on root.
Write the code there.

protected_web_paths:
  - /web.config
  - /core/package.json

And this way easily we can protect our file or folder from unknown users.



Note: If have any suggestions or issue regarding 'How to protect file from public access in Drupal 8?' then you can ask by comments. 

Sunday 28 June 2020

How to set the flood limit in Drupal 8?

Sometimes, we get the flood of Unlimited attempts of login fail message, block user, block IP. In that case our website handle unwanted extra data, extra burden on database that is not good for our website health.
So what we have to do, in Drupal 7, we have module that name is "Flood control" https://www.drupal.org/project/flood_control

But in Drupal 8 we don't have that module, So many times we get the error message that is very famous: "Login blocked after 5 failed login attempts".
In that case or if we want to overcome this problem Drupal 8 we have solution, we are going to share:

Code for Flood limit change:

$flood_limit = 5;                 //Default value is 5, change whatever you want. 
// for login form
\Drupal::configFactory()->getEditable('login.settings')
      ->set('flood.limit', $flood_limit)
      ->save();
// for contact form
$flood_limit = 5;                //Default value is 5, change whatever you want. 
\Drupal::configFactory()->getEditable('contact.settings')
      ->set('flood.limit', $flood_limit)
      ->save();   
  
Code for Flood interval change:

// for login form
$flood_interval = 3600;      //Default value is 3600sec (1hour), change whatever you want
 \Drupal::configFactory()->getEditable('login.settings')
      ->set('flood.interval', $flood_interval)
      ->save();
// for contact form
$flood_interval = 3600;     //Default value is 3600sec (1hour), change whatever you want
 \Drupal::configFactory()->getEditable('contact.settings')
      ->set('flood.interval', $flood_interval)
      ->save();   

  
Important Notice: Put this code in custom module or template or theme file.

Or we can use 'settings.php' option for this code
$flood_limit = 10;
$config['login.settings']['flood']['limit'] = $flood_limit; 

And another we have a module in drupal 8, we can use this and all this code feature is there. Please find this "Flood settings" module. https://www.drupal.org/project/flood_settings 
Note: If have any suggestions or issue regarding 'How to set the flood limit in Drupal 8?' then you can ask by comments.  

Saturday 27 June 2020

How to check log error messages in Drupal 8?

As we know about log messages in Drupal, Log messages are our project related, every user related track (error, notice, warning, failure, PHP issue). In our Drupal we can check that track with URL '/admin/reports/dblog'.



And if we create a custom Module and we want to track every event of module, every time activity that we can write that code in this module.

Logs with an arbitrary level:
\Drupal::logger('module_name')->log($message); //When a module was installed

Normal but significant events:
\Drupal::logger('module_name')->notice($message); //Normals events, as cron execution

Exceptional occurrences:
\Drupal::logger('module_name')->warning($message); //exceptional cases not an error

Errors:
\Drupal::logger('module_name')->error($message); //error messages

And If we have requirement that we want to track this log error message by File
In that case we have a Drupal 8 module that we can install "File Log" module.

After configure, that file will be Create in root area Bydefault "site/default/files/logs".
I am going to share that module link here.

Note: If have any suggestions or issue regarding 'How to check log error messages in Drupal 8?' then you can ask by comments.  

Friday 20 September 2019

How to add attributes in drupal 8 twig file?

Easy to use and to add attributes in drupal 8 twig file, here are some examples for attributes:
Add Class attributes..
Syntax: {{ attributes.addClass('myclass') }}
Example: <div {{ attributes.addClass('myclass') }}> <!-- any stuff here --> </div>
//here classes is the class name.
Remove Class attributes..
Syntax: {{ attributes.removeClass('myclass') }}

Example: <div {{ attributes.removeClass('myclass') }}> <!-- any stuff here --> </div>
here classes is the class name.
Add and Remove both attributes..
<div {{ attributes.addClass('myclass').removeClass('node') }}>

</div>
Add Multiple classes attribute..
{%
set classes = ['region','region-header']
%}
<div {{ attributes.addClass(classes)>
result: <div class="region region-header">

Add a setAttribute..
attributes.setAttribute($attribute, $value)
Syntax: <div{{ attributes.setAttribute('id', 'myID') }}></div>
Example: <div id="myID"></div>
 
Remove attributes..
attributes.removeAttribute($attribute)
Syntax: <div{{ attributes.removeAttribute('id') }}></div>

Check class exist or not..
attributes.hasClass($class)
Syntax:
{% if attributes.hasClass('myclass') %}
  {# here stuff #}
{% endif %}

Note: How to add attributes in drupal 8 twig file?

Thursday 7 February 2019

How to dynamically clear cache in drupal 8?

It's a easy way to clear or remove cache with using this simple code.

Code: \Drupal::service('page_cache_kill_switch')->trigger();

Description: Simple write this code on your function and when your code will hit or run on any page this page cache will automatically triggered and clear.


Note: If have any suggestions or issue regarding 'How to dynamically clear cache in drupal 8?' then you can ask by comments.  

Thursday 24 January 2019

How to render template for custom module in drupal 8?

It is easy way to render/call template(.html.twig) file for custom module in drupal 8, But here concept is slightly different from drupal 7.
First we will go to the Controller file:
Like our controller name is ContactController.php so we will write there code like.
//Go to the ContactController.php file..
/**
 * @file
 * Contains \Drupal\contact\Controller\ContactController.
 */

namespace Drupal\contact\Controller;
use Drupal\node\Entity\Node;
use Drupal\Core\Controller\ControllerBase;


class Contactv4Controller extends ControllerBase {  
    public function indexv2() {
     
      $data = "<div>Testing</div>";
     
      return [
       '#theme'  => 'specific_contact',
       '#contact'   => $data,
    ];
  }
}

// Then go to the contact.module file.
/**
* Implements hook_theme() to add the template definition..
**/
function contact_theme($existing, $type, $theme, $path) {
  return array(
       'specific_contact' => [
        'variables' => [
            'contact' => NULL,
       ]
    ]
  );
}
 
// Now in the create template folder and the file with name of 'specific_contact.html.twig'.
And render the variable there like: <p> {{ contact }} </p>
And clear the cache after this.
Now Front end result will be 'Testing' on new template page.


Note: If have any suggestions or issue regarding 'How to render template for 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.  

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.  

Monday 17 September 2018

How to create Schema in custom module drupal 8?

When we need to create our custom module table, So we have to create schema file in custom module root like if our module name is `crudform`, so in the folder of module we will create file which name is `crudform.install`. here our file extension will be `.install` for schema.
In the file we will create function `hook_schema()` with name of `crudform_schema()` and there we will define create structure of table with table name, we have an example for this, Please have a look..

Schema database

function crudform_schema() {
  $schema['crudform'] = array(
    'fields' => array(
          'id'=>array(
            'type'=>'serial',
            'not null' => TRUE,
          ),
          'name'=>array(
            'type' => 'varchar',
            'length' => 40,
            'not null' => TRUE,
          ),
           'email'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
            'city'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
            'country'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
          'message'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

In that function crudform_schema(), our database table name will be `crudform`. here we will define table fields and structure and then return the schema. When we will install our custom module then this table with schema will automatically create in database and with the help of this we can store data in our custom table.


If we want to store default data on table then we have to use `hook_install` function In case of installation of module that data will store automatically. We have an example for this, please have a look..

function crudform_install() {
  $database = \Drupal::database();
  // Add default entry in table.
  $fields = array(
    'name' => 'Sahil',
    'email' => 'sahil@gmail.com',
    'city' => 'Delhi',
    'country' => 'India',
    'message' => 'Hello text',
  );
  $database->insert('crudform')
    ->fields($fields)
    ->execute();
  
  // Add one another entry on this table.
  $fields = array(
    'name' => 'Abhi',
    'email' => 'abhi@gmail.com',
    'city' => 'Delhi',
    'country' => 'India',
    'message' => 'Hello text world',
  );
  $database->insert('crudform')
    ->fields($fields)
    ->execute();
}

There we are creating a $fields array with few data and then store by insert query.
So that's a simple process of 'create schema in drupal 8 custom module'.


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

Friday 14 September 2018

What is right query structure for drupal 8?

Here we are defining our drupal 8 query structure with easy mode. You can find/search here INSERT, SELECT, UPDATE, DELETE.
We will explain in easy way with an examples, Please have a look..
That is our table `testing_form` structure..

id candidate_name candidate_mail candidate_number candidate_dob
1 John john@gmail.com 1236547890 2014-10-22
2 Mary mary@gmail.com 5698741230 2014-10-23
3 Karen karen@gmail.com 0123654789 2014-10-23

INSERT Query Structure:
According to php we will define INSERT Query as:

$insert_query = "INSERT INTO testing_form (candidate_name, candidate_mail, candidate_number, candidate_dob) VALUES ('sahil', 'sahil@gmail.com', '9874563210', '22-11-1990')";
mysqli_query($connection, $insert_query);

And now in case of drupal 8, our structure will be.

$fields = array(
    'candidate_name'   => 'sahil',
    'candidate_mail'   => 'sahil@gmail.com',
    'candidate_number' => '9874563210' ,
    'candidate_dob'    => '22-11-1990',           
);
db_insert('testing_form')
    ->fields($fields)
    ->execute();
   
Here 'testing_form' is table name and $fields variable is the data for fields of table.


SELECT Query Structure:
According to php we will define SELECT Query as:

$select_query = "SELECT * from testing_form where id = '2' and id != '3'";
mysqli_query($connection, $select_query);

And now in case of drupal 8, our structure will be.

$result = db_select('testing_form', 't')
    ->fields('t')
    ->condition('id', 2, '=')
    ->condition('id', 3, '!=')
    ->execute()
    ->fetchAll();
   
Here 'testing_form' is table name and our condition is all 2nd id candidate come but not come on 3rd id candidate.

We have some other method for SELECT query with connection in drupal 8..

$connection = \Drupal\Core\Database\Database::getConnection();
$results = $connection->query('select candidate_name, candidate_mail, candidate_number, candidate_dob')->fetchAll();


UPDATE Query Structure:
According to php we will define UPDATE Query as:

$update_query = "UPDATE `testing_form` set candidate_name='karen sood' where id='3'";
mysqli_query($connection, $update_query);

And now in case of drupal 8, our structure will be.

$update_query = \Drupal::database()->update('testing_form')
          ->fields(array('candidate_name' => 'karen sood', 'candidate_number' => '1236547890'))
          ->condition('id', '3')         
          ->execute();
   
Here 'testing_form' is table name and our condition is id number `2nd` of candidate data will update.

 
DELETE Query Structure:
According to php we will define DELETE Query as:

$delete_query = "DELETE from `testing_form` where id='3'";
mysqli_query($connection, $delete_query);

And now in case of drupal 8, our structure will be.

$delete_query = \Drupal::database()->delete('testing_form');
      ->condition('id', '3');   
      ->execute();
   
Here 'testing_form' is table name and our condition is id number `3rd` of candidate data will delete.


So these all are INSERT, SELECT, UPDATE, DELETE queries structure for Drupal 8. Next time we will come with `JOINS`, like how to use `joins` in drupal 8 query with many of conditions.



Note: If have any suggestions or issue regarding 'What is right query structure for drupal 8?' then you can ask by comments.  

Tuesday 11 September 2018

Steps for Add Custom or Add More Language on website.

If we want to add custom language or add multiple languages on our drupal website then we have to add and install `Language Module` first.


Install Language module



Then click on the Configure link or go with this link "/admin/config/regional/language".
Language List

and then you can add custom language by choose last option "Custom Language". After choose you will be redirect in this page.

Choose Custom or other language option
If we are choosing default languages that given by module then automatically will be added on list, but in case of last option custom language we will reach in this page.

Set Custom language code and name

After this you will redirect to listing page of added languages.
Language list
here we can set our default language that will automatically display in language list.

After that we have to check the "Show language selector on create and edit pages" option on content type edit page in "language settings".
Content type edit page for add dropdown option

Then you will be get the language drop-down in body/description type fields on node form.
So this is the simple steps for Add Custom or Add more language in website.



Note: If have any suggestions or issue regarding 'Steps for Add Custom or Add More Language on website.' then you can ask by comments.  

Thursday 6 September 2018

Media entity fields render in drupal 8 Node Twig template.

If we want to load media entity fields on node twig template. It's easy to load media entity, Please have a look..

{# call to media entity fields on node twig #}

{% for key, item in node.field_document_entity_browser %} 
// This is the node field which is connect to media field `field_document_entity_browser`..
{% if node.field_document_entity_browser[key].entity %}
// here we are rendering media entity field which machine name is `field_capt2120`..                           
{{ node.field_document_entity_browser.entity.field_capt2120[key].value }}

// here we are rendering media entity image field which machine name is `field_media_image`..        
{%if item.entity %}
{% set media = item.entity %}
{% set file = media.field_media_image.entity %}
{% set uri = file_url(file.uri.value) %}
                              
<img src="{{ uri }}" alt="{{ media.name.value }}" />
                          
 {% endif %}                           
                                                                                     
 {% endif %}
  {% endfor %}



Note: If have any suggestions or issue regarding 'Media entity fields render in drupal 8 Node Twig template.' then you can ask by comments.  

Wednesday 5 September 2018

Paragraph fields render in drupal 8 Node Twig template.

If we want to load paragraph entity fields on node twig template. It's easy to load paragraph entity, Please have a look..

{# call to paragraph entity fields on node twig #}

{{ node.field_professional_features.entity.field_professional_services_name.value }}
 // here `field_professional_features` is the content type field and `field_professional_services_name` is the related paragraph field..

{{ node.field_professional_features.entity.field_professional_services_summ.value }}
  // here `field_professional_features` is the content type field and `field_professional_services_summ` is the related paragraph field..

// here we are calling paragraph image field..

{% for key, image in node.field_professional_features %}
// here `field_professional_features` is the content type field..
{%if image.entity %}
{% set paragraph = image.entity %}
{% set file = paragraph.field_professional_services_imag.entity %}
 // here `field_professional_services_imag` is the related paragraph field..
{% set uri = file_url(file.uri.value) %}

<img src="{{ uri }}" alt="{{ paragraph.name.value }}" />

{% endif %}
{% endfor %} 



Note: If have any suggestions or issue regarding 'Paragraph fields render in drupal 8 Twig template.' then you can ask by comments.  

Tuesday 4 September 2018

Replace any string or value in twig template variable.

If we want to Replace the value in twig template then we have an example and syntax, please have a look..
{#
    ****  replace '-' with '$' sign in vidyard ID ****  
#}

{% set twig_content_variable  = node.field_resources_vidyard_id.value  %}   // here we are applying on field_resources_vidyard_id field..
{% set replace_value_var      = '-' %}
{% set replace_with_value_var = '$' %}
{%if twig_content_variable %}
   {% set vidyard_function_id = twig_content_variable|replace({ '-': '$' }) %}
{% endif %}


Note: If have any suggestions or issue regarding 'Replace any string or value in twig template variable.' then you can ask by comments. 

Programmatically Media load in drupal 8.

If we want to load Media entity. we have to add library on the top of page. ( use Drupal\media\Entity\Media; )
Then its easy to load media entity by the syntax.
   
Syntax:
$media_detail = Media::load($mid);    // here $mid is media entity id       
   
now if we want to get image field data of media field then syntax is..

$media_img = file_create_url($media_detail->field_media_image->entity->getFileUri());
 // here field_media_image is field name in media entity
   
now if we want to get any text field value then syntax will be..

$media_caption = $media_detail->get('field_capt2120')->getValue();   
// here field_capt2120 is the machine name of caption field in media entity    

foreach($m_caption as $mkey){
   $capval = $mkey['value'];    // here we will get the caption value           
}


Note: If have any suggestions or issue regarding 'Programmatically Media load in drupal 8.' then you can ask by comments.   

Thursday 23 August 2018

How we can Url Alias in Drupal 8?

If you want to path alias in drupal 8 then we have different syntax in drupal 8, Please follow this.
Syntax:
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($tid or $nid);

Example: like if we have taxonomy term and we want to path alias so first we create URL path as given exmaple..

$tid = '/taxonomy/term/'.$term_id;
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($tid); or \Drupal::service('path.alias_manager')->getAliasByPath('/taxonomy/term/'.$term_id),

OR

$nid = '/node/'.$node_id;
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($nid); or \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$node_id),


Simple then we can use this alias to send or redirect using
$response = new Symfony\Component\HttpFoundation\RedirectResponse($alias);
$response->send();
return; 


Note: If have any suggestions or issue regarding 'How we can Url Alias in Drupal 8?' 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...