Thursday 20 December 2018

How to add custom js file in custom module in drupal 8 ?

It is very simple way to add custom JQuery file in custom module, but we have few methods for this.

Method 1: Our custom libraries(js/css) will be apply on all pages of project.
If we want to add custom js file in whole pages of project then we have to use this method.

1. First we have to create js file like 'gallery.js' file in js folder in our custom module.
2. Then we have to create a 'hook.libraries.yml' file means there hook will be module name.
     
Example: Suppose our Module name will be 'gallery' So we will create file with name of     'gallery.libraries.yml' in custom module folder means this file should be placed with '.routing.yml' file.
3. The code for '.libraries.yml' file is..

image_gallery:
  version: 8.4.5
  js:
    js/gallery.js: {}   
  dependencies:
    - core/jquery
  css:
    theme:
      css/gallery.css: {}


Note: There is a library called image_gallery that when included in a page will deliver the 'js/gallery.js' and 'css/gallery.css' file.

4. Then we have to create '.module' file.

Example: Suppose our Module name is gallery so file name will be 'gallery.module'. There our code for attachment of this library to our module is..

<?php
function gallery_page_attachments(array &$attachments) {
   $attachments['#attached']['library'][] = 'gallery/image_gallery';
}
?>

5. Here 'gallery/image_gallery' means 'module name/libraries name' and in the time of controller function return of page will be written like..
return array('#markup' => t($html)); // here $html is return the result for page.   

Method 2: Our custom libraries(js/css) will be apply only on custom module pages of project.  
1. Whole process and file creation will be same but we will not use attachments code in '.module' file.
2. In this case we just have to create '.libraries.yml' file and apply code..

image_gallery:
  version: 8.4.5
  js:
    js/gallery.js: {}   
  dependencies:
    - core/jquery
  css:
    theme:
      css/gallery.css: {}

     
3. Then in the time of controller function return of page will be written like..
   
return [
    '#markup' => t($html),
    '#attached' => array(
        'library' => array(
            'gallery/image_gallery',
        ),
    ),
];       


here 'gallery/image_gallery' means 'module name/libraries name' and '$html' is the written result for page.

Note: If have any suggestions or issue regarding 'How to add custom js file in custom module in drupal 8 ?' then you can ask by comments.   

Wednesday 12 December 2018

How to disable or hide or exclude the cache from page in drupal 8 ?

Sometimes we want to face the issue that don't want to apply cache or disable cache for particular page on drupal 8. Here we have option that will help in that case and we are going to give an example with this.
First of all we want to show the name of Module that will help in that case that is "Cache Exclude" in drupal 8 or download by link "https://www.drupal.org/project/cacheexclude".
for this just install this module on project and go to the configure page of this module.

Cache Exclude




So juts put the page URL in that "Pages to exclude from caching" textarea as given example of `news`, we want to remove or disable cache from `news` page so put the URL here.
and Check the content type in "Content types to exclude from caching" that checklist. so that's the simple and effective process.

Note: If have any suggestions or issue regarding 'How to disable or hide or exclude the cache from page in drupal 8 ?' then you can ask by comments.   

Tuesday 11 December 2018

How to use country timezone in our Twig file ?

If we want to change the 'DATE' filter in you TWIG file, its easy to use Timezone.
here is the good example for this issue.

Example:
{{ "now"|date("m/d/Y H:i", "Europe/Paris") }}  //For Europe Paris region timezone
{{ "now"|date("m/d/Y H:i", "Asia/Calcutta") }}  //For Asia Calcutta region timezone
{{ "now"|date("m/d/Y H:i", "Europe/Berlin") }}  //For Europe Berlin region timezone

So same like we can use for other countries region time in our TWIG file.


Note: If have any suggestions or issue regarding 'How to use country timezone in our Twig file ?' then you can ask by comments.  

Monday 12 November 2018

How to add JS file using theme file in Drupal 8 ?

Sometimes we add Jquery file by libraries.yml but if we want to add JS file by `.theme` file in drupal 8 so we will add <script> code in `hook_page_attachments_alter`.
There we will create a variable and put the script code and then add in $page['#attached']['html_head'][].
We will add #tag is script and pass the script code variable using this code of line..

\Drupal\Core\Render\Markup::create($javascript_header)
 
here $javascript_header is our script code variable.

Example:
<?php
function hook_page_attachments_alter(array &$page) {   
   
$javascript_header = 'var hmt = hmt || [];
(function()
{
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?1236547890";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);
}
 )();';
        $page['#attached']['html_head'][] = [       
            [       
              '#tag' => 'script',         
              '#value' => \Drupal\Core\Render\Markup::create($javascript_header),       
              '#weight' => -1,
            ],       
            'key'
        ];
   
}
?>
So this is simple way to add JS file in header of project of Drupal 8.

Note: If have any suggestions or issue regarding 'How to add JS file using theme file in Drupal 8 ?' then you can ask by comments.  

Monday 29 October 2018

How to send email programmatically in Drupal 8?

Sometime we need to send email on any events or after creation of blog or article or in any e-commerce site for send confirmation mail after successful completion of order. So In this Blog we are going to explore how to send email programmatically in drupal 8.
We just have to use `hook_mail` function in '.module' file. here two simple steps for send email:

1. Define your properties like Subject, body, headers etc in hook_mail() function.
2. Use Mail Manager to send email.

When we need to send email programmatically, we need to specify the module name that implements hook_mail().
Now have a look of implementation.

<?php

/**
 * Implements hook_mail().
 */

function [module_name]_mail($key, &$message, $params) {
    $options = array(
        'langcode' => $message['langcode'],
    );
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
    switch ($key) {
        case 'create_event':
            $message['from'] = \Drupal::config('system.site')->get('mail');
            $message['subject'] = t('Notification: @subject', array('@subject' => $params['subject']), $options);
            $message['body'][] = SafeMarkup::checkPlain($params['message']);
            break;
    }
}
?>

Here $key is defines one template identified as test_message.
The two other arguments are $params and $message. here $parms is an array of data that needs to go in the email and that is passed from mail manager.
So here is final step for send mail via `mailManager`.

<?php
/**
* Implements hook_entity_insert().
*/

function [module_name]_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
    if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'event')) {
      return;
    }   
    $user_email = \Drupal::currentUser()->getEmail();
    $key = 'create_event';
    $module = <module_name>;
    // mail sending to reviewer users
    $msg1 = "Hello, <br /><br />";
    $msg1.= "Please check your content item, that is published by publisher.";
    $msg1.= "Kind regards";

    $mailManager = \Drupal::service('plugin.manager.mail');
    $to = $user_email;
    $params['message'] = t($msg1);
    $params['subject'] = "Project name workflow for published Notification.";
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $send = true;

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);   

    if ($result['result'] !== true) {
      drupal_set_message(t('There was a problem sending your message.'), 'error');
    }
    else {
      drupal_set_message(t('Your message has been sent.'));
    }   
}
?>

By default, PHPMail, which is use for default_mail() function in PHP. So this will triggered whenever any event will be created, here
$send = the boolean value which is indicating whether the email should be actually sent or not.
$key = template id.


Note: If have any suggestions or issue regarding 'How to send email programmatically in Drupal 8?' then you can ask by comments.  
   

Friday 12 October 2018

How to upload file using URL in drupal 8 programmatically?

Here is a simple way to upload file either file or image by URL in drupal 8. We are going to give an example for this query.
Example: First we need an url like..
        $fileurl = $fileurlval->url;             
        $name = str_replace(' ', '-', strtolower($meta_title).'.pdf');   //here meta_title is the name of your pdf or image
       
        //Get the uploaded file from the url.  
        $filedata = file_get_contents($fileurl);
       
        //Saves a file to the specified destination and creates a database entry.
        $file_directory_name = 'images'; // it means  upload folder name  
        $uploaded_file = file_save_data($filedata, "public://".$file_directory_name."/".$name, FILE_EXISTS_RENAME);
       
        // here "public://" means 'sites/default/files/' folder..
        // here $file_directory_name means we can set any folder where we want to upload..
        // here $name is name of file name..
                           
        if (!empty($uploaded_file)) { 
            $file_arr = array(
                "target_id" => $uploaded_file->id(),
                 "alt" => $uploaded_file->getFilename(),
            );       
       
            $node->field_resources_asset_tagging = $file_arr; // here field_resources_asset_tagging is file field..       
        }

So this is the way to upload file/image in drupal 8 programmatically.  


Note: If have any suggestions or issue regarding 'How to upload file using URL in drupal 8 programmatically?' then you can ask by comments.  
   

Thursday 4 October 2018

How to remove or unset META tag from web page?

If we want to hide or unset or remove META Tag from our web page then we have to use `hook_page_attachments_alter` in `.theme` file.
we have to create an array and pass the name of `META name` which we want to remove or unset from web page.
like..
$unset_meta = [
    'title', // Meta name "title"
    'description', // Meta name "description"
    'keywords', // Meta name "keywords"
    'Generator'     // Meta name "Generator"
];

then with the help of $page['#attached']['html_head'], page attachments html_head we have to check that meta name if exist then we have to unset this.
we are giving here an example for this..

Example:
function moldev_page_attachments_alter(array &$page) { // here moldev is my theme name.
 // Define an array of META tags to remove.
   $unset_meta = [
    'title', // Meta name "title" 
    'description', // Meta name "description"
    'keywords', // Meta name "keywords"
    'Generator'     // Meta name "Generator"   
   ];
  // Check values and delete.
   foreach ($page['#attached']['html_head'] as $key => $value) {
     if (in_array($value[1], $unset_meta)) unset($page['#attached']['html_head'][$key]);
   }
}

if you want to delete/remove/unset any link rel="alternate" and hreflang="en" or any language then follow the below given code.
foreach ($page['#attached']['html_head_link'] as $key => $attachment) {   
          if ($attachment[0]['rel'] == 'alternate' && $attachment[0]['hreflang'] == 'en') {
               unset($page['#attached']['html_head_link'][$key]);
          }
}

Note: If have any suggestions or issue regarding 'How to remove or unset META tag from web page?' then you can ask by comments.  

Monday 17 September 2018

How to create Schema in custom module drupal 8?

When we need to create our custom module table, So we have to create schema file in custom module root like if our module name is `crudform`, so in the folder of module we will create file which name is `crudform.install`. here our file extension will be `.install` for schema.
In the file we will create function `hook_schema()` with name of `crudform_schema()` and there we will define create structure of table with table name, we have an example for this, Please have a look..

Schema database

function crudform_schema() {
  $schema['crudform'] = array(
    'fields' => array(
          'id'=>array(
            'type'=>'serial',
            'not null' => TRUE,
          ),
          'name'=>array(
            'type' => 'varchar',
            'length' => 40,
            'not null' => TRUE,
          ),
           'email'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
            'city'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
            'country'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
          'message'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

In that function crudform_schema(), our database table name will be `crudform`. here we will define table fields and structure and then return the schema. When we will install our custom module then this table with schema will automatically create in database and with the help of this we can store data in our custom table.


If we want to store default data on table then we have to use `hook_install` function In case of installation of module that data will store automatically. We have an example for this, please have a look..

function crudform_install() {
  $database = \Drupal::database();
  // Add default entry in table.
  $fields = array(
    'name' => 'Sahil',
    'email' => 'sahil@gmail.com',
    'city' => 'Delhi',
    'country' => 'India',
    'message' => 'Hello text',
  );
  $database->insert('crudform')
    ->fields($fields)
    ->execute();
  
  // Add one another entry on this table.
  $fields = array(
    'name' => 'Abhi',
    'email' => 'abhi@gmail.com',
    'city' => 'Delhi',
    'country' => 'India',
    'message' => 'Hello text world',
  );
  $database->insert('crudform')
    ->fields($fields)
    ->execute();
}

There we are creating a $fields array with few data and then store by insert query.
So that's a simple process of 'create schema in drupal 8 custom module'.


Note: If have any suggestions or issue regarding 'How to create Schema in custom module drupal 8?' then you can ask by comments.   

Friday 14 September 2018

What is right query structure for drupal 8?

Here we are defining our drupal 8 query structure with easy mode. You can find/search here INSERT, SELECT, UPDATE, DELETE.
We will explain in easy way with an examples, Please have a look..
That is our table `testing_form` structure..

id candidate_name candidate_mail candidate_number candidate_dob
1 John john@gmail.com 1236547890 2014-10-22
2 Mary mary@gmail.com 5698741230 2014-10-23
3 Karen karen@gmail.com 0123654789 2014-10-23

INSERT Query Structure:
According to php we will define INSERT Query as:

$insert_query = "INSERT INTO testing_form (candidate_name, candidate_mail, candidate_number, candidate_dob) VALUES ('sahil', 'sahil@gmail.com', '9874563210', '22-11-1990')";
mysqli_query($connection, $insert_query);

And now in case of drupal 8, our structure will be.

$fields = array(
    'candidate_name'   => 'sahil',
    'candidate_mail'   => 'sahil@gmail.com',
    'candidate_number' => '9874563210' ,
    'candidate_dob'    => '22-11-1990',           
);
db_insert('testing_form')
    ->fields($fields)
    ->execute();
   
Here 'testing_form' is table name and $fields variable is the data for fields of table.


SELECT Query Structure:
According to php we will define SELECT Query as:

$select_query = "SELECT * from testing_form where id = '2' and id != '3'";
mysqli_query($connection, $select_query);

And now in case of drupal 8, our structure will be.

$result = db_select('testing_form', 't')
    ->fields('t')
    ->condition('id', 2, '=')
    ->condition('id', 3, '!=')
    ->execute()
    ->fetchAll();
   
Here 'testing_form' is table name and our condition is all 2nd id candidate come but not come on 3rd id candidate.

We have some other method for SELECT query with connection in drupal 8..

$connection = \Drupal\Core\Database\Database::getConnection();
$results = $connection->query('select candidate_name, candidate_mail, candidate_number, candidate_dob')->fetchAll();


UPDATE Query Structure:
According to php we will define UPDATE Query as:

$update_query = "UPDATE `testing_form` set candidate_name='karen sood' where id='3'";
mysqli_query($connection, $update_query);

And now in case of drupal 8, our structure will be.

$update_query = \Drupal::database()->update('testing_form')
          ->fields(array('candidate_name' => 'karen sood', 'candidate_number' => '1236547890'))
          ->condition('id', '3')         
          ->execute();
   
Here 'testing_form' is table name and our condition is id number `2nd` of candidate data will update.

 
DELETE Query Structure:
According to php we will define DELETE Query as:

$delete_query = "DELETE from `testing_form` where id='3'";
mysqli_query($connection, $delete_query);

And now in case of drupal 8, our structure will be.

$delete_query = \Drupal::database()->delete('testing_form');
      ->condition('id', '3');   
      ->execute();
   
Here 'testing_form' is table name and our condition is id number `3rd` of candidate data will delete.


So these all are INSERT, SELECT, UPDATE, DELETE queries structure for Drupal 8. Next time we will come with `JOINS`, like how to use `joins` in drupal 8 query with many of conditions.



Note: If have any suggestions or issue regarding 'What is right query structure for drupal 8?' then you can ask by comments.  

Tuesday 11 September 2018

Steps for Add Custom or Add More Language on website.

If we want to add custom language or add multiple languages on our drupal website then we have to add and install `Language Module` first.


Install Language module



Then click on the Configure link or go with this link "/admin/config/regional/language".
Language List

and then you can add custom language by choose last option "Custom Language". After choose you will be redirect in this page.

Choose Custom or other language option
If we are choosing default languages that given by module then automatically will be added on list, but in case of last option custom language we will reach in this page.

Set Custom language code and name

After this you will redirect to listing page of added languages.
Language list
here we can set our default language that will automatically display in language list.

After that we have to check the "Show language selector on create and edit pages" option on content type edit page in "language settings".
Content type edit page for add dropdown option

Then you will be get the language drop-down in body/description type fields on node form.
So this is the simple steps for Add Custom or Add more language in website.



Note: If have any suggestions or issue regarding 'Steps for Add Custom or Add More Language on website.' then you can ask by comments.  

Thursday 6 September 2018

Media entity fields render in drupal 8 Node Twig template.

If we want to load media entity fields on node twig template. It's easy to load media entity, Please have a look..

{# call to media entity fields on node twig #}

{% for key, item in node.field_document_entity_browser %} 
// This is the node field which is connect to media field `field_document_entity_browser`..
{% if node.field_document_entity_browser[key].entity %}
// here we are rendering media entity field which machine name is `field_capt2120`..                           
{{ node.field_document_entity_browser.entity.field_capt2120[key].value }}

// here we are rendering media entity image field which machine name is `field_media_image`..        
{%if item.entity %}
{% set media = item.entity %}
{% set file = media.field_media_image.entity %}
{% set uri = file_url(file.uri.value) %}
                              
<img src="{{ uri }}" alt="{{ media.name.value }}" />
                          
 {% endif %}                           
                                                                                     
 {% endif %}
  {% endfor %}



Note: If have any suggestions or issue regarding 'Media entity fields render in drupal 8 Node Twig template.' then you can ask by comments.  

Wednesday 5 September 2018

Paragraph fields render in drupal 8 Node Twig template.

If we want to load paragraph entity fields on node twig template. It's easy to load paragraph entity, Please have a look..

{# call to paragraph entity fields on node twig #}

{{ node.field_professional_features.entity.field_professional_services_name.value }}
 // here `field_professional_features` is the content type field and `field_professional_services_name` is the related paragraph field..

{{ node.field_professional_features.entity.field_professional_services_summ.value }}
  // here `field_professional_features` is the content type field and `field_professional_services_summ` is the related paragraph field..

// here we are calling paragraph image field..

{% for key, image in node.field_professional_features %}
// here `field_professional_features` is the content type field..
{%if image.entity %}
{% set paragraph = image.entity %}
{% set file = paragraph.field_professional_services_imag.entity %}
 // here `field_professional_services_imag` is the related paragraph field..
{% set uri = file_url(file.uri.value) %}

<img src="{{ uri }}" alt="{{ paragraph.name.value }}" />

{% endif %}
{% endfor %} 



Note: If have any suggestions or issue regarding 'Paragraph fields render in drupal 8 Twig template.' then you can ask by comments.  

Tuesday 4 September 2018

Replace any string or value in twig template variable.

If we want to Replace the value in twig template then we have an example and syntax, please have a look..
{#
    ****  replace '-' with '$' sign in vidyard ID ****  
#}

{% set twig_content_variable  = node.field_resources_vidyard_id.value  %}   // here we are applying on field_resources_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: If have any suggestions or issue regarding 'Replace any string or value in twig template variable.' then you can ask by comments. 

Programmatically Media load in drupal 8.

If we want to load Media entity. we have to add library on the top of page. ( use Drupal\media\Entity\Media; )
Then its easy to load media entity by the syntax.
   
Syntax:
$media_detail = Media::load($mid);    // here $mid is media entity id       
   
now if we want to get image field data of media field then syntax is..

$media_img = file_create_url($media_detail->field_media_image->entity->getFileUri());
 // here field_media_image is field name in media entity
   
now if we want to get any text field value then syntax will be..

$media_caption = $media_detail->get('field_capt2120')->getValue();   
// here field_capt2120 is the machine name of caption field in media entity    

foreach($m_caption as $mkey){
   $capval = $mkey['value'];    // here we will get the caption value           
}


Note: If have any suggestions or issue regarding 'Programmatically Media load in drupal 8.' then you can ask by comments.   

Thursday 30 August 2018

Programmatically Node load and Multiple Node load in drupal 8.

In drupal 7, we have node_load($nodeid) for load the node but now in drupal 8 syntax is changed and now node load by Node::load($nodeid) or Add the name space at the top of the page. \Drupal\node\Entity\Node::load($nodeid);

If we are using Symfony library and calling name space

use Drupal\node\Entity\Node;

So we do not need to use node class in node::load, we just need the syntax like Node::load($nodeid);

but if we are not calling or render name space then for node load we need to use the syntax like

\Drupal\node\Entity\Node::load($nodeid);

For get the node detail fields by Node::load($nodeid) syntax is..

Example: This example is for single node load.

              $node_detail = Node::load($nodeid);

                                   OR

              $node_detail = \Drupal\node\Entity\Node::load($nodeid);

              $node_id = $node_detail->id();

              $node_title = $node_detail->getTitle();

              $node_status = $node_detail->isPublished();

              $node_type = $node_detail->type->target_id; 

              $node_field_select_id = $node_detail->get('field_machine_name')->target_id;

              $node_field_select_value = $node_detail->get('field_machine_name')->value;

--------------------------------------------------------------------------------------------------------------------------

In drupal 8 for load multiple nodes of any `Content Type`, we have Node::loadMultiple() and Drupal::entityQuery() functions for load all the nodes of given content type. We have an Example with Syntax for this, please have a look.
Syntax:
$all_nids = \Drupal::entityQuery('node')->condition('type','write content type machine name ')->execute();

Then pass the $get_all_nids variable to Node::loadMultiple function for get data..

$nodes = \Drupal\node\Entity\Node::loadMultiple($get_all_nids);

Example:
    $nids = \Drupal::entityQuery('node')->condition('type','applications')->execute(); // There application is my content type machine name..
    $node_detail = \Drupal\node\Entity\Node::loadMultiple($nids);
    foreach ($node_detail as $node){  // In node_detail array we have all nodes details..
        // here we are fetching fields detail.
        $title = $node->getTitle();
        $application_category_id = $node->field_application_category->target_id;       
        $img = file_create_url($node->field_application_image->entity->getFileUri());
        $image_gallery .='<div class ="imggallery"><img src="'.$img.'"><p>'.$title.'</p></div>';
    }
    // here returning $image_gallery array with image_gallery detail.
    return array(
    '#markup' => t($image_gallery),
    );       

   
Note: If have any suggestions or issue regarding 'Programmatically Node load and Multiple Node load in drupal 8. ' then you can ask by comments.   

Thursday 23 August 2018

How we can Url Alias in Drupal 8?

If you want to path alias in drupal 8 then we have different syntax in drupal 8, Please follow this.
Syntax:
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($tid or $nid);

Example: like if we have taxonomy term and we want to path alias so first we create URL path as given exmaple..

$tid = '/taxonomy/term/'.$term_id;
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($tid); or \Drupal::service('path.alias_manager')->getAliasByPath('/taxonomy/term/'.$term_id),

OR

$nid = '/node/'.$node_id;
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($nid); or \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$node_id),


Simple then we can use this alias to send or redirect using
$response = new Symfony\Component\HttpFoundation\RedirectResponse($alias);
$response->send();
return; 


Note: If have any suggestions or issue regarding 'How we can Url Alias in Drupal 8?' then you can ask by comments.

Monday 20 August 2018

How to render fields on node twig templates?

It is easy way to render node fields on node template. We just have to create template file according to content type machine name like 'landing page' is content type, So machine name will be 'landing_page', but our template name will be 'node--landing-pages--full.html.twig' as per Drupal 8(Symphony) Syntax.

and we will call/render fields like..


Node id: {{ node.id }} // Node id

Node Url: {{ url }}  // current page url

Node Title: {{ label }}  // Node title

Node Bundle: {{ node.bundle }}  // Node bundle its means content type name

Node Publish Status: {{ node.isPublished() }}  // Retrun node is published or not

Node Created Time: {{ node.getCreatedTime() }}  //will return node created timestamp

Node Plain(Text) Field: {{ node.field_machine_name.value }}  //will return node plain field value

Node Image: {{ file_url(node.field_full_banner_image.entity.fileuri) }} or {{ file_url(node.field_full_banner_image.entity.uri.value) }}  // show url of full banner image is the image field in node

Node Description/body: {{ content.body }}

Node Link field: {{ node.field_machine_name.0.url }}

Node Link Field Title Value: {{ node.field_machine_name.0.title }}

Node custom field: {{ content.field_machine_name }}  or {{ content.field_machine_name[0] }}  // ex:{{ content.field_resources_content_type }}

If you want to check field value return or not the we have multiple options like.
// here we are checking field banner video return or not.
{% if content.field_banner_video|render %}  
  // write comment here..
{% endif %}

OR

// here we are checking field carousel title is empty or not.
{% if content.field_carousel_title[0] is not empty %}
  // write comment here..
  {{ content.field_carousel_title[0] }}
{% endif %}


Split array in twig:

We have split option also in twig file in symphony, please have a look.
{% set videogal_value_variable = videogall|split('~~') %}
like 'videogall' is an array and separated by ~~ sign so we will do like this for break and use.
{{ videogal_value_variable.0 }}
{{ videogal_value_variable.1 }}
and so on.


Note: If have any suggestions or issue regarding 'How to render fields on node twig templates' then you can ask by comments.

Thursday 9 August 2018

drupal 8 images with custom style.

If we want to apply the custom styling on image path then we have to create first with go to Configuration -> media -> image styles or /admin/config/media/image-styles
then click on Add image style and according to requirement choose effect option like Convert, Crop, Resize, Rotate, Scale, Scale and Crop, Desaturate and apply height/width and save it, then get the machine name of your custom create style and apply like this syntax.

Image style listing

Add new image style

Apply Effect


Call the ImageStyle library on header of file.
use Drupal\image\Entity\ImageStyle;

Then get the uri of image..

$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_machine_name')->buildUrl($path);   

OR direct use this syntax..
$product_image = \Drupal\image\Entity\ImageStyle::load('related_products')->buildUrl($nodeload->field_banner_image->entity->getFileUri());   

here 'related_products' is the machine name of custom image style and 'field_banner_image' is the machine name of banner image, and this is $nodeload->field_banner_image->entity->getFileUri() the uri of banner image by node::load.

Note: If have any suggestions or issue regarding 'drupal 8 images with custom style.' then you can ask by comments.

Vocabulary or Taxonomy load in Drupal 8.

If we have vocabulary/taxonomy name then we can easily load by loadTree, follow the syntax.

$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('write vocabulary machine name here');
foreach ($tree as $term) {
  echo $term->tid.' - '.$term->name;
}

Example:
$select_category .= '<select><option value="0">- Select -</option>';
$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('product_family'); //here product_family is machine name of Product Family taxonomy.
foreach ($tree as $term) {
$select_category .= '<option value="' . $parent . '_' . $term->tid . '">' . $term->name . '</option>';
}
$select_category .= '</select>';


Note: If have any suggestions or issue regarding 'Vocabulary or Taxonomy load in Drupal 8.' then you can ask by comments.

Tuesday 7 August 2018

How to render fields on Taxonomy twig templates?

It is easy to call/render taxonomy fields on taxonomy template. We just have to create template file according to vocabulary machine name like 'application landing page' is taxonomy and machine name will be 'application_landing_page', but our template name will be 'taxonomy-term--application-landing-page.html.twig' as per Drupal 8(Symphony) Syntax.

and we will call/render fields like..


Term id: {{ term.id }}  // term id

Term Url: {{ url }}  // current page url

Term Title: {{ term.label }}  // term title

Term Image: {{ file_url(term.field_product_group_image.entity.uri.value) }}  // show url of product group image is the image field in taxonomy

Term Description/body: {{ content.description }}

Term Link field: {{ term.field_link.0.url }}

Term Link Title field: {{ term.field_link.0.title }}

Term custom field: {{ content.field_machine_name }}


If we want to check any field value exist or not then we are giving an example like we have field 'line of business' so machine name will be line_of_busines and we will check by..

{% if content.field_line_of_busines is not empty %}

{{ content.field_line_of_busines }}

{% endif %}



Note: If have any suggestions or issue regarding 'How to render fields on Taxonomy twig templates' then you can ask by comments.

Monday 6 August 2018

Programmatically add canonical, shortlink, viewport and robots in site header.

For add Programmatically, first we will work on .theme file, we will create alter attachments in .theme file like 'theme_name_page_attachments_alter(array &$page).
Code for add 'viewport' in html head is..
<?php
function theme name/module name_page_attachments_alter(array &$page) {
    $viewport = [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'viewport',
        'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
      ],
    ];
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];

global $base_url;
$current_page = \Drupal::request()->getpathInfo();   
$canon_url = $base_url.''.$current_page;  
  
Code for add 'canonical' in html head is..
    $viewport_canonical = [
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'canonical',
        'href' => $canon_url,
      ],
    ];
    $page['#attached']['html_head'][] = [$viewport_canonical, 'canonical'];   

Code for add 'shortlink' in html head is..
    $viewport_shortlink = [
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'shortlink',
        'href' => $canon_url,
      ],
    ];
    $page['#attached']['html_head'][] = [$viewport_shortlink, 'shortlink'];       
       

For add robots programmatically on site header, we have to work on 'theme_name_preprocess_html(&$variables).
Code for add 'robots' in html head is..
    $noindex = [
        '#tag' => 'meta',
        '#attributes' => [
            'name' => 'robots',
            'content' => 'noindex, nofollow',
        ],
    ];
    $variables['page']['#attached']['html_head'][] = [$noindex, 'noindex'];     

?>

Note: If have any suggestions or issue regarding 'Programmatically add canonical, shortlink, viewport and robots in site header.' then you can ask by comments.

Create custom twig file and include in twig file.

For create custom twig file,
Example 1: We just have to create a file like 'instrument.html.twig' so for include this file simple code is..
     {% include('instrument.html.twig') %}

Example 2: We just have to create a file like 'consumable.html.twig' so for include this file simple code is..
     {% include('consumable.html.twig') %} 

Example 3: We just have to create a file like 'abc.html.twig' so for include this file simple code is..
     {% include('abc.html.twig') %}


Note: If have any suggestions or issue regarding 'include twig file' then you can ask by comments.

Naming convention for node/content type template in drupal 8.

The naming convention of node/content type is very simple and we will explain by example here..

Example 1. If we have content type with name of 'customer story' so our this content type machine name will be 'customer_story' but we will take as a 'node--customer-story--full.html.twig' in naming convention.

Example 2. If we have content type with name of 'products' so our this content type machine name will be 'products' but we will take as a 'node--products--full.html.twig' in naming convention.

Example 3. If we have basic page single node like node id '58', So we will take as a 'node--58.html.twig' in naming convention.


Note: If have any suggestions or issue regarding 'Naming convention for node/content type template' then you can ask by comments.

Friday 3 August 2018

Naming convention for taxonomy template in drupal 8.

The naming convention of taxonomy is very simple and we will explain by..

Example 1. If we have taxonomy with name of 'product groups' so our this taxonomy machine name will be 'product_groups' but we will take as a 'taxonomy-term--product-groups.html.twig' in naming convention.

Example 2. If we have taxonomy with name of 'service support' so our this taxonomy machine name will be 'service_support' but we will take as a 'taxonomy-term--services-support.html.twig' in naming convention.


Note: If have any suggestions or issue regarding 'Naming convention for taxonomy template' then you can ask by comments.

Multiple images store in variable and render on twig file.

Yes, we have option for render multiple images on any template file. We just have to create variable in .theme file and collect in array and then print array value by variable.

Example: First we have to take the step on hook_preprocess_node(&$variables). we have to check node value is available or not.

if(isset($variables['node'])){

    $node = $variables['node'];

    $current_node_id = $node->id(); //get the current node id

    $node_type = $node->type->target_id;  //get the current node type

    if($node_type == "applications"){  // we are going with example of applications content type nodes..
  
    /*  Now we will get the fields by node::load  */
  

    $categoryid = $node->get('field_category')->target_id; //here field_category is Category field machine_name..

        $category_detail = \Drupal\taxonomy\Entity\Term::load($categoryid);

        $variables['category_name'] = $category_detail->name->value;  // get the category name

        $variables['landing_page']  = $category_detail->field_setup_landing_page->value;  // get the field_setup_landing_page field value     

        /* here 'category_name' and 'landing_page' is our variable keys */    

        $node_detail = Node::load($current_node_id);                          


        $node_id = $node_detail->id();                   // get the node id

        $node_title = $node_detail->getTitle();          // get the node title

        $node_Published = $node_detail->isPublished();   // get the publish status

        $node_type = $node_detail->getType();            // get the node type

        $node_field_model_value = $node_detail->get('field_model')->value;   // get the field model value

        $node_field_price_value = $node_detail->get('field_price')->value;   // geth the field price value

         $img_urls = array();
        foreach ($node_detail->field_image as $item) { // get the field image with multiple image url
          if ($item->entity) {
            $img_urls[] = $item->entity->url();
          }
       
        }


        /* Now put the all values in array with keys for differentiate */

        $arr = array('id'       => $node_id,

                     'title'    => $node_title,

                     'published'=> $node_Published,

                     'type'     => $node_type,

                     'model'    => $node_field_model_value,

                     'price'    => $node_field_price_value,

                     'image'    => $img_urls

        );


        /* Now pass the $arr in final productfields variable like this.. */

        $variables['productfields'] = $arr;  

        This is our final product fields variable now we have to move on applications type twig file because we are working for specially applications type of contents.

        Suppose are applications type twig file name is 'node--applications--full.html.twig'. That file is for applications detail pages.

        <ul>

        {% for key, value in productfields %}
        {% if key == 'image' %}
            <ul>
            {% for keys, imgvalue in value %}
                <li class="{{ keys }}"><img src="{{ imgvalue }}"></li>
            {% endfor %}
            </ul>
        {% endif %}
        {% endfor %}  

        </ul>

  /* here 'productfields' is same variable name which we are created in 'hook_preprocess_node(&$variables)' hook in .theme file, so we just have to print the array keys and value by for loop in Symphony syntax, So that is the easy way to create custom variable and then render values in twig file. */

    }      

}

Note: If have any suggestions or issue regarding 'Multiple images store in variable and render on twig file.' then you can ask by comments.

Thursday 2 August 2018

Create custom variable in drupal 8 and render on template file.

We have alternate option for custom variable in drupal 8. Now we will going to describe that how to create custom variable and use on any template file.
here we are going to giving an example with easy steps for custom variable use and render on file.
Example: First we have to take the step on hook_preprocess_node(&$variables). we have to check node value is available or not.
if(isset($variables['node'])){
    $node = $variables['node'];
    $current_node_id = $node->id(); //get the current node id
    $node_type = $node->type->target_id;  //get the current node type
    if($node_type == "products"){  // we are going with example of products content type nodes..
   
    /*  Now we will get the fields by node::load  */
   
    $categoryid = $node->get('field_category')->target_id; //here field_category is Category field machine_name..
        $category_detail = \Drupal\taxonomy\Entity\Term::load($categoryid);
        $variables['category_name'] = $category_detail->name->value;  // get the category name
        $variables['landing_page']  = $category_detail->field_setup_landing_page->value;  // get the field_setup_landing_page field value
       
        /* here 'category_name' and 'landing_page' is our variable keys */
       
        $node_detail = Node::load($current_node_id);                           

        $node_id = $node_detail->id();                   // get the node id
        $node_title = $node_detail->getTitle();          // get the node title
        $node_Published = $node_detail->isPublished();   // get the publish status
        $node_type = $node_detail->getType();            // get the node type
        $node_field_model_value = $node_detail->get('field_model')->value;   // get the field model value
        $node_field_price_value = $node_detail->get('field_price')->value;   // geth the field price value
        $node_field_image_value = $node_detail->get('field_image')->entity->uri->value; // get the field image with single image url

        /* Now put the all values in array with keys for differentiate */
        $arr = array('id'       => $node_id,
                     'title'    => $node_title,
                     'published'=> $node_Published,
                     'type'     => $node_type,
                     'model'    => $node_field_model_value,
                     'price'    => $node_field_price_value,
                     'image'    => $node_field_image_value
        );

        /* Now pass the $arr in final productfields variable like this.. */
        $variables['productfield'] = $arr;
       
        This is our final product fields variable now we have to move on products type twig file because we are working for specially products type of contents.
        Suppose are products type twig file name is 'node--products--full.html.twig'. That file is for products detail pages.
        <ul>
        {% for key, value in productfield %}
       
        <li>{{ key }} | {{ value }}</li>
       
        {% endfor %}   
        </ul>
       
        /* here 'productfield' is same variable name which we are created in 'hook_preprocess_node(&$variables)' hook in .theme file, so we just have to print the array keys and value by for loop in Symphony syntax, So that is the easy way to create custom variable and then render values in twig file. */
    }
       
}

Note: If have any suggestions or issue regarding 'Custom variable in drupal 8 and render on template file.' then you can ask by comments.

Monday 23 July 2018

Drupal entity render on twig template.

We have few short codes or cheat codes for render views or blocks, entity, menu, field, form on twig template. This will help to publish all these things on twig file in easy way. we have some examples for easy to use these short code, Please have a look,
First thing most important is that we have to install 'Twig tweak' module on site that is required for render views, block and entity on twig file.
link for twig tweak module is https://www.drupal.org/project/twig_tweak

Render View on twig file:
{{ drupal_view('view_machine_name', 'block or view machine_name') }}
example:-  {{ drupal_view('application_resources', 'block_10') }}  

Render Block on twig file: 
{{ drupal_block('block_machine_name', wrapper=false) }}
example:-  {{ drupal_block('bartik_breadcrumbs') }}

Render Region on twig file: 
{{ drupal_region('sidebar_first') }}

Render Entity on twig file:
{{ drupal_entity('block_content', 1) }}

Render entity edit form:
{{ drupal_entity_form('node', 1) }}
/* here 1 is node id.*/

Render entity add form:
{{ drupal_entity_form('node', values={type: 'page'}) }}

Render single entity field:
{{ drupal_field('field_image', 'node', 1) }}
/* here field_image is from node 1 */

Render menu on twig file:
{{ drupal_menu('main') }}  or {{ drupal_menu('footer') }}
/* here main and footer parameter is the name of menu machine_name. */

Render any form on twig file:
{{ drupal_form('Drupal\\search\\Form\\SearchBlockForm') }}
/* here we are calling search block form. */



Note: If have any suggestions or issue regarding 'Drupal entity render on twig template' then you can ask by comments.

Friday 20 July 2018

Programmatically render Block in a twig template drupal 8.

In drupal 7 syntax of render block in twig template is.

$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

But now in drupal 8 syntax is changed, but first we have to install "Twig tweak" module that provides
a twig extension with useful functions an filters that can improve development experience.
here is the link for twig tweak module, please download from here..
https://www.drupal.org/project/twig_tweak
there will be cheat sheet for drupal 8 that helps in calling/render block or views in twig template file.

Drupal_view render..

Suppose we have to render/call view in twig template then syntax will be
{{ drupal_view('view_machine_name', 'block/page machine name') }}
Example:
{{ drupal_view('product_overview_video', 'block_2') }} 
here 'product_overview_video' is view machine name and 'block_2' is we created 2nd block on this view.

Drupal_block render..
Suppose we have to render/call block in existing block then our syntax will be
{{ drupal_block('block_machine_name', wrapper=false) }}
 Example:
{{ drupal_entity('block_content', 27) }}
here block_content is block machine name and 27 is block id.
OR
 {{ drupal_block('bartik_breadcrumbs') }}
we can direct call block by machine_name like breadcrumbs block. we just have to put the drupal_block function with machine_name and clear the cache and it will work.

Note: If have any suggestions or issue regarding 'Programmatically render Block in a twig template' then you can ask by comments.

Taxonomy terms load in drupal 8.

In drupal 7, we have taxonomy_term_load($tid), taxonomy_term_load_multiple($tids) functions for load the taxonomy term or multiple terms but now in drupal 8 syntax is changed and now Single/Multiple term load by Term::load($tid)
or
Add the name space at the top of the page.
\Drupal\taxonomy\Entity\Term::load($tid);

If we are using Symfony library and calling name space 
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy;

or direct use in function calling time like  \Drupal\taxonomy\Entity\Term::load($tid);

Example:
$term_detail_array = \Drupal\taxonomy\Entity\Term::load($tid);
or
$term_detail_array = Term::load($tid); //if we are already using taxonomy library..

Then get the fields detail by $term_detail_array like,

Term id:  $term_detail_array ->tid->value;
Term name:  $term_detail_array ->name->value;
Term manually added field:  $term_detail_array ->get('field_machine_name')->value;  // manually added field value..
Term image field:  $term_detail_array ->field_machine_name->entity->getFileUri();

 If we have field with entity reference then field value will be in form of $term_detail_array ->get('field_machine_name')->target_id;
or
If we have field without entity reference then field value will be in form of $term_detail_array ->get('field_machine_name')->value;

Now we will discuss on Term::loadMultiple.
And the syntax is $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids); // here $tids is the array of multiple tid..
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids); 
foreach ($terms as $term) {  //then the fields value will be..
$term_id = $term->tid->value;
$term_name = $term->name->value;
$term_file field = $term->field_machine_name->uri;
}
and so on..

Note: If have any suggestions or issue regarding 'Taxonomy terms load in drupal 8' then you can ask by comments.

Thursday 19 July 2018

User load by mail in drupal 8.

Yes, we can load the user detail by mail id in drupal 8. As per drupal syntax first we have to add user library for classes then we will user drupal load by mail function that is "user_load_by_mail()".

$check_user = user_load_by_mail($mailid);
 if (!empty($check_user)) {
     $uid = $check_user->id();
     $user_detail = \Drupal\user\Entity\User::load($uid);
                $user_id= $user_detail->get('uid')->value;
                $user_roles = $user_detail->getRoles();
                $user_status = $user_detail->isActive();
                $user_name = $user_detail->getUsername();
                $user_body = $user_detail->get('body')->value;               
                $user_email = $user_detail->get('mail')->value;
                $user_created_time = $user_detail->created->value;
                $user_field = $user_detail->get('field_machine_name')->value;  
                $user_loggedin_check = $user_detail ->login->value; // that will return 1 or 0
                if ($user_detail->login->value != 0) {
                    $first_login_data = date('Y-m-d H:i:s', $user_detail->login->value);
                } else {
                    $first_login_data = 'never';
                }
  }

Note: If have any suggestions or issue regarding 'User load by mail in drupal 8' then you can ask by comments.

Programmatically User load and User load Multiple in drupal 8.

In drupal 8 User::load, we have to use library and calling name spaceuse Drupal\user\Entity\User;

So same as node::load, we can use User::load($userid);
or
we can direct call \Drupal\user\Entity\User::load($userid);

For get the user detail fields by User::load($userid) syntax is..

Example: This example is for single user load.
                $user_detail = User::load($userid);       
                                    OR
                $user_detail = \Drupal\user\Entity\User::load($userid);
           
                $user_id= $user_detail->get('uid')->value;
                $user_roles = $user->getRoles();
                $user_status = $user_detail->isActive();
                $user_name = $user_detail->getUsername();
                $user_body = $user_detail->get('body')->value;               
                $user_email = $user_detail->get('mail')->value;
                $user_created_time = $user_detail->created->value;
                $user_field = $user_detail->get('field_machine_name')->value;  

Example: This example is for multiple user load.
First you have to use user library and calling name space
use  \Drupal\user\Entity\User;

                $users = User::loadMultiple($ids);
                foreach($users as $u) {
                   $users_mailid= $u->getEmail();
                   $user_id= $u->get('uid')->value;
                   $user_name = $u->getUsername();
                   $field_value = $u->get('field_machine_name')->value;
                 } 

Note: If have any suggestions or issue regarding 'Programmatically User load and User load Multiple in drupal 8.' then you can ask by comments.

Monday 16 July 2018

Page Redirection programmatically in drupal 8.

In drupal 8 for page redirection, we have to use Symfony components class. Here page redirection is done by 'RedirectResponse' class from Symfony HttpFoundation. In drupal 7 we using drupal_goto() function for redirect.
But in case of drupal 8, RedirectResponse' class is..

use Symfony\Component\HttpFoundation\RedirectResponse;

and suppose redirection page is node 2691 so we will give redirect url is '/node/2691'.
Example:
$url = '/node/2691';
return new RedirectResponse($url);

               OR

$redirect_variable = new Symfony\Component\HttpFoundation\RedirectResponse('/node/2691');     $redirect_variable ->send();
 return;

     For front page redirection, we can use..

return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('<front>'));

             OR
 In Function we can use redirect..
 public function submitForm(array &$form, FormStateInterface $form_state) {
   $form_state->setRedirect('redirect router name');
Example:
  $form_state->setRedirect('account_login.content');
 }

Note: If have any suggestions or issue regarding 'Page Redirection programmatically in drupal 8' then you can ask by comments.

Thursday 12 July 2018

Custom login create in drupal 8.

We are trying to clear the code of custom login with authentication. here we have the code.

 // Authentication of username and password..
$uid = \Drupal::service('user.auth')->authenticate($username,$password);
// Get the user id by database and load..
$user = \Drupal\user\Entity\User::load($uid);
// finally pass the user detail array in user login function..
 user_login_finalize($user);

Example:
 Like we have username and password by POST method and fields are.
<input id="login-username" type="text" class="form-control" name="name" value="" placeholder="username">
<input id="login-password" type="password" class="form-control" name="pass" placeholder="password">

so for got these credentials in function the code is.
$username = \Drupal::request()->request->get('name'); // form username
$password = \Drupal::request()->request->get('pass'); // form password

And the final code for login..

 $uid = \Drupal::service('user.auth')->authenticate($username,$password);
 $user = \Drupal\user\Entity\User::load($uid);
 user_login_finalize($user);
 
Note: If have any suggestions or issue regarding 'Custom login create in drupal 8' then you can ask by comments.

Get the current logged in user detail.

We have the syntax of current logged-in user detail, Please have a look.

1. Logged-in user id :    $uid = \Drupal::currentUser()->id();
2. Current User Detail Array :     $current_user_detail = \Drupal::currentUser();
3. Current Logged-in User Role Array: $current_user_role = \Drupal::currentUser()->getRoles();     
If we have multiple roles for single user and we have to check one role is exist or not in roles array.
Syntax..
if(in_array("my_role", $current_user_role )){         
   \\ my role exist in this array..
}

4. Current User Default Language : $langcode = \Drupal::currentUser()->getPreferredLangcode();

 
Note: If have any suggestions or issue regarding 'Get the current logged in user detail' then you can ask by comments.

Friday 6 July 2018

Render view fields in custom view template in drupal 8.

First we have to create view according to our requirement and then create the custom view template file, suppose our view machine name is 'customer_story' and on 'block_1', so our template file name will be 'views-view-fields--customer-story--block-1.html.twig'.
and we can render our views fields variables like..

{{ fields.title.content }} //for title field
{{ fields.field_machine_name.content }} //for any other field render.
{{ file_url(fields.field_landing_page_image.content) }} //for image field render
{{ fields.field_page_url.content }}  //for link field render

you can get these variable name by 'custom text field' "Replacement pattern" settings.

Note: If have any suggestions or issue regarding 'Render view fields in custom view template in drupal 8' then you can ask by comments.

Thursday 5 July 2018

Loop in twig file drupal 8.

Here we have syntax of for/foreach loop in Twig file. Please have a look the syntax..
Suppose we have array with name of 'data', so our for loop for twig will be.

{% for key, value in data %}
      {{ key }} | {{ value }}
{% endfor %}

                      OR

In case we need key with value then our syntax will be..

<ul>
 {% for key, value in data %}
   {% if key!= ' '%}

      <li class="{{ key }}"> {{ value }}</li>
    {% endif %}
{% endfor %}
</ul>

                       OR

In case we just need value without key then our syntax will be..

{% for value in data %}
   {{ value }}     
{% endfor %}

Note: If have any suggestions or issue regarding 'Loop in twig file drupal 8' then you can ask by comments.

Wednesday 4 July 2018

Drupal 8 base_path and base_path_url.

We have syntax change in drupal 8 for base_path and base_path_url, Please have a look..

  • base_path = base_path();  // This code is for base_url of site.                                                    
  • base_path_url = \Drupal::request()->getpathInfo();  // This code for current page path.
  • Front page = {{ url('<front>') }}  // This code is for front page url.
  • Theme directory path = url('{{ base_path ~ directory }} //This code is for theme's root directory
Note: If have any suggestions or issue regarding 'Drupal 8 base_path and base_path_url' 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...