Monday 16 December 2019

How to avoid Core CSS and JS from theme in drupal 8?

Sometimes we just want to render our custom css/js, and avoid globally rendered core css or js from every page. So we have to follow given below steps:

Step 1: First go to your theme ".info.yml" file.
Step 2: Then add "stylesheets-remove:" parameter and add css file path of all core files like,
Example: Theme file name is "account.info.yml".
then we just have to add 'stylesheets-remove:' for avoid under write files there..

stylesheets-remove:
  - core/themes/stable/css/system/components/autocomplete-loading.module.css
  - core/themes/stable/css/system/components/ajax-progress.module.css
  - core/themes/stable/css/system/components/align.module.css

 
Step 3: Clear full cache of project.

So this is the easy way to avoid core file from project pages.


Note: How to remove globally CSS from theme of project in drupal 8?

Monday 2 December 2019

How to change in view ajax according to requirement in drupal 8?

It's easy to handle this core changes of views. One thing we have to sure that Views Advanced feature "Use AJAX:" should be yes.

"Use AJAX: Yes"

After that we can check our views/ajax request by Inspect and Check with Network Tab. We are giving an example to easy to use this.

Example: Suppose we have to start any view/ajax request on click on any "id" in html then our code in jquery file will be:

jQuery(document).on("click", "#prodresources", function (e) {                
    var arr = base_fullurl.split('/');
    var page_nid = arr[2]; 
    Drupal.attachBehaviors();
    getInfo('application_resources',['block_3','block_13'], page_nid);    // we are creating a function on click on "prodresources" id.
});

Parameters:
view_name : "application_resources"       // that is view machine name
view_display_id : ['block_3','block_13']  // we can use multiple views block on same view.
view_args: page_nid                       // this is argument for view


We just have to pass these three parameters view_name:machine name and view_display_id: blocks in array in multiple case and last one is view_args: if arguments pass.

function getInfo(view_name, blocks, args) {
    var base_url = window.location.origin;       
    $.ajax({
      url: base_url+'/views/ajax',
      type: 'post',
      data: {
        view_name: view_name, 
        view_display_id: blocks,
        view_args: args,
      },
      dataTypeview_display_id: 'json',
      success: function (response) {
          if (response[3] !== undefined) {
          var viewHtml = response[3].data;
          $('#destination_id').html(viewHtml);
          Drupal.attachBehaviors();
        }           
      },
          error: function(data) {
           alert('An error occured!');
          }
    });
}

Note: How to apply changes on views ajax according to requirement in Drupal 8?

Thursday 28 November 2019

How to store temporary data in drupal 8?

Drupal 8, we have service's for store temporary data by using private_tempstore or getSession() for user data. It's simple to use store and pass the data from one place to another. Here we are discussing about two popular way to store and pass data with 'Session' and 'tempStore'.

Two different things to store, So both have different behaviors, we are discussing, where we will use and how we will use. In past time we just use '$_SESSION' for temporary data storage. But now in drupal 8 we have Service's: 'user.private_tempstore' and 'user.shared_tempstore'.

If we have to store and pass the big amount of data like multiple values or array then we will use 'user.private_tempstore', and in case we just have to store and pass the one variable or small values then we can normally use '$session'.

Private_tempstore:
This will work/Store data in duration of session time.

Use this library for private_tempstore on top of the page..
use Drupal\Core\TempStore\PrivateTempStoreFactory;

// Set a variable in the tempstore
$tempstore = \Drupal::service('user.private_tempstore')->get('yourmodule_name');
$tempstore->set('any_variable_name', $value); // store the temporary data in 'any_variable_name' variable.

// Read the variable in the tempstore
$tempstore = \Drupal::service('user.private_tempstore')->get('yourmodule_name');
$some_data = $tempstore->get('any_variable_name'); // Read the temporary variable.

Session:
A private tempstore is a kind of storage for large amount of data, big to have it preloaded in memory.
If you want to store a small amount of data, then use session. You find the session attached to the request object:
Use $session->set() and $session->get() for store:

Use this library for session on the top of the page..
use Symfony\Component\HttpFoundation\Request;

$session = \Drupal::request()->getSession();

if you want to set/store some value in session.
$session->set('myvariable', $value); //$value is any value

To retrive or get the session variable.
$detail = $session->get('myvariable');


$session = \Drupal::request()->getSession();

Example:
  $temp_array['username'] = $form_state->getValue('username');
  $temp_array['password'] = $form_state->getValue('password');
  $temp_array['otp'] = $form_state->getValue('otp');
  $temp_array['email'] = $form_state->getValue('email');

  $session = \Drupal::service('user.private_tempstore')->get('my_module_name');
  $session->set('temp_details', $temp_array); // for store temporary data
 
  $session->get('temp_details'); // for retrieve temporary data
 
Example:
    $session = $this->getRequest()->getSession();
    $session->set('temp_details', $value); //set data

    $session = $this->getRequest()->getSession();
    $session->get('temp_details', []);    // get data
   
     // make sure the form is not cached and this code is run on every request
    $form['#cache']['max-age'] = 0;
  
Here we don't need to start the session. This is done by Drupal in the background for each request.    When completing the response, Drupal checks if there is new session data and then starts a session to store the data.


Note: How to store temporary data in drupal 8?

Monday 4 November 2019

How to sort data by array of category ids in drupal 8?

Sometime we have a case of sort data with array of categories So we can't use direct 'orderBy' in drupal 8 query. We have to use 'addExpression' in query. Here we have an example for better clear this article.
Example:
In a way of query:

    $products = db_query("select gfd.entity_id from node__field_category as gfd inner join node_field_data as nfd on nfd.nid=gfd.entity_id ORDER BY FIELD(gfd.field_category_target_id, 675, 676, 677), nfd.title ASC");

    OR
    Other way of Query:


    $products = \Drupal::database()->select('node__field_category', 'gfd');
    $products->join('node_field_data', 'nfd', 'nfd.nid=gfd.entity_id');       
    $products->fields('gfd', array('entity_id'));       
    $products->addExpression('FIELD(gfd.field_category_target_id, 675, 676, 677)', 'order_field');
    $products->orderBy('order_field', 'ASC');   
    $product_ids = $products->execute()->fetchAll();
   
Description: Here we are using '$products->addExpression' for add special type of sorting so we will pass the field alias and field name then category id which you want for sort data and then 'order_field' is some kind of alias and we will pass in this way for ASC or DESC:
$products->orderBy('order_field', 'ASC');
So this is the simple way to sort data by array ASC/DESC in Drupal 8 query.


Note: How to sort data by array of category ids in drupal 8?

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?

Tuesday 27 August 2019

Why Drupal 8 Performance is better than Drupal 7?

Drupal 8 comes with Symfony framework, a high performing PHP framework with code security. Drupal 8 is faster than Drupal 7, here we have some points that can prove who is faster version in Drupal. 

1. Drupal 8 now turned on dynamic caching.
2. Drupal 8 turned on 6 week page caching for anonymous users. This makes Drupal 8 serving    anonymous user very fast.
3. Even logged in users can Benefit from performance improvement.
4. Drupal 8 does not send JavaScript to all pages, unless you need to use it.
5. Only place where Drupal 8 is slow in cold caching, if user is the first visitor of website in Drupal 8, it will be slower than Drupal 7 but because of cache improvement next time visitor will hit the page, it will be faster in Drupal 8.
6. Drupal 8 uses breakpoint media queries, which saves extra efforts to make a website responsive but in Drupal 7 does not use breakpoint media queries and has a different approach to manage how the site appears on different devices screens.
7. Drupal 8 uses Twig as a template engine. Twig is part of Symfony 2 framework and PHP based compiled template engine, however Drupal 7 uses the PHP template as default template engine and users create the templates by PHP code.
8. Symfony framework makes Drupal 8 stronger than Drupal 7 to develop secure and robust website or web applications.
9. Drupal 7 does not have powerful framework to manage its codebase. Developers still use Drupal 7 but its lack of framework features makes it hard to manage code.


Note: Why Drupal 8 Performance is better than Drupal 7?

Monday 12 August 2019

How to replace function use in Twig template?

It's a simple way to use "Replace" function in twig file just go through simple method:

Syntax with example:                   

{#
*** replace '-' with '$' sign in vidyard ID ***
#}

{% set twig_content_variable = node.field_resources_vidyard_id.value %}    //field_resources_vidyard_id is are 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: How to replace function use in Twig template?

Thursday 8 August 2019

How to node load by name in drupal 8?

In drupal 8, we have easy way to node load by name/title. We can use "loadByProperties" function for node/user/file data.
here we are going to give an example with 3 type of entity.

Syntax 1:
$title = 'dummy';
//node load by name/title
$node_data = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadByProperties(['title' => $title]); 
 OR

$result = \Drupal::entityQuery("node")
                ->condition('type', 'resources') // put your content type here
                ->condition('title', $title) // pass the title value or take any other condition
                ->execute();
               
Syntax 2:               
$email = 'dummymailid@gmail.com';
//load user by email id
$user_data = \Drupal::entityTypeManager()
           ->getStorage('user')
           ->loadByProperties(['mail'=> $email]); // here we can use any other property/field

          
Syntax 3:
$filr_uri = 'dummy file uri';          
//load file by uri
$file_data = \Drupal::entityTypeManager()
           ->getStorage('file')
           ->loadByProperties(['uri' => $file_uri]); // here we can use any other field


Note: How to node load by name in drupal 8?

How to delete content node programmatically in drupal 8?

Here we have simple way to 'delete content programmatically'. We can use this code in our "custom module/plugin" or  "hook_entity_predelete" or in "hook_entity_delete". Just use that simple code..

Syntax:

 $result = \Drupal::entityQuery("node")
                ->condition('type', 'resources');  // here change the content type of your
 $nids = $result->execute();

  if (!empty($nids)) {
    $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
    $nodes->delete();
  }


#Extra notes: here we can add more conditions in 'entityQuery' as per our requirement.









Note: How to delete content node programmatically in drupal 8?

Wednesday 24 July 2019

How to set hreflang manually in website?

Here we are simple way to add 'hreflang' manually. We just have to add code in "html.html.twig" file.
For Front page code:

{% if is_front %}
<link rel="alternate" href="https://www.google.com/" hreflang="x-default" />
<link rel="alternate" href="https://de.google.com/" hreflang="de-de" />
<link rel="alternate" href="https://www.google.com.cn/" hreflang="zh-cn" />
<link rel="alternate" href="https://fr.google.com/" hreflang="fr-fr" />
{% endif %}


For Full website code: Without add any "if" condition.

<link rel="alternate" href="https://www.google.com/" hreflang="x-default" />
<link rel="alternate" href="https://de.google.com/" hreflang="de-de" />
<link rel="alternate" href="https://www.google.com.cn/" hreflang="zh-cn" />
<link rel="alternate" href="https://fr.google.com/" hreflang="fr-fr" />


<meta name="title" content="News Releases" />
<meta name="description" content="demo description." />
<meta name="keywords" content="demo, description" />




Note: If have any suggestions or issue regarding 'How to set hreflang manually in website?' then you can ask by comments.

Tuesday 2 July 2019

How to display records in custom module with pagination?

It is simple to display record/data from database in drupal 8 with pagination, here we are going to explain by example with some simple steps:
Step 1:
Create a folder with name of "gpcustom", this is our custom module name. Now create a file "gpcustom.info.yml" for create identity of module.
and the code for this file is..

name: Student Records
description: 'Display student records'
type: module
core: 8.x


Step 2:
Create a file with name of "gpcustom.routing.yml", here we are going to declare routing means path for display record page.
and the code for this file is..

google_feeds_list:
  path: 'student/record'
  defaults:
    _controller: '\Drupal\gpcustom\Controller\gpcustomController::student_record'
    _title: 'Student Records'
  requirements:
    _permission: 'access content'   

   
// _controller: '\Drupal\gpcustom\Controller\gpcustomController::student_record'  means '\Drupal\gpcustom\Controller\viewController' is file path for function and 'student_record' is the function name.   
// _permission: 'access content' means anybody can access this page without login.
// path: 'student/record' means display record page url.
// _title: 'Student Records' means title of page.


Step 3:
Create a folder with this hierarchy '\src\Controller\' and file with name of "gpcustomController.php".
and the code for this file is..
<?php
namespace Drupal\gpcustom\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;

/**
 * Class DisplayTableController.
 *
 * @package Drupal\gpcustom\Controller
 */

class gpcustomController extends ControllerBase {

  /**
   * Returns a render-able array for a test page.
   */

  public function student_record() {
    //create table header
         $header = array(
         'id'=> t('SrNo'),
         'name' => t('Candidate Name'),
         'mobile' => t('Mobile Number'),
         'email' => t('Email ID'),
         'age' => t('Age'),
         'gender' => t('Gender'),
         'opt' => t('operations'),
         );

    //select records from table
    $query = \Drupal::database()->select('mydata', 'm');
    $query->fields('m', ['id','name','mobilenumber','email','age','gender']);
    $pager = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(3);
      // The actual action of sorting the rows is here.
    $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')
            ->orderByHeader($header);
    $result = $pager->execute();
    $rows=array();
    foreach($result as $data){
        if ($data->id != 0 && $data->id != 1) {
   
        $operate = '<a href="/drupaladvance/mydata/form/mydata?num='.$data->id.'">Edit</a>|<a href="/drupaladvance/mydata/form/delete/'.$data->id.'">delete</a>';
        //print the data from table
         $rows[$data->id] = array(
             'id' =>$data->id,
             'name' => $data->name,
             'mobile' => $data->mobilenumber,
             'email' => $data->email,
             'age' => $data->age,
             'gender' => $data->gender,
             'operation' => t($operate),
           
         );
        }
    }
        //display data in site
         $form['table'] = [
         '#type' => 'table',
         '#header' => $header,
     '#rows' => $rows,
     '#empty' => t('No users found'),
     ];
      // Finally add the pager.
        $form['pager'] = array(
          '#type' => 'pager'
      );
     return $form;

    }
}

?>
So that's all for display data by csutom module in drupal 8, now clear the cache and goto the modules page '/admin/modules' and find by name your module and enable it.
and go to the URL which we decide in '.routing.yml' file.


Note: If have any suggestions or issue regarding 'How to display records in custom module with pagination?' then you can ask by comments. 

Friday 7 June 2019

How to Create Custom Block and Render on template in drupal 8?

Here we are discussing simple concept for create custom Block and render on template. Just simple Steps, Please follow this.

1. We have to create folder under "/modules/custom/herobanner".
2. Inside this 'myblock' folder have to create 'info.yml' file like..

Example:
herobanner.info.yml
name: Hero Banner
type: module
description: Homepage hero banner.
core: '8.x'
package: Custom
dependencies:
  - block


 
3. Then we have to create one more folder like "/modules/herobanner/src/Plugin/Block" and create file in this folder with name of "HerobannerBlock.php".

There we will mention "Annotation meta data", that will allow us to identify the Block.
Here "HerobannerBlock" class will contain 4 methods:
build(), blockAccess(), blockForm(), blockSubmit()

4. Now we will start code in "HerobannerBlock.php" file.

<?php

namespace Drupal\herobanner\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Link;

/**
 * Provides a 'Banner' Block
 *
 * @Block(
 *   id = "banner_block",
 *   admin_label = @Translation("Banner block"),
 * )
 */


class HerobannerBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */

  public function build() {
    return [
      '#markup' => $this->t('This is a custom block example.'),
    ];
  }

  /**
   * {@inheritdoc}
   */

  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }

  /**
   * {@inheritdoc}
   */

  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();

    return $form;
  }

  /**
   * {@inheritdoc}
   */

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['herobanner_settings'] = $form_state->getValue('herobanner_settings');
  }
}


Example:
namespace Drupal\herobanner\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Link;

/**
 * Provides a 'Banner' Block
 *
 * @Block(
 *   id = "banner_block",
 *   admin_label = @Translation("Banner block"),
 * )
 */


class HerobannerBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */

  public function build() {
  /**
   * Read homepage_banner_products homepage_hero_banner
   */

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "homepage_banner_products");   
    $query->sort('weight','ASC');
    $tids = $query->execute();
       
    $homepage_banner_products_terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    $i=0;
    $product_slider = '';
    foreach ($homepage_banner_products_terms as $term) {   
                
        $product_image_path = $term->field_image->entity->getFileUri();   
        $img_url = file_create_url($product_image_path);
        $product_image = $term->get('field_image')->getValue();
        $prdct_alt = $product_image[0]['alt'];
        $new_window = $term->get('field_open_in_new_window')->getValue();
        $target = (isset($new_window[0]) && $new_window[0]['value'] == 1)?'target="_blank"':'';               
       
        $enddate = $term->get('field_end_date')->getValue();       
       
        $curdate = date('Y-m-d');
        if($enddate >= $curdate){
        $active_class = ($i == 0)?'active':'';       
          
            $product_slider.='<div class="item '.$active_class.'">
                                <div class="item-inner">
                                    <h2>'.$term->name->value.'</h2>
                                    <div class="productthumb"><img src="'.$img_url.'" alt="'.$prdct_alt.'"></div>
                                    '.$term->description->value.'
                                    <a href="'.$term->field_title->value.'" '.$target.' class="linkBtn mdhbanner">'.$term->field_support_option_title->value.'<span class="icon-icon_link"></span></a>
                                </div>
                            </div>';       
       
            $i++;   
           
        }
    }
   
    $html = '<div class="arc-container layer-3 layer" data-depth=".5" data-type="parallax">
            <div class="arc-circle">
                <div class="featuredproduct">
                    <div class="pop-scroll-outer">
                        <div class="pop-scroll">
                            <div class="slidercontrol">
                                <a type="button" class="slick-prev slickbutton carousel-control" href="javascript:void(0)">
                                    <span class="icon-icon_link icon-flip" href="#myCarousel" data-slide="prev"></span>
                                </a>
                                <strong>Featured Products</strong> <span class="num"></span>
                                <a type="button" class="slick-next slickbutton carousel-control" href="javascript:void(0)">
                                    <span class="icon-icon_link" href="#myCarousel" data-slide="next"></span>
                                </a>

                            </div>

                            <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="false">
                                <div class="carousel-inner">
                                    '.$product_slider.'
                                </div>
                            </div>
                        </div>

                    </div>
                    <!--Featured Product-->
                </div>
            </div>
        </div>
    </div>';
   
    return array(
      '#markup' => $this->t($html),
    );
  }
}


?>

Now we have to install and Enable our module and then clear the cache.
Place Block
Choose Block




And Pass the 'id' of your Block in this function..

Syntax: {{ drupal_block('myblock_id') }}

Example: {{ drupal_block('banner_block') }}


After this clear the cache and get the result.


Note: If have any suggestions or issue regarding 'How to Create Custom Block and Render on template in drupal 8?' then you can ask by comments.

Tuesday 30 April 2019

How to find text from URL in Twig Template drupal 8?

It is easy way to find any text in any string or url in a Twig template file, here is we have syntax structure for this problem, have a look.

Syntax:

                 {% set testvar = url('<current>') %}
                 {% if 'test' in testvar|render|render %}
                         <p>url contains "test"</p>
                 {% endif %}

Description: here we set a 'testvar' variable with contain of current page URL, and then we find a 'test' string in 'testvar' variable means in URL, if contain string then <p> tag data will print.

Example:
               {% set testvar = node.field_link.0.url %}
               {% if '/node/add' in testvar|render|render %}                               
               {% else %}
               <a href="{{ node.field_link.0.testvar }}">Read More</a>
               {% endif %} 

Description: here 'testvar' variable contain the value of that 'node.field_link.0.url' field. and we are checking/finding the '/node/add' string. if this will exist in then data will not display and in else case 'Read More' will display with that link.



Note: If have any suggestions or issue regarding 'How to find text from URL in Twig Template drupal 8?' then you can ask by comments.

Friday 29 March 2019

How to Check the Condition in Twig Template?

It's easy process to check the condition of our 'id' exist or not for particular variable render time in Twig template.
Like we have to check any "Product type" exist or not and then variable call there, So we are giving an example:
Example 1:
{% if node.field_product_type.value not in ['0', '2', '4', '5', '7'] %}
 /*** print variable here ***/
{% endif %}

Description: Here our condition is, if Product type of node value is not in these id's ['0', '2', '4', '5', '7'], then our variable will show the result otherwise not.

Example 2:
{% set node_id = node.id %}
{% if node_id in ['216','217','9','1258'] %} 
 /*** print variable here ***/
{% endif %}

Description: Here our condition is, if node id of node is in these id's ['216','217','9','1258'], then our variable will show the result otherwise not.


Note: If have any suggestions or issue regarding 'How to Check the Condition in Twig Template?' then you can ask by comments.

Tuesday 19 March 2019

How to get the Parent id from term id in drupal 8?

It's easy way to tackle this problem, Sometimes we face this issue and take the query help and get the parent id, but we have here solution for this issue.

Just write the loadParent syntax as per given instructions:

Syntax:

$term_id = $node->get('field_category')->target_id;
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term_id);
$parentids = $term->parent->target_id;

OR

 $parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($term_id);   // here term_id is child term id
 $parent = reset($parent); //reset the parent array
 $parentids = $parent->id();    //get the parent id  


Note: If have any suggestions or issue regarding 'How to get the Parent id from term id in drupal 8?' then you can ask by comments.

Tuesday 12 March 2019

How to encode url in drupal 8?

It's a easy way to encode url in drupal 8 twig template. We just have to follow the simple steps:
Step 1. First create a variable like given example.

Example:
{% set return_url = render_var(url('<front>')) ~ 'contact?msg=success&region=americas' %}

Description: here
   return_url is the variable name and
   url('<front>') is the front page url and
   contact?msg=success&region=americas this section we are concating with " ~ " Tilde sign and
   render_var is the render that full url.

Step 2. Now we have to pass the url in src like given example.

Example: https://www.google.com?Return_URL={{ return_url|url_encode}}

Description: So just call the "return_url" with "url_encode" function in url query string. That will return the encoded url.


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

Thursday 28 February 2019

How to migrate content by admin in drupal 8?

It is easy way to import content in any content type in drupal 8 by admin. We just have to download module and install in our project that is `CSV Importer`. The link of `csv importer` module on drupal Org site is..

CSV Importer Download Link: https://www.drupal.org/project/csv_importer

Description: It supports Taxonomy, Users, Content migration service and this module is also available for Drupal 8.
We are going to attach demo CSV file format as screenshot in this article for better understanding.
Now going to add some screenshots for understanding module.
CSV Importer Module
Install Module process
Module Configuration
Choose entity for migrate
Now we can Choose here Entity type[Content type, Taxonomy, Users] and then content type dropdown will come automatically and in case of taxonomy then taxonomy's dropdown list will come.
Then Upload CSV file same as attached under file screenshot and upload content with easy way.

Demo CSV file Format:
Demo CSV file format

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

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.   

Friday 11 January 2019

How to optimize the website in drupal 8 ?

Sometimes we create the website but that is not quickly responded and we don't get proper users response on site. Sometime our client want to Speed Up the website and we just go through the Admin section and Aggregate CSS and JS files. But that is not properly working as our expectation. So here very first time we have some suggestion in easy way to Speed up the website and that will surly Speed up our website . That is tested with our projects. Please have a look suggestions for Desktop and Mobile both end..

Suggestions:
- Module to speed up site(Image Lazyloader, ADVANCED CSS/JS AGGREGATION)  --> We have added screen shot for checked options.
- Aggregated CSS/JS code.
- Remove extra CSS/JS that is not use full for front page.
- Set required custom image size(image styling) for page images.
- Create custom size of images(Home -> Administration -> Configuration -> Media -> Add image style).
- Follow Google page speed suggestion.
- Reduces Request to server.
- Uninstall extra modules.
- Use Optimized Image.
- Use critical css only ,use only those css/js which you need most.
- Add Async and defer attribute.
- Eliminate render-blocking resources.











Note: If have any suggestions or issue regarding 'How to optimize the website 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...