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?

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