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. 

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 13 March 2020

Difference between hook_entity_presave and hook_entity_insert ?

Simple way to differentiate both hooks is the 'ID' is not available in hook_entity_presave() ("pre meaning before, and without saved ID is not assigned in database),
But this 'ID' will be available in hook_entity_insert().

Example:
function mymodule_node_insert(NodeInterface $node) { 
  $nid = $node->id();
}
OR
function mymodule_node_insert($node) {
  if ($node->getType() == 'your content type') {
        $node->setTitle('New entity ' . $node->id()); // to update title with node id
        $node->field_test = 'Id' . $node->id();  // or, to update a text field with node id
        $node->save();
  }
}

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('New Title here');
    //Note : Not to save, because it's automatic.   
  }
}
OR
function mymodule_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('Edited Title');
  $node->set('body', 'this is the new body section');
  //Note : Not to save, because it's automatic.
}

Note: If have any suggestions or issue regarding 'Difference between hook_entity_presave and hook_entity_insert ?' then you can ask by comments.  

Thursday 27 February 2020

How to use breakpoints in drupal 8?

There we have simple way to use breakpoints means separate media query in drupal 8 and that will also help in speed up or optimize the website.
We have some following points, that will easily clear your doubts about breakpoints and separate media query.
1. We will create a file with the name of 'yourthemeORmoduleName.breakpoints.yml', Example for theme like your theme name is 'bartik' the file name will be 'bartik.breakpoints.yml'.
2. This breakpoints file will be use for write the code of media query for responsiveness. This file will be located in 'themes/bartik/' root.
Example:
bartik.mobile:
  label: mobile
  mediaQuery: ''
  weight: 0
  multipliers:
    - 1x
    - 1.5x
    - 2x    
bartik.narrow:
  label: narrow
  mediaQuery: 'all and (min-width: 560px) and (max-width: 850px)'
  weight: 1
  multipliers:
    - 1x
    - 1.5x
    - 2x    
bartik.wide:
  label: wide
  mediaQuery: 'all and (min-width: 851px)'
  weight: 2
  multipliers:
    - 1x
    - 1.5x
    - 2x    
bartik.small:
  label: small
  mediaQuery: "(min-width: 0px)"
  weight: 1
  multipliers:
    - 1x
    - 1.5x
    - 2x
bartik.medium:
  label: medium
  mediaQuery: "(min-width: 768px)"
  weight: 2
  multipliers:
    - 1x
    - 1.5x
    - 2x
bartik.large:
  label: large
  mediaQuery: "(min-width: 1024px)"
  weight: 3
  multipliers:
    - 1x
    - 1.5x
    - 2x
Here the breakpoint properties are:
    Very first we will take a unique breakpoint name like: bartik.small:      (moduleName/themeName.unique breakpointName),
    Example: bartik.small: ,bartik.medium: ,bartik.large: ,bartik.wide: ,bartik.narrow: ,bartik.mobile:
   
    label - The human readable name of the breakpoint
    mediaQuery - a valid @media query(for responsiveness)
    weight - where the breakpoint is ordered in relation to other breakpoints
    multiplier - the ratio between the physical pixel size of the active device and the device-independent pixel size
               - 1x
               - 1.5x // supports Android
               - 2x  // supports Mac retina display
              
3. After that we will create new library and attach this breakpoints in 'bartik.libraries.yml' file.
Syntax:
libraryName:
  version: 1.0
  css:
    theme:
      css/desktop-small.css: { media: all and (min-width: 851px) }
      css/mobile.css: { media: only screen and (max-width: 767px) }
      css/mobile-common.css: { media: all and (min-width: 560px) and (max-width: 850px) }
     
    Same like we can create many viewports / breakpoints / media queries and attach with libraries and templates of our website.

4. Now this specific library we will render on template where we want to apply.
Example: {{ attach_library('mythemeName/libraryName') }}   

So in this way we can optimize the site and increase the performance with the help of breakpoints because with the help of this only in case of Mobile or Tab or Ipad or Desktop specific mentioned css will be rendered else not.
And the most important thing is clear the Cache and run Cron.

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

Tuesday 11 February 2020

How to create tabs by custom module in drupal 8?

Today we will discuss about, how to create new tab in custom module and set the linking. So before start, we will clear some points for custom module.
1. "module_name.links.task.yml" and "module_name.routing.yml" is important file, if we are going to create tabs.
2. Now Please follow the syntax, we will explain here for all parameters and syntax for tabs.
Example Syntax:   Here 'account_login' is example of my module name..

account_login.tab_1:                                   // This is the Tab Routers
  route_name : account_login.content         // This is route name and we will use this in routing.yml  file when we create routers and path
  title: account login                                   // This is Title of Tabs.
  base_route: account_login.content          // This is for set default open Tab
  weight: 10                                                // This is for tab weight or for order of Tab

account_login.tab_2:                                   // This is for second Tab Router
  route_name: account_login_otp.content   // This is route name and we will use this in routing.yml file when we create routers and path
  title: Work                                                 // This is Title of Tabs.
  base_route: account_login.content           // This is for set default open Tab
  weight: 20                                                 // This is for tab weight or for order of Tab

 
 
Now we will create "routing.yml" file.
Example Syntax:   Here 'account_login' is example of my module name..

account_login.content:        // so we will use same route name for first tab which we use in 'links.task.yml' file
   path: '/account/login'
   defaults:
   # Calls the list controller, defined in the annotation of the product entity.      
    _form: '\Drupal\account_login\Plugin\Form\userloginForm'
    -title: 'Two Way Authentication Login'
   requirements:
    _permission: 'access content'
    _user_is_logged_in: 'FALSE'
   
account_login_otp.content:                             // We will use same route name for second tab which we use in 'links.task.yml' file
   path: '/account/login/authenticate'
   defaults:
   # Calls the list controller, defined in the annotation of the product entity.      
    _form: '\Drupal\account_login\Plugin\Form\userloginotpForm'
    -title: 'Login Form Authenticate'
   requirements:
    _permission: 'access content'   
    _user_is_logged_in: 'FALSE'
   

   
Now just we have to install custom module and and clear the cache then put the first URL on brower (Ex: /account/login) and its will show our Tabs. So simple way to easily create custom tabs.


Note: What is Namespace and Use keyword in drupal 8 module?

Tuesday 7 January 2020

What is Namespace and Use keyword in drupal 8 module?

Namespace: Namespace is a way of Organizing your classes into folder and ensure that your class does not conflict with another class with the same name because the class can be same but namespace will be unique.

Use Keyword: use keyword allows you to use classes from another namespaces when you need them.

Drupal 8 generally use PHP classes instead of functions. Two classes can have same name in different namespace. Namespace is way of organize the classes into folders and subfolders and the namespace as the path of the file.

If you will try the same name file with the same name in same folder, you will get the fetal error. but if you want to create the same name file then you have to create subfolder and put there.

Get the example of namespaces with create module.

1. Start the custom module with create directory name like 'testing'.
2. Now create 'info.yml' file. That file tells Drupal that your module exist and have some content/information.

The filename should be the machine name of your module with .info.yml extension, like testing is our module name so here name will be 'testing.info.yml'.
File content:
    name: Testing
    description: A custom module to build our Drupal 8 module
    package: Custom
    type: module
    version: 1.0
    core: 8.x

   
3. Some modules have controllers, plugins, forms, templates, test all are in src folder. So now we will create the src required folder.
4. Now we need a page controller for show the content output with these simple steps:
  a. Create src folder.
  b. now create Controller folder under the src folder.
  c. within the Controller folder , create file with name of 'TestingController.php'.
In the 'TestingController.php' file we will print our short message for testing.

    /**
     * @file
     * Contains \Drupal\testing\Controller\TestingController.
     */
    namespace Drupal\testing\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    
    class TestingController extends ControllerBase {
      public function content() {
        return array(
          '#type' => 'markup',
          '#markup' => t('Hello, we are here for testing.'),
        );
      }
    } 
 

Here the namespace has been defined as Drupal\testing\Controller. We will not here use full folder structure like ->  Drupal\modules\testing\src\Controller

here modules\src is silent from namespace and Drupal automatically mapped with namespace src folder, so that we have to follow standard folder structure of modules.

If we have to use TestingController class in different namespace then we have to include with 'use keyword' as its namespace -> use Drupal\testing\Controller\TestingController;

TestingController is extending another class called ControllerBase. So for get the classes, include ControllerBase with use statement -> use Drupal\Core\Controller\ControllerBase;

If use statement are not included then PHP will looking for ControllerBase and gives error.
"So use statement allows you to use classes from another namespace."

5. Now we have to create important file with name of 'routing.yml'. here the name will be 'testing.routing.yml' that will create in custom module root.

    testing.content:
      path: '/testing'
      defaults:
        _controller: 'Drupal\testing\Controller\TestingController::content'
        _title: 'Hello Tester'
      requirements:
        _permission: 'access content'

       
so now enable the module and clear the cache then go with the path '/testing' and get the output form controller.
       

Note: What is Namespace and Use keyword in drupal 8 module?

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