Monday 12 August 2019

How to replace function use in Twig template?

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

Syntax with example:                   

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

{% set twig_content_variable = node.field_resources_vidyard_id.value %}    //field_resources_vidyard_id is are vidyard id field
{% set replace_value_var = '-' %}
{% set replace_with_value_var = '$' %}
{% if twig_content_variable %}
{% set vidyard_function_id = twig_content_variable|replace({ '-': '$' }) %}
{% endif %}







Note: How to replace function use in Twig template?

Thursday 8 August 2019

How to node load by name in drupal 8?

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

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

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

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


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

How to delete content node programmatically in drupal 8?

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

Syntax:

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

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


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









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

Wednesday 24 July 2019

How to set hreflang manually in website?

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

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


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

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


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




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

Tuesday 2 July 2019

How to display records in custom module with pagination?

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

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


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

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

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


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

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

class gpcustomController extends ControllerBase {

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

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

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

    }
}

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


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

Friday 7 June 2019

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

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

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

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


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

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

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

<?php

namespace Drupal\herobanner\Plugin\Block;

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

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


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

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

  /**
   * {@inheritdoc}
   */

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

  /**
   * {@inheritdoc}
   */

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */

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


Example:
namespace Drupal\herobanner\Plugin\Block;

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

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


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

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

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

                            </div>

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

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


?>

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




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

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

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


After this clear the cache and get the result.


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

Tuesday 30 April 2019

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

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

Syntax:

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

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

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

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



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

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