Tuesday, June 15, 2021

WP - write log in wordpress

Write log in wordpress: 

functions.php:

if (!function_exists('write_log')) {
  function write_log($log) {
    if (true === WP_DEBUG) {
      if (is_array($log) || is_object($log)) {
        error_log(print_r($logtrue));
      } else {
        error_log($log);
      }
    }
  }
}

Then call write_log() in below way:
write_log("SOME TEXT");
Or
write_log($variable_to_test);

.:Happy coding:.



Monday, June 7, 2021

Drupal 9 commerce - get order number

Drupal 9 commerce - get order number:
By the below method you can generate order number:

public function generateOrderNumber(OrderInterface $order) {
    if ($order->getOrderNumber()) {
      return $order->getOrderNumber();
    }
    $order_type_storage = \Drupal::entityTypeManager()->getStorage('commerce_order_type');
    /** @var \Drupal\commerce_order\Entity\OrderTypeInterface $order_type */
    $order_type = $order_type_storage->load($order->bundle());
    /** @var \Drupal\commerce_number_pattern\Entity\NumberPatternInterface */
    $number_pattern = $order_type->getNumberPattern();
    $order_number = $number_pattern->getPlugin()->generate($order);
    $order->setOrderNumber($order_number);
    return $order->getOrderNumber();
  }

.:Happy coding:.

Friday, May 28, 2021

Drupal 9 - Read custom block body content

Drupal 9 - Read custom block body content:

$block = \Drupal\block\Entity\Block::load('block_machine_name');
if ($block) {
$blockuuid = $block->getPlugin()->getDerivativeId();
  $blockContent = \Drupal::service('entity.repository')
->loadEntityByUuid('block_content'$blockuuid);
  $vsf_form_message = $blockContent->get('body')->value;
}

Happy coding!

Wednesday, May 26, 2021

Drupal 9 - Sending email by Ajax form

Sending email by Ajax form in Drupal 9:

First make the HTML form, say it is here in this twig template:

<div id="shop-feedback-form" class="container-fluid">
  <div class="container">
    <div class="row">
     <div class="col-12 col-lg-5 text-left">
       <span class="d-block mb-3">Share your experience</span>
        <span class="d-none mb-3">How can we help?</span>
        <div class="d-block">
         <label class="ib-label" for="validationTextarea">Message</label>
          <textarea class="form-control exp-text-value" id="validationTextarea" 
placeholder="Please send us your question/remark or 
any problems you experienced during ordering. 
We will contact you as soon as possible."></textarea>
          <button class="btn btn-outline-secondary mx-0 share-exp-btn">Send</button>
        </div>
        <div class="d-none please-wait-box">Please wait!</div>
        <div class="d-none message-result-display-box">
         Thank you for sharing.  We will contact you as soon as possible.
        </div>
      </div>
    </div>
  </div>
</div> 

Second write down the Ajax functionalities: in your JS file, I hope you know how to add JS file/code in Drupal 9.

// Start
(function ($Drupal) {
  'use strict';

  $(document).ready(function() {
    $('.share-exp-btn').click(function() {
      var _self = $(this);
      var experienceBox = $(this).prev();
      var experienceText = $(this).prev().val();
      if (experienceText != "") {
        $.ajax({
          url: Drupal.url('module_name/share-your-experience-form'),
          type: "POST",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: experienceText,
          beforeSend: function() {
            _self.addClass('d-none');
            $('.please-wait-box').addClass('d-block');
            $('.message-result-display-box').addClass('d-none');
          },
          success: function(response) {
            _self.addClass('d-block');
            $('.message-result-display-box').addClass('d-block');
            $('.message-result-display-box').text(response.data);
            $('.please-wait-box').removeClass('d-block');
            experienceBox.val('');
          }
        });
      }
      else {
        $('.message-result-display-box').addClass('d-block');
        $('.message-result-display-box').text('Please enter something in message input box!');
      }
    });
  });
})(jQueryDrupal);

Third write down the route in module_name.routing.yml file:

module_name.share_experience_form:
  path'/module_name/share-your-experience-form'
  defaults:
    _controller'\Drupal\module_name\Controller\ShareYourExperienceController::submit'
    _title'Share your experience form'
  methods: [POST]
  requirements:
    _permission'access content'

Fourth write down the controller in your modue here src/Controller/ShareYourExperienceController.php 

<?php

namespace Drupal\ibcart\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

class ShareYourExperienceController extends ControllerBase {

  public function submit(Request $request) {
    $params = array();
    $content = $request->getContent();
    if (!empty($content) && $content != "") {
      // Send email to CS
      $module = 'module_name';
      $key = 'customerservice';
      $to = 'someemail@domain.org';
      $params['subject'] = 'Customer experience';
      $params['message'] = $content;
      $langcode = \Drupal::currentUser()->getPreferredLangcode();
      $send = true;

      $mailManager = \Drupal::service('plugin.manager.mail');
      $result = $mailManager->mail($module$key$to$langcode$paramsNULL$send);
      if ($result['result'] !== true) {
        return new JsonResponse(['success' => 0'data' => 'E-mail not sent!']);
      }
      return new JsonResponse(['success' => 1'data' => 'Thank you for sharing. We will contact you as soon as possible.']);
    }
    return new JsonResponse(['success' => 0'data' => 'Please enter something in message input box!']);
  }
}

Happy Coding!

Wednesday, May 5, 2021

Drupal 9 commerce - get product type by product ID

Get product type by product ID:

$product = \Drupal\commerce_product\Entity\Product::load((int)$product_id);
var_dump($product->bundle());

Happy coding!

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:
    classDrupal\module_name\Service\ClassName
    tags:
      - { nametwig.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)$amount2"."",");
    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...

Wordpress debug log function

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