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.  

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