Monday 19 April 2021

How to remove or cleanup old aggregated css and js files?

It's very problematic question that how we remove old aggregated css and js files otherwise folder will be too large.

In drupal we have 2 functions drupal_clear_css_cache() and drupal_clear_js_cache() that are creating our aggregation files and store in css and js folder in files/css or files/js folder.

In drupal we have on special variable `drupal_stale_file_threshold` and the default value of this 30 days, it means after 30 days old aggregated file will automatically removed and we can change this 30 days value or less then 30 days like..

Code:

variable_get('drupal_stale_file_threshold', 2592000) //for 30 day. 

variable_set('drupal_stale_file_threshold', 172800) //for 2 days.  


Note: In drupal, we have advance aggregation module, there we have delete old aggregated files option.



Note: If have any suggestions or issue regarding 'How to remove or cleanup old aggregated css and js files?' then you can ask by comments. 

How to permanent delete unused files in Drupal 8?

Drupal 8, we can programmatically delete our unused files(assets) easily. we just have to write the code in custom module file in `hook_cron` function. After put the code and clear the cache whenever you hit the cron manually or automatically will run this code will execute.

Code:

/**

 * override hook_cron()

 */

function mymodule_cron()  // mymodule will replace with module name

{

  // get all files ids

  $fids = Drupal::entityQuery('file')->execute();

  $file_usage = Drupal::service('file.usage');

  // loop all fids and load files by fid

  foreach ($fids as $fid) {

    $file = Drupal\file\Entity\File::load($fid);

    $usage = $file_usage->listUsage($file);

    // check if file not used

    if (count($usage) == 0) {

      $file->delete();

    }

  }

}


Note: If have any suggestions or issue regarding 'How to permanent delete unused files in Drupal 8?' then you can ask by comments. 

Wednesday 7 October 2020

How to create node programmatically in drupal 8?

Simple way to create node in Drupal 8 is use of Node::create() function. We are going to explain with an example.

Code structure:

$entity_type = 'node';

$values = [

  'nid' => NULL,

  'type' => 'article', // put the content type machine name here..

  'title' => 'Testing title', // title of the node..

  'uid' => 1, //user id for node publisher or use \Drupal::currentUser()->id() for default logged-in user id..

  'status' => TRUE, // published..

  'field_metatags' => serialize([

        'title' => 'Some title',

        'description' => 'Some description.',

      ]),

];

$node = \Drupal::entityTypeManager()->getStorage($entity_type)->create($values);

$node->save();


OR 


We have another code for node creation…

    $nodeArray = array();

$nodeArray = array(

'type' => 'resources',

'langcode' => 'en',

'uid' => '1', //\Drupal::currentUser()->id(),

'status' => '1',

'title' => $row->title,

'created' => strtotime($row->created),

'path' => [

  'alias' => $row->page_url,

  'pathauto' => PathautoState::SKIP,

]

);

$node = \Drupal\node\Entity\Node::create($nodeArray);        

$node->set('body', ['value' => $row->body, 'summary' => '', 'format' => 'full_html']);

$node->set('field_resources_content_type', $row->field_resources_content_type);

$node->set('field_resources_lob', $row->field_resources_lob);

$node->set('field_resources_vidyard_id', $row->field_resources_vidyard_id);

$node->set('field_instrument_description', $row->field_instrument_description);

$node->set('field_source', $row->source);

$node->set('field_expiration_date', $row->field_expiration_date);

$node->set('field_meta_tags', serialize([

  'title' => $row->field_meta_title,

  'description' => $row->field_meta_description,

  'keywords' => $row->field_meta_keywords,

]));

$document_url = $row->field_resources_asset_tagging;

$extfile_info = basename($document_url);

$filename = explode(".", $extfile_info);

list($ext_name, $extension) = explode(".", $extfile_info);

//$name = $filename[0] . '.' . $extension;

        $name = $extfile_info;

        $savepath = str_replace($base_url.'/sites/default/files/','',$document_url); 

$uploaded_file = file_save_data(file_get_contents($document_url), "public://".$savepath, FILE_EXISTS_RENAME);

$file_url = $uploaded_file->getFileUri();

$fid = $uploaded_file->get('fid')->value;

if (!empty($uploaded_file)) {

    $node->set('field_resources_asset_tagging', ['target_id' => $fid]);

} else {

drupal_set_message('file not uploaded for '.$row->title,'warning');

}

$thumbnail_url = $row->field_resources_thumbnail;

if($thumbnail_url!=''){

$extfile_info1 = basename($thumbnail_url);

$filename = explode(".", $extfile_info1);

list($ext_name, $extension) = explode(".", $extfile_info1);

//$name = $filename[0] . '.' . $extension;

$name = $extfile_info1;

$uploaded_thumbnail = file_save_data(file_get_contents($thumbnail_url), "public://importcsv/$name", FILE_EXISTS_RENAME);

$file_url = $uploaded_thumbnail->getFileUri();

$fid = $uploaded_thumbnail->get('fid')->value;

if (!empty($uploaded_thumbnail)) {

$node->set('field_resources_thumbnail', ['target_id' => $fid]);

}

}

        $res_save = $node->save();

Here we are giving an example for node create programmatically in Drupal 8, default fields, entity reference field, text field, list field, image upload, PDF upload in Node::create() code.


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

Thursday 24 September 2020

How to generate sitemap xml in drupal 8 ?

Simple way to generate XML for sitemap in Drupal 8, we have 'Simple sitemap' and 'XML sitemap' modules but if we want  to add some custom code or want customization in XML, so we have simple code for generate custom XML, please follow the given process and example.

Steps:

  1. Create custom module and controller file and render the below given class in file header.
    use Drupal\Core\Controller\ControllerBase;
    use Drupal\node\Entity\Node;
    use Symfony\Component\HttpFoundation\Response;

  2. Write the code in controller function:
    $rows .= '<?xml version="1.0" encoding="UTF-8" ?>';

    //open the urlset..
    $rows .= '<urlset xmlns="http://www.google.com/schemas/sitemap/0.84"
                                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84
                                http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';

    If you want to add COVEO elements in XML then we have to use below given code also:

     $rows .= '<urlset xmlns="http://www.google.com/schemas/sitemap/0.84"   
                                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                 xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84
                                 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd"
                                 xmlns:coveo="http://www.coveo.com/schemas/metadata">';

  3. After that create the xml code with elements:
    $rows.='<url>
                 <loc>'.$base_url.''.$alias.'</loc>
                 <lastmod>'.$last_modified.'</lastmod>
                 <changefreq>daily</changefreq>
                 <priority>0.5</priority>
                 <coveo:metadata>
                         <md_contenttype>'.$res_content_type.'</md_contenttype>                         
                         <md_pagetype>'.$pagetype.'</md_pagetype>
                 </coveo:metadata>
                 </url>';

    $rows .='</urlset>'; //close the urlset..

  4. After that last final code for render XML:
         $response = new Response();
         $response->headers->set('Content-Type', 'text/xml'); //add content type = text/xml header.. 
         $response->setContent($rows); // pass the $row as array or xml print value..
         return $response; //return reponse with xml format without any styling..

    So with the help of this simple code we can create custom XML in drupal 8.


Note: If have any suggestions or issue regarding 'How to generate sitemap xml in drupal 8 ?' then you can ask by comments. 



Wednesday 26 August 2020

How to remove or unset url links form simple sitemap in druapl 8?

Simple way to unset the URL link is alter simple sitemap module, here we will give an example of code for remove or unset any link on any condition basis.

Example:

Create a custom module or put the code in existing custom module.

a. First render class library in file header.

use Drupal\simple_sitemap\Simplesitemap;

b. Then write the hook function code.

/**

 * Alter the generated link data before the sitemap is saved.

 * This hook gets invoked for every sitemap chunk generated.

 *

 * @param array &$links

 *   Array containing multilingual links generated for each path to be indexed.

 */

function finder_simple_sitemap_links_alter(&$links) {


  // Remove french URL for a certain path in the hreflang sitemap.

  foreach ($links as $key => $link) {

    if ($link['path'] === 'node/1') {

      // Remove 'loc' URL if it points to a french site.

      if ($link['langcode'] === 'fr') {

        unset($links[$key]);

      }

      // If this 'loc' URL points to a non-french site, make sure to remove

      // its french alternate URL.

      else {

        if ($link['alternate_urls']['fr']) {

          unset($links[$key]['alternate_urls']['fr']);

        }

      }

    }

  }

}


Note: If have any suggestions or issue regarding 'How to remove or unset url links form simple sitemap in druapl 8?' then you can ask by comments. 

Tuesday 25 August 2020

How to alter or add custom url links in simple sitemap in drupal 8?

 It is very simple method, we have 2 options in Drupal 8.

https://www.drupal.org/project/simple_sitemap

1. we can add by config page of module like (//localhost//admin/config/search/simplesitemap/custom). There add custom links with priority with change frequency.

2. we can use alter method with simple steps::

a. Create any custom module or write code in any existing custom module.

b. go to custom_module.module file or create new if not exist.

c. write code line with below given example:

Example:

First render class library in file header.

use Drupal\simple_sitemap\Simplesitemap;

/**

 * Use this hook to add arbitrary links to the sitemap.

 *

 * @param array &$arbitrary_links

 */

function finder_simple_sitemap_arbitrary_links_alter(&$arbitrary_links) {


  // Add an arbitrary link.

  $arbitrary_links = array([

    'url' => 'https://localhost/applications',

    'priority' => '0.9',

    'lastmod' => '2020-05-25T14:40:30+02:00',

    'changefreq' => 'daily',

],

[

'url' => 'https://localhost/products',

    'priority' => '0.7',

    'lastmod' => '2020-07-15T13:40:30+02:00',

    'changefreq' => 'daily',

    ],

);

}

Note: We can't add date(lastmod) in custom links by admin, so we have to use alter code for add dates(lastmod) in custom create links.


Note: If have any suggestions or issue regarding 'How to alter or add custom url links in simple sitemap in drupal 8?' 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. 

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...