Some times we need custom function that will help us to use custom function to use in Twig file. We can extend the core Twig_Extension to use in our custom module.
Please follow the below steps/code to create custom twig function.
Creating your own Twig Extension function
To start with it first, we need to create a module.
1.) Create a new module inside: /modules/custom/ directory inside your drupal project.
2.) Our new module structure would look like this:
modules
--custom
----demo_module
------demo_module.info.yml
------demo_module.services.yml
------src
--------TwigExtension.php
3.) demo_module.info.yml contains
name: demo_module
type: module
description: 'Provides Twig Extension that process the Regular Expression functions.'
core: 8.x
version: 0.1.1
Information provided inside module_name.info.yml is used to be displayed on admin module page.
4.) Create a service file inside your module as 'module_name.services.yml'
services:
demo_module.twig.TwigExtension:
class: Drupal\demo_module\TwigExtension
tags:
- {name: twig.extension}
5.) The TwigExtension.php contains the following code
<?php
namespace Drupal\demo_module;
use Drupal\block\Entity\Block;
use Drupal\user\Entity\User;
use Drupal\node\Entity\Node;
/**
* Class DefaultService.
*
* @package Drupal\demo_module
*/
class TwigExtension extends \Twig_Extension {
/**
* {@inheritdoc}
* This function must return the name of the extension. It must be unique.
*/
public function getName() {
return 'pcre_extension';
}
/**
* {@inheritdoc}
*/
public function getFilters()
{
return [
new \Twig_SimpleFilter('pregReplace', [$this, 'pregReplace']),
];
}
/*
* This function is used to return only letters
*/
public function pregReplace($value, $pattern, $replacement = '', $limit = -1) {
if (!isset($value)) {
return null;
}
return preg_replace($pattern, $replacement, $value, $limit);
}
6.) Now, enable your demo_module module.
drush en demo_module -y
7.) Clear the cache.
drush cr
8.) Applying Twig Extension to your twig template
You can make a call to your TwigExtension directly inside template using “{{ }}” braces. These braces are used to render any content placed inside them.
{{ val|pregReplace('/[^A-Za-z]/') }}
Moving further, set the value from pregReplace('/[^A-Za-z]/') function to remove all special characters in Twig template files, it will return only letters.
TwigExtension provides a great accessibility to the code which is often reused. With easy re-usability of the code, it also saves a lot of time and efforts. Hope you will now be able to use Twig in Drupal 8.
Web Development Information [PHP, DRUPAL, MYSQL, MAGENTO, JQUERY, JAVASCRIPT, CSS, HTML5]
Monday, April 8, 2019
Thursday, December 6, 2018
Views exposed form programmatically and assign to somewhere
Sometimes to get the views exposed form and place into somewhere in the site. So we can use the below code to achieve programmatically.
$view = Views::getView('view_name');
$view->setDisplay('display_name');
$view->initHandlers();
$form_state = (new FormState())
->setStorage([
'view' => $view,
'display' => &$view->display_handler->display,
'rerender' => TRUE,
])
->setMethod('get')
->setAlwaysProcess()
->disableRedirect();
$form_state->set('rerender', NULL);
$form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
$view = Views::getView('view_name');
$view->setDisplay('display_name');
$view->initHandlers();
$form_state = (new FormState())
->setStorage([
'view' => $view,
'display' => &$view->display_handler->display,
'rerender' => TRUE,
])
->setMethod('get')
->setAlwaysProcess()
->disableRedirect();
$form_state->set('rerender', NULL);
$form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
Wednesday, May 24, 2017
Download drupal contributed module in Drupal 8 using composer
Use the following commands to download and install in drupal 8 contributed module using Composer.
composer require drupal/{module_name} {version}
Example: composer require drupal/devel 1.0-beta1
Once execute the above command, this will download the module (not installed). For install, we need the execute the drush or drupal console command to install the module.
Via Drush: drush en {module_name}
Via Drupal console: drupal module:install {module_name}
composer require drupal/{module_name} {version}
Example: composer require drupal/devel 1.0-beta1
Once execute the above command, this will download the module (not installed). For install, we need the execute the drush or drupal console command to install the module.
Via Drush: drush en {module_name}
Via Drupal console: drupal module:install {module_name}
Tuesday, May 23, 2017
Clear the cache in Drupal 8
We can clear the cache in Drupal 8 in many ways
1. Via CMS end
Go to Administration > Configuration > Development > Performance (/admin/config/development/performance)
Click the button "Clear all caches"
2. Drupal console
drupal cache:rebuild all
3. Drush
drush cache-rebuild / drush cr
1. Via CMS end
Go to Administration > Configuration > Development > Performance (/admin/config/development/performance)
Click the button "Clear all caches"
2. Drupal console
drupal cache:rebuild all
3. Drush
drush cache-rebuild / drush cr
Monday, May 22, 2017
Create custom module in Drupal 8 via Drupal console
Generate module
drupal generate:module - It will ask the module name and basic information.
Give the module a name of module (welcome) and Enter module description, path and basic information. Then drupal will create the below files under the your custom module.
composer.json
welcome.info.yml
welcome.module
Install module
The module now exists but it is not enabled. You don’t need to go to the module page to enable it, you can install and enable the welcome module using the module:install command:
drupal module:install welcome
This will install the module and automatically rebuild the cache.
drupal generate:module - It will ask the module name and basic information.
Give the module a name of module (welcome) and Enter module description, path and basic information. Then drupal will create the below files under the your custom module.
composer.json
welcome.info.yml
welcome.module
Install module
The module now exists but it is not enabled. You don’t need to go to the module page to enable it, you can install and enable the welcome module using the module:install command:
drupal module:install welcome
This will install the module and automatically rebuild the cache.
Monday, April 11, 2016
List out CCK field allowed values in Drupal
List out CCK field allowed values in Drupal
$field = field_info_field('field_machine_name');
$allowed_values = list_allowed_values($field);
This will return the allowed values list as array.
Usage:
field_info_field - Load the field instance by using field machine name
list_allowed_values - List out the allowed values
$field = field_info_field('field_machine_name');
$allowed_values = list_allowed_values($field);
This will return the allowed values list as array.
Usage:
field_info_field - Load the field instance by using field machine name
list_allowed_values - List out the allowed values
Tuesday, March 1, 2016
Remove the password hint details in drupal register page
You can use the below code remove the password hint details in drupal register page.
/**
* Implements hook_element_info_alter().
*/
function HOOK_element_info_alter(&$types) {
if (isset($types['password_confirm']['#process']) && (($position = array_search('user_form_process_password_confirm', $types['password_confirm']['#process'])) !== FALSE)) {
unset($types['password_confirm']['#process'][$position]);
}
}
Note: Please clear form cache after adding
/**
* Implements hook_element_info_alter().
*/
function HOOK_element_info_alter(&$types) {
if (isset($types['password_confirm']['#process']) && (($position = array_search('user_form_process_password_confirm', $types['password_confirm']['#process'])) !== FALSE)) {
unset($types['password_confirm']['#process'][$position]);
}
}
Note: Please clear form cache after adding
Remove the user tab link in user login page and user register page
We can use the below code to remove the user tab link in user login page and user register page.
/**
* Implementation of hook_menu_alter().
*/
function HOOK_menu_alter(&$items) {
$items['user/login']['type'] = MENU_CALLBACK;
$items['user/register']['type'] = MENU_CALLBACK;
$items['user/password']['type'] = MENU_CALLBACK;
}
Note: Please clear the menu cache after adding this function
/**
* Implementation of hook_menu_alter().
*/
function HOOK_menu_alter(&$items) {
$items['user/login']['type'] = MENU_CALLBACK;
$items['user/register']['type'] = MENU_CALLBACK;
$items['user/password']['type'] = MENU_CALLBACK;
}
Note: Please clear the menu cache after adding this function
Monday, July 6, 2015
Programmatically create view mode for product in Drupal Commerce
1. First create the view mode by using the following hook or Entity View Mode module.
2. Then create the template file commerce-product--product--{view-mode}.tpl.php
3. Inside the template file, you can render what ever you want.
4. Then clear the cache.
2. Then create the template file commerce-product--product--{view-mode}.tpl.php
3. Inside the template file, you can render what ever you want.
4. Then clear the cache.
Monday, June 29, 2015
Generate SSH Key using GIT
Please follow the below steps to create the SSH key in GIT
1) Open Git Bash (type git bash in search bar of windows start)
2) Generate the key using following command
$ ssh-keygen -t rsa -b 4096
This will prompt you to enter file name, just press enter key.
When prompting for passpharse, enter a passpharse. (Note the pharse
which will be used while you clone the repository)
3) Open key file and copy
$ cat /d/Users/<yourloginusername>/.ssh/id_rsa.pub
Friday, June 26, 2015
Drupal commerce programmatically change the quantity of product in a cart by using product id
Programmatically change the quantity of product in a cart by using product id
function product_alter_quanity($product_id, $quantity, $param) {
$line_item_id = product_in_cart($product_id); // product_in_cart() function - http://php-developer-informations.blogspot.co.uk/2015/06/drupal-commerce-add-line-item-delete.html
if ($line_item_id != -1 && $line_item_id != -2) {
if ($param == 'remove') {
$product_quantity_in_cart = commerce_line_items_quantity(array($line_item_id));
if ($quantity >= $product_quantity_in_cart) {
product_delete_cart($product_id);
}
else {
$line_item = commerce_line_item_load($line_item_id);
$line_item->quantity = $line_item->quantity - $quantity;
commerce_line_item_save($line_item);
}
}
elseif ($param == 'add') {
//$line_item_id = product_in_cart($product_id);
$line_item = commerce_line_item_load($line_item_id);
$line_item->quantity = $line_item->quantity + $quantity;
commerce_line_item_save($line_item);
}
}
else {
return -1;
}
}
function product_alter_quanity($product_id, $quantity, $param) {
$line_item_id = product_in_cart($product_id); // product_in_cart() function - http://php-developer-informations.blogspot.co.uk/2015/06/drupal-commerce-add-line-item-delete.html
if ($line_item_id != -1 && $line_item_id != -2) {
if ($param == 'remove') {
$product_quantity_in_cart = commerce_line_items_quantity(array($line_item_id));
if ($quantity >= $product_quantity_in_cart) {
product_delete_cart($product_id);
}
else {
$line_item = commerce_line_item_load($line_item_id);
$line_item->quantity = $line_item->quantity - $quantity;
commerce_line_item_save($line_item);
}
}
elseif ($param == 'add') {
//$line_item_id = product_in_cart($product_id);
$line_item = commerce_line_item_load($line_item_id);
$line_item->quantity = $line_item->quantity + $quantity;
commerce_line_item_save($line_item);
}
}
else {
return -1;
}
}
Drupal commerce programmatically delete a line item from the cart by using product id
Programmatically delete a line item from the cart by using product id
function product_delete_cart($product_ids) {
if (!is_array($product_ids)) {
$line_item_id = product_in_cart($product_ids); // product_in_cart() function - http://php-developer-informations.blogspot.co.uk/2015/06/drupal-commerce-add-line-item-delete.html
if ($line_item_id != -1 && $line_item_id != -2) {
global $user;
$current_order = commerce_cart_order_load($user->uid);
commerce_cart_order_product_line_item_delete($current_order, $line_item_id);
} else
return -1;
}
else {
$line_item_ids = product_in_cart($product_ids);
if ($line_item_ids != -1 && $line_item_ids != -2) {
global $user;
$current_order = commerce_cart_order_load($user->uid);
foreach ($line_item_ids as $line_item_id) {
commerce_cart_order_product_line_item_delete($current_order, $line_item_id);
}
}
else {
return -1;
}
}
}
function product_delete_cart($product_ids) {
if (!is_array($product_ids)) {
$line_item_id = product_in_cart($product_ids); // product_in_cart() function - http://php-developer-informations.blogspot.co.uk/2015/06/drupal-commerce-add-line-item-delete.html
if ($line_item_id != -1 && $line_item_id != -2) {
global $user;
$current_order = commerce_cart_order_load($user->uid);
commerce_cart_order_product_line_item_delete($current_order, $line_item_id);
} else
return -1;
}
else {
$line_item_ids = product_in_cart($product_ids);
if ($line_item_ids != -1 && $line_item_ids != -2) {
global $user;
$current_order = commerce_cart_order_load($user->uid);
foreach ($line_item_ids as $line_item_id) {
commerce_cart_order_product_line_item_delete($current_order, $line_item_id);
}
}
else {
return -1;
}
}
}
Drupal Commerce find the line item id by using product id
Programmatically find the line item id by using product id
function product_in_cart($product_id) {
if (!is_array($product_id)) {
global $user;
$current_order = commerce_cart_order_load($user->uid);
if (count($current_order->commerce_line_items) > 0) {
$line_items = $current_order->commerce_line_items;
foreach ($line_items['und'] as $key => $value) {
$line_item = commerce_line_item_load($value['line_item_id']);
$products = $line_item->commerce_product['und'];
foreach ($products as $product_key => $product_value) {
if ($product_id == $product_value['product_id']) {
return $value['line_item_id'];
}
}
}
return -1;
} else
return -2;
}
else {
global $user;
$current_order = commerce_cart_order_load($user->uid);
if (count($current_order->commerce_line_items) > 0) {
$line_items = $current_order->commerce_line_items;
foreach ($line_items['und'] as $key => $value) {
$line_item = commerce_line_item_load($value['line_item_id']);
$products = $line_item->commerce_product['und'][0]['product_id'];
foreach ($product_id as $id) {
if ($id == $products) {
$line_item_ids[] = $value['line_item_id'];
}
}
} if (isset($line_item_ids) >= 1) {
return $line_item_ids;
}
else {
return -1;
}
} else
return -2;
}
}
function product_in_cart($product_id) {
if (!is_array($product_id)) {
global $user;
$current_order = commerce_cart_order_load($user->uid);
if (count($current_order->commerce_line_items) > 0) {
$line_items = $current_order->commerce_line_items;
foreach ($line_items['und'] as $key => $value) {
$line_item = commerce_line_item_load($value['line_item_id']);
$products = $line_item->commerce_product['und'];
foreach ($products as $product_key => $product_value) {
if ($product_id == $product_value['product_id']) {
return $value['line_item_id'];
}
}
}
return -1;
} else
return -2;
}
else {
global $user;
$current_order = commerce_cart_order_load($user->uid);
if (count($current_order->commerce_line_items) > 0) {
$line_items = $current_order->commerce_line_items;
foreach ($line_items['und'] as $key => $value) {
$line_item = commerce_line_item_load($value['line_item_id']);
$products = $line_item->commerce_product['und'][0]['product_id'];
foreach ($product_id as $id) {
if ($id == $products) {
$line_item_ids[] = $value['line_item_id'];
}
}
} if (isset($line_item_ids) >= 1) {
return $line_item_ids;
}
else {
return -1;
}
} else
return -2;
}
}
Drupal Commerce add line item
Function for programmatically add a product as line item by using product id
function product_cart_add($product_id, $quantity, $uid = NULL) {
$line_item = NULL;
if ($uid == NULL) {
global $user;
$uid = $user->uid;
}
if ($product = commerce_product_load($product_id)) {
$line_item = commerce_product_line_item_new($product, $quantity);
$line_item = commerce_cart_product_add($uid, $line_item);
}
return $line_item;
}
function product_cart_add($product_id, $quantity, $uid = NULL) {
$line_item = NULL;
if ($uid == NULL) {
global $user;
$uid = $user->uid;
}
if ($product = commerce_product_load($product_id)) {
$line_item = commerce_product_line_item_new($product, $quantity);
$line_item = commerce_cart_product_add($uid, $line_item);
}
return $line_item;
}
Wednesday, May 27, 2015
Drupal user login form customization
Customizing the user login page is very simple, and uses the following concepts:
Use preprocess to set variables
register you template file in hook_theme
create templates and render your variables
Step 1:
/**
* Implements hook_theme().
*/
function hook_theme() {
$items = array();
$items['user_login'] = array(
'render element' => 'form',
'path' => PATH . '/templates',
'template' => 'user-login',
'preprocess functions' => array(
'hook_preprocess_user_login'
),
);
return $items;
}
Step 2:
function hook_preprocess_user_login(&$variables) {
$variables['render_text'] = 'You can add extra text and message';
}
Step 3:
Create you template file in your template folder
user-login.tpl.php
<div class="login-wrapper">
<h2><?php print t('SIGN IN'); ?></h2>
<?php
// split the username and password from the submit button so we can put in links above
print drupal_render($form['name']);
print drupal_render($form['pass']);
?>
<div class="login-links">
<?php print l(t('FORGOT YOUR PASSWORD?'), 'user/password', array('attributes' => array('class' => 'login-link'))); ?>
</div>
<?php
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
print drupal_render($form['actions']);
?>
</div><!--//login-wrapper-->
Step 4:
Clear drupal cache
Use preprocess to set variables
register you template file in hook_theme
create templates and render your variables
Step 1:
/**
* Implements hook_theme().
*/
function hook_theme() {
$items = array();
$items['user_login'] = array(
'render element' => 'form',
'path' => PATH . '/templates',
'template' => 'user-login',
'preprocess functions' => array(
'hook_preprocess_user_login'
),
);
return $items;
}
Step 2:
function hook_preprocess_user_login(&$variables) {
$variables['render_text'] = 'You can add extra text and message';
}
Step 3:
Create you template file in your template folder
user-login.tpl.php
<div class="login-wrapper">
<h2><?php print t('SIGN IN'); ?></h2>
<?php
// split the username and password from the submit button so we can put in links above
print drupal_render($form['name']);
print drupal_render($form['pass']);
?>
<div class="login-links">
<?php print l(t('FORGOT YOUR PASSWORD?'), 'user/password', array('attributes' => array('class' => 'login-link'))); ?>
</div>
<?php
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
print drupal_render($form['actions']);
?>
</div><!--//login-wrapper-->
Step 4:
Clear drupal cache
Wednesday, April 15, 2015
Add custom file extension in PHP application
We can add custom file extension in Apache PHP application. We can add our custom file extension instead of .php
For example, index.xyz instead of index.php
Open httpd.conf located in apache/conf folder
Find " <IfModule mime_module> "
Add " AddType application/x-httpd-php .xyz "
Restart your apache server
For example, index.xyz instead of index.php
Open httpd.conf located in apache/conf folder
Find " <IfModule mime_module> "
Add " AddType application/x-httpd-php .xyz "
Restart your apache server
Thursday, March 5, 2015
Status messages not removing with Commerce Ajax Cart
Use ajax_command_remove() command to remove the existing error messages while submit ajax add to cart button
$commands[] = ajax_command_remove('div.messages');
$commands[] = ajax_command_after('#main-content', theme('status_messages'));
$commands[] = ajax_command_remove('div.messages');
$commands[] = ajax_command_after('#main-content', theme('status_messages'));
Friday, January 30, 2015
Create an commerce order programmatically
The following steps to describe about to create an commerce order programmatically in Drupal
global $user;
$product_id = 100;
$quantity = 1;
$order = commerce_order_new($user->uid, 'cart');
commerce_order_save($order);
$line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
commerce_order_save($order);
global $user;
$product_id = 100;
$quantity = 1;
$order = commerce_order_new($user->uid, 'cart');
commerce_order_save($order);
$line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
commerce_order_save($order);
Thursday, December 4, 2014
Implement Jquery infinite scroll plugin
Plugin Source: https://github.com/paulirish/infinite-scroll/
Automatic Scroll:
$('selector').infinitescroll(options);
Manual Scroll:
$('#scroll-container').infinitescroll(options);
$('#scroll-container').infinitescroll('unbind');
$('.view_more').click(function() {
$('#scroll-container').infinitescroll('retrieve');
return false;
});
Note:
You may have to add the manual trigger behavior if you are working with masonry or isotope in order to make it work. Just include manual-trigger.js after infinitescroll and pass the behavior by passing behavior: 'twitter' when calling the plugin.
Automatic Scroll:
$('selector').infinitescroll(options);
Manual Scroll:
$('#scroll-container').infinitescroll(options);
$('#scroll-container').infinitescroll('unbind');
$('.view_more').click(function() {
$('#scroll-container').infinitescroll('retrieve');
return false;
});
Note:
You may have to add the manual trigger behavior if you are working with masonry or isotope in order to make it work. Just include manual-trigger.js after infinitescroll and pass the behavior by passing behavior: 'twitter' when calling the plugin.
Monday, October 27, 2014
GIT shows warning when pull
GIT shows warning when pull. If you are getting the below warning message when GIT pull
(gnome-ssh-askpass:29014): Gtk-WARNING **: cannot open display:
Please use "unset SSH_ASKPASS"
(gnome-ssh-askpass:29014): Gtk-WARNING **: cannot open display:
Please use "unset SSH_ASKPASS"
Subscribe to:
Comments (Atom)