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.

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