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?

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