Wednesday, April 21, 2021

Drupal 8 - call function from twig template

Drupal 8 - call function from twig template:

Create a service yml file 'module_name.services.yml'

services:
  unique_function_name:
    class: Drupal\module_name\Service\ClassName
    tags:
      - { name: twig.extension }

Create a service class 'src/Service/ClassName'

<?php 
namespace Drupal\module_name\Service;

use Drupal\taxonomy\Entity\Term;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_product\Entity\ProductAttributeValue;

/**
 * Class IBSearch.
 *
 * @package Drupal\ibsearch
 */
class ClassName extends AbstractExtension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'unique_function_name';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return [
      new TwigFunction('ib_get_term_name', [$this, 'getTermName']),
      new TwigFunction('ib_get_attr_name', [$this, 'getAttrName']),
      new TwigFunction('ib_get_format', [$this, 'getFormat']),
      new TwigFunction('ib_format_amount', [$this, 'formatAmount']),
    ];
  }

  /**
   * The php function to load a given block
   */
  public function getTermName($tid) {
    // Normalize if $tid is a Markup
    $tid = "".$tid;
    $term = Term::load($tid);
    if ($term) {
      return $term->getName();
    }
    return '';
  }

  public function getAttrName($attrId) {
    $attrObject = ProductAttributeValue::load($attrId);
    return is_null($attrObject) ? '' : $attrObject->get('name')->value;
  }

  public function getFormat(Product $commerce_product) {
    $variations = $commerce_product->getVariations();
    $format = array();
    foreach ($variations as $variation) {
      $value = $variation->getAttributeValue('attribute_format');
        $retval[] = $value->getName();
    }
    return implode(' | ', $retval);
  }

  public function formatAmount(string $amount) {
    $price = number_format((float)$amount, 2, ".", ",");
    return str_replace(".00", "", $price);
  }
}

Now call your function from twig file:

{{ ib_format_amount(item.content["#markup"]) }}

Thanks for reading...

Tuesday, April 13, 2021

JS - convert string date to your desire date in javascript

JS - convert string date to your desire date in Javascript:

var dateStrValue = "Tue, 04/13/2021 - 12:00";
if (dateStrValue != "") {
    const monthNames = ["January", "February", "March", "April", "May", 
"June", "July", "August", "September", "October", "November", "December"];
            
    var dateStrDateOnlyArray = dateStrValue.split(',');
    dateStrDateOnlyArray = dateStrDateOnlyArray[1];

    dateStrDateOnlyArray = dateStrDateOnlyArray.split('-');
    dateStrDateOnlyArray = dateStrDateOnlyArray[0];

    var replaced = dateStrDateOnlyArray.split('/').join('-');

    var dateObj = new Date(replaced);
    var monthValue = monthNames[dateObj.getMonth()];
    var yearValue = dateObj.getFullYear();
    $('#prod-date').html(monthValue + ' ' + yearValue);
}
else {
    $('#prod-date').html("");
}


Happy coding...

Tuesday, April 6, 2021

Drupal 8 - display HTML in twig template

Drupal 8 - display HTML in twig template

{% set build = {
    '#type': 'processed_text',
    '#text': '<h1>Raw HTML here</h1>',
    '#format': 'full_html',
    }
%}
{{ build }} HAPPY CODING...

Drupal 8 - access field value in preprocess views view unformatted hook

Drupal 8 - access field value in preprocess views view unformatted hook:

/**
 * Implements hook_preprocess_views_view().
 */
function yourmodule_preprocess_views_view_unformatted(&$vars) {  
  if ($vars['view']->id() == 'solr_product_search') {
    $vars['base_url'] = \Drupal::request()->getSchemeAndHttpHost(); 
    
    if ($vars['view']->id() == 'solr_training_search') {
      $view = $vars['view'];
      $rows = $vars['rows'];
      
      foreach ($rows as $rowId => $row) {
        foreach ($view->field as $fieldId => $fieldValue) {
          if ($fieldId == 'field_coursedate') {
            $data = trim(strip_tags($view->style_plugin->getField($rowId, $fieldId)));
            $vars['field_course_date'] = $data;
          }
        }
      }
    }
  }
} HAPPY CODING...

Friday, April 2, 2021

Word truncate in Twig template

Follow the below code to achieve your word truncate in twig template:
It is done in a Drupal project so you can pick up the concept from here, not by doing copy paste code to achieve your result.

{% set field_description = view.style_plugin.getField(key, 'field_name')|render|striptags %}
{% set field_description_array = field_description|split(' ') %}
{% if field_description_array|length > 20 %}
    {% set word = 20 %}
    {% for i in range(1, word) %}
        {{ field_description_array[i] }}
    {% endfor %}
    {{ '...' }}
{% else %}
    {% for key,value in field_description_array %}
        {{ value }}
    {% endfor %}
{% endif %}

Happy coding!

Tuesday, February 16, 2021

Get specific length random number in Java

Get specific length random number in Java:

import java.util.Random; 

public class RandomJavaProgram {
   public static void main(String []args) {
       RandomNumber RandomNumberObj = new RandomNumber();
       System.out.println(RandomNumberObj.getRandomNumber(3));
   }
}

class RandomNumber {
    public String getRandomNumber(int digitLength) {
        int[] numberContainer = new int[digitLength];
        String mainRandomNumber = "";
        Random rand = new Random();

        for ( int i = 0; i < digitLength; i++ ) {
            numberContainer[i] = rand.nextInt(10);
        }        

        for ( int j = 0; j < digitLength; j++ ) {
            mainRandomNumber = mainRandomNumber + String.valueOf(numberContainer[j]);
        }       

        return mainRandomNumber;
    }
}

Difference between COPY and volume in Docker

Difference between COPY and volume in Docker:

Volume creates a mount point that the Docker host can interact with.
COPY too can accomplish that but it does that during build time.

With Volume, you can keep interacting with the contents on the host machine but COPY is just one time activity which is used during the build time.

Wordpress debug log function

Wordpress error log code: if ( ! function_exists ( 'write_log' ) ) { function write_log ( $data ) { if ( defined ( '...