Data-binding methods in AngularJS

The blog is follow up on our previous post “My First Impression of Learning AngularJS” where I shared my experience of working in AngularJS. This blog is intended to take you one step ahead and have a better understanding of basic operation workflow. In Angular, we have a concept of ‘Data-binding’ that means synchronization of data between a view to model or model to view (technically). 
 

Data Binding Flow

From the business perspective: Change in the logic (backend) impacts front-end (view) and vice versa.

Scenario: Suppose you have a variable, called BookPrice, stored in a database or in local storage. And you are trying to render that value to your page. So change in a “BookPrice” in DB will change front-end value by performing any operation and submitting data back to DB. It will also help you to sync data from view to model.

Angular follow three types of Data-binding method:

  1.  One-way Data-binding
  2.  Two-way Data-binding
  3.  One-Time Data-binding

One Way Data-binding: AngualrJS binds data using one way/two way Data-binding method. In this approach, the value of the variable is always taken from model and display using a view. This is a unidirectional approach. Any update from view won’t update the model. Few points to notice here:

  • Data always flows from model to view.
  • In case of any modification in the model, the same will sync up in view.
  • Data won’t flow from view to model.
  • To render data to the page. Use data-ng-bind aka ng-bind or evaluation expression  {{ }} (curly braces).

One-Way Binding

As you can see in below codebase, we have included AngularJS minified version in a script tag and we have ng-app & ng-init

ng-app or data-ng-app: Before compiler starts executing Angular, it looks for ng-app for initialization and loads the document. Then tells Angular that this is a root element for the application. Generally, it is attached to

/

tag. 
You’re not allowed to use multiple ng-app for single HTML page. Angular does not execute outside of its scope (code inside ng-app will be executable).

ng-init: ‘ng-init’ stands for initialization. As per Angular official statements, ng-init can be used to add an unnecessary amount of logic to your template. The main objective of using ng-init is to evaluate expression under the current scope.

Model, View

In the above source code, I tried to execute outside

tag. As a result, it responded incorrectly and print the data as it is. Similarly, there are various ways you can incorporate ng-app into the HTML. Here we are executing the codes online. Later, we will take a look at different ways to incorporate ng-app.

 

One way data-binding

Two-way Data-binding: It is a bi-directional approach as it travels in both of the directions. From model to view or view to model. Any Update/change on (model) endpoint response (JSON/XML) will impact in the front page that means data in a page(view) will be also impacted.

Few points to note here:

  1. Data always flow from model to view and view to model
  2. In case of any modification in the model, the same will sync up in view
  3. In case of any modification in view, the same will sync up in the model
  4. ng-model directives are used to bind input box/textarea/select list to the variable created using AngularJS
     
Two-Way Data binding

Code Simplification: As you can see in the following source code, we have created a new application under script tag and added it inline. Before I start any more code simplification, let me take out a portion of code that you will get in each and every codebase.

Best way to differentiate HTML tag and JS code is by creating a separate file and paste the same code in JS file.

var app = angular.module('newApp', []);

Note that using above code, we can create an object for an app and give them name as ‘newapp’ where angular.module is a syntax to create a new app. Also, you will find a blank array, it’s nothing but to inject services into your app or any dependency for your app.

Sample codebase:

Here controller holds the function or attribute or functionality in order to provide data to module and module provides data to an application.

Sample codebase:

app.controller('newController', function($scope) {
                 /*properties will be defined here.
                    Variable defines inside controller will be always tagged with $scope
                */
  $scope.properties=’100’;
 });
Two way data-bindingTwo way data-binding method

One-Time Data-binding: In AngularJS, data gets transferred from model to view only one time. Ones the change happen in mode, it won’t impact on view again and again. As per Angular official document, the values only need to be shown in the view and are never going to update from view or controller.

  • Data always flow from model to view or scope to view
  • Data populated only once
  • Data doesn’t travel from view to model
  • Rendering the one-time data view can be accomplished using: :[double colon] special character
  • Use one-time binding when we need a static variable. Help to reduce unwanted watchers.

Below source code will assign name variable only once. It won’t change later. On-time binding follows data flow pattern from model to view that also only once. As you can see on the result screen. Name value has been taken only once from the model and didn’t change later on.

Result:

One-time data-binding

Above shared source code refers to Databinding in AngualrJS with examples. 

That’s it! Data-binding is a technique that helps you bind data with the model in front-end and vice versa. Though we have different ways to bind the data, we have gone through one-way, Two-way, One-time Data-binding model. Use the models technically as per the requirement to make sure the flow, internal performance & complexity.

Related: Overview of AngularJs Module and Controllers

GitHub source code: https://github.com/xaiwant/AngularJS-Data-Binding

A beginners guide to caching in Drupal 8

Caching is a popular technique to optimize the performance of a website. It is a process that stores web data (HTML, CSS, Image) in some accessible space. Moreover, a cache is a detailed information of a validity of a resource. This information defines for how long the resource is valid and should not be considered stale. The information can be stored at every level right from the original server to intermediate proxies to the browser.

Here you will get to learn about what key/value pairs in the header mean and Cacheability metadata in Drupal 8.

Every request or response contains a HTTP header, which provides additional information about the request/response. This also contains information related to cache.

Typical HTTP Header Example :

HTTP Header Example

Let’s see what these key/value pairs in the header mean:

  • Expires: The Expires header sets a time in the future when the content will expire. This header is probably best used only as a fallback.
     
  • Etag: It is a unique hash identifier of the cacheable object that the browser caches. Whenever a cached response is requested repeatedly, browser checks with the server if the eTag of the response is modified. If the response is not modified, the server returns 304 not modified else 200 along with new response & new eTag.
     
  • Last-modified: This parameter specifies the date and time the resource was last modified. Last-modified is used as a fallback when Etag is not specified.

          Syntax : , :: GMT

  • Vary: Vary specifies the list of a parameter on which the response should vary. For example, Accept-Encoding specifies the format in which the browser expects the response such as gzip, sdch or simply text/html.

Similarly, User-Agent specifies the user-agent such as a mobile user or desktop user based on which the content should vary.

Another interesting Vary parameter is ‘cookie’ which specifies to vary content based on the user. For instance, the different version of same content for the anonymous user and logged-in user.

  • Cache-Control: Cache-Control specifies directives which instruct the browser / intermediate-proxies to who can cache the response, the conditions for caching the response and the maximum time for which the response can be cached. Some of Cache-Control directives are:
     
    • No-cache: Indicates that the response should be validated with the origin server before sending.
       
    • Public/private: "Public" marked responses indicates that the response can be cached by any cache, even if it has HTTP authentication associated with it. Private marked responses are intended for a single user and intermediate cache should not store the response, but private cache such as browser may store the response.
       
    • No-store: Shows that the response should not be cached by the browser or intermediate proxies.
       
    • Max-age: Indicates the maximum time in seconds for which the content can be cached before it must-revalidate. This replaces the Expires header for modern browsing. This option takes its value in seconds with a maximum valid freshness time of one year (31536000 seconds).
       
    • s-maxage: Similar to the max-age setting. The difference is that this option is used only for intermediary caches.

Now we have a basic understanding of caching, so let’s see how this works in Drupal 8.

Cacheability metadata in Drupal 8 :

All things that are either directly renderable or used to determine what to render, providing cacheability metadata.

Cacheability metadata consists of three properties:

  • Cache tags: If our renderable arrays depend on some data such as entity data or some configuration values we use cache tags to invalidate the data.

    Syntax : “Thing:identifier” 

    Example:

    node:5 // cache tag for node entity 5
    user:4 // cache tag for user entity 4
    node_list // list cache tag for node
    
    $tags = array('node:1', 'user:7');
    \Drupal::cache()->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, $tags);
    
    // Invalidate all cache items with certain tags.
    \Drupal\Core\Cache\Cache::invalidateTags($tags);
  • Cache contexts: Cache context is used when our renderable arrays depend on some context such as user role, theme or URL. This is similar to Drupal 7 block constants like DRUPAL_NO_CACHE / DRUPAL_CACHE_PER_ROLE / DRUPAL_CACHE_PER_PAGE, but with many more options.

    Example :

    // Setting Cache Context & Tag for a block.
    return array(
      '#markup' => $this->t('My custom block content'),
      '#cache' => array(
        'contexts' => ['url.path'], //setting cache contexts
        'tags' => ['node:1', 'node:2'] // setting cache tags
      ),
    );	 
  • Cache max-age: Cache controls how long an item may be cached by a number of seconds.

    0 means cacheable for zero seconds, i.e. not cacheable.

    \Drupal\Core\Cache\Cache::PERMANENT means cacheable forever, i.e. this will only ever be invalidated due to cache tags. (In other words: ∞, or infinite seconds.)

Here we have explored the basic of Caching in Drupal 8, what key/values pairs in the header mean and cacheability metadata. Caching allows retrieval without having to request the data from the original source. In case you have any questions, feel free to share in the comments below—we'll get back to you ASAP.

Below given is a presentation on Caching in Drupal 8.

My first impression of learning AngularJS

Before we delve into the ocean of understanding and learning curves of AngularJS, let me share my insights and experience of working on web development. Later, I will tell you why experiences are worth sharing.

For the past four-and-a-half years, I have been working in an IT industry. Started my career as a Drupal developer, working on web building, site building, extending features, development as well as designing. During this journey, I came across many technologies which I was expected to learn from scratch to bind/ integrate one to another. 

Cutting a long story to short! So why did I started learning AngularJS? What is the scope of AngularJS? And why I am sharing my experiences with you guys?

Nowadays, applications are mostly developed in haste, intended to build once and run across multiple environments with or without little changes. These days we focus more on re-usability instead of rewriting the code base afresh.  

Recently, I had an opportunity to build a website using REST Services, which provides result in JSON or XML format. It also displays the same data using front-end framework/Decoupled website. In Drupal, it’s called as Headless Drupal, where front-end & backend will have different technology (because the client was not happy with the existing design pattern of Drupal & wants to execute those pages as a mobile app for different Operating System). 

After brainstorming, our team decided to go ahead with AngularJS to get the things done. Initially, I didn’t know whether it was a time-saving framework or not as it follows MVC architect. Considering the various advantages of AngularJS, the framework is good for building a hybrid app using HTML, CSS, and JavaScript. 

The main advantage of building over the native app as it is sleek, maintainable & simple. When we started learning this framework, at that time every syntax/term was new for me. Sometimes it was like a nightmare to understand the usage. Initially, I was a bit worried whether developing the app on AngularJS is worth or not, but stick to the decision and moved ahead with same ideas. This is the reason why I wanted to share my experience with you noobs.

Let’s have a brief look at the history of AngularJS as it helps in learning, who developed AngularJS and why it was extended. Check out some of the reasons why you should give AngularJS a shot. To mention a few:

  • AngularJS is an open source framework powered by Google. The framework is supported by a community of highly skilled professionals and is a solution for various web applications.
     
  • It follows MVC architect that help developers to write clean code and separate front-end with logic. Model refers to data, the view refers to front-end and controller is the logic that binds the model with a view. MVC splits app into a different component and later on, Angular manages that component and merge them for your request. 
     
  • Good to build SPA. SPA does not refresh the page again repeatedly for each request, instead of loads the chunks of the page to act faster because it loads entire page only once. More into Front-end and reduce page refresh act as a local application.
     
  • AngularJS is not a DOM-like jQuery, but uses a subset of jquery (Jqlite).
     
  • Basic Knowledge of HTML, CSS, and JavaScript required. Jquery will be a plus point.
     
  • Gives power to your front-end with time saver.
     
  • Mobile app development using AngularJS. Hybrid apps like Ionic, PhoneGap used to build a hybrid app. so that user can use those page as App.

Moving forward, we will discuss various AngularJS components, namely

  • Data Binding
  • Modules and Controllers
  • Scope
  • Filters
  • Services
  • Dependency Injection
  • Functions
  • Directive
  • Routing

Let’s start from the beginning. Download AngularJS library from https://angularjs.org/. Now install and enable AngularJS for the web page

Downloading AngularJS

 

Now place it on your associated web page and attach. As we attach JS script in the HTML page.
 


AngularJS is attached to your page. Now perform an operation using frontend Framework. Start with a small piece of code. Do not worry, if few terms will be absolutely new.
 
Below, I have included script tag to include AngularJS minified version 1.2 with 2 function New1() & New2() and terms like ng-app, ng-controller. As an output, this will return the text.
 

AngualarJS mini version

So far we have discussed the basic codebase of AngularJS. How to set up AngularJS with sample code execution. Over the next couple of posts, I will elaborate each of the components of AngularJS with sample codebase. Till then just relax and focus on the basic. 

When you complete the tutorial, I believe you will have a better understanding of complex terminologies and techniques. Later, I will also use new terms name like the model, view, controller, data etc. Guys! Have patience and don’t get confused.
 

A beginners guide to Performance optimization in Drupal 8

Web performance is an important factor to consider when developing a website because user experience and usability are dependent on the speed of page loads. Not to mention, web giants like Google, Yahoo, Amazon, and eBay are obsessed with it. And there are numerous ways you can boost site performance. 
          
In Drupal 8, there are specific tools and modules to optimize the site performance. 

To begin with, Caching is a popular technique to optimize the website. It is a process that stores web data (HTML, CSS, Image) in some accessible space. For instance, when a user request for a web page for the first time it stores readable content or information in the cache memory and whenever viewer request the same HTTP page again it retrieves the stored data and display to users. This is how it makes loading web page fast. 

There are mainly two types of caching: Client-side caching and Server side caching. Except for this two caching methods, pages can be cached in the database, Drupal primarily cache information within its database.

Core caching techniques of Drupal 8

Make sure “Internal Dynamic Page Cache” and “Internal Page Cache” are installed and enabled by default. See the below screenshot for an example.

Core caching techniques of Drupal 8

 

Internal Page Cache:

This core module is for anonymous users. If you have an e-commerce website and you have “Add to cart” functionality for an anonymous user then this kind of caching can be done using the module. In case you don’t need this functionality then turn it off.

Internal dynamic page cache: This module is similar to Internal Page Cache and the only difference between the two is that it cache for both anonymous user and logged in user. 

Page cache maximum age:

Page cache maximum age

This setting is for the maximum time age for a cached page. Whatever age we set here is the maximum age that our site tells browsers that they should keep cached information/data. By default internal dynamic page cache set “No caching”, however, it can be changed as per the requirement.

Bandwidth optimization:

Bandwidth optimization

When you choose to aggregate CSS and JavaScript files, “Bandwidth Optimization” groups both in bundles in order to reduce the number of HTTP requests, which is necessary for the page to load. Instead of loading a couple dozens of files, the page will load with just a handful of aggregates.

Drupal external caching technique:

There are few techniques in Drupal that controls the CMS interaction with an external cache. This can be done using contributed modules, such as 

  • CSS/JS Aggregation: There is a module for CSS/JS aggregation, dubbed  Advanced CSS/JS Aggregation. Drupal has its own aggregation capabilities, but AdvAgg module greatly enhances these by offering more effective approaches to file grouping, caching, and compression. 
  • Varnish cache: Varnish is a program that speeds up a website while reducing the load on the web server. You can accelerate the site performance using various other modules, such as Varnish purge and  Advanced Varnish Cache
  • Memcache: Memcache improves Drupal application performance by moving standard caches out of the database. In Drupal 8, there are two types of Memcached modules: Memcache and Memcache Storage Have a look at how to configure Memcached modules with Drupal 8.
  • Redis: Redis is a cache technique that is optimized for high-performance storage and retrieval. It works with an in-memory dataset. Have a look at Redis module for a detailed explanation.  

Use MariaDB instead of mysql

MariaDB turns data into structured information in various web applications. There are various advantages of MariaDB in terms of performance and features, like better storage engines. In addition, it supports TokuDB that handles big data for large organizations and corporate users.

Note that MySQL's database engines, MyISAM and InnoDB, are replaced in MariaDB by Aria and XtraDB respectively. Aria offers better caching, which makes a difference when it comes to disk-intensive operations. Temporary tables also use Aria to speed up complex queries. Percona's XtraDB gets rid of all of the InnoDB problems with slow performance and stability, especially in high load environments.

Use Nginx instead of Apache

Apache and Nginx are the two most common open source web servers, but Nginx is way faster and consumes less memory than Apache. Nginx has proven record and performing well. It also manages a large number of concurrent users with minimal resources.    

Other specific tools and modules

  • Disable all unnecessary module from your web application.
  • Update contributed and core modules. If an update is available.
  • Devel: Use Devel module for query analysis as it helps to trace issues.
  • CDN (content delivery network): If your site has large amounts of content to display, consider using a CDN. Most CDNs are used to host static resources such as images, videos, audio clips, CSS files, and JavaScript. The closer a CDN server is to a site visitor, the faster the content will be delivered to their computer or mobile device. E.g.: AWS CloudFront, Akamai. It provides easy Content Delivery Network integration for Drupal sites.         
  • Image Lazyloader and Blazy: These two modules loads only those images that are visible to the browser window.
  • CSS sprite: Use CSS sprite for small images combine into one or serve it from glyphicon.

    Ex. 

CSS sprite

 

  • Use gzip compression: GZIP provides a lossless compression, that is, we can recover the original data when decompressing it. It is based on the DEFLATE algorithm. E.g. gzip compression:
     

mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

You can also check if your compression is working using the Gzip compression tool.

Replace Your Web Hosting

Now you know how to enhance Drupal site performance. In case, your application is still not meeting expected performance goals then consider choosing a host that provides faster service.

Managed Dedicated Server(s): Managed dedicated server takes care of all your hosting needs for you. Not only you get the hardware but you get a team of experts to make sure everything is running as it should. They keep your software up-to-date and alert you if there are any problems. You can deploy multiple servers in many configurations.

Dedicated Server(s): A dedicated server provides low latency that means a fast response time for most small to medium-sized sites.

Cloud Hosting: Cloud hosting is scalable. The “cloud” means that there is a data center with lots of dormant servers. As your site’s need scale up (or down), the servers in the data center respond with more server power. Examples: Acquia Cloud, Pantheon, and Platform.sh.

Let’s check the result

You can use one of a desktop or online tools to test and improve your site performance. Here are few that you may consider trying:

Desktop tools: ApacheBench (ab), Apache jmeter, The Grinder, EasyQA

Online sites: Pingdom, GTMetrix, PageSpeed Insights etc.

Performance optimization plays a pivotal role in every web application whether it a large scale or a small scale. In this blog, I have tried to assemble a list of all the configuration changes you can do to tune the performance of Drupal applications. Note that the size of images can have a great impact on your website’s loading speed and performance.

Below given is a presentation on "Performance optimization in Drupal 8." 

References

http://www.tothenew.com/blog/best-practices-to-optimize-performance-in-drupal-8/ 
https://www.volacci.com/blog/how-improve-drupal-8-website-performance 
https://www.nginx.com/blog/8-tips-for-drupal-8-performance/
https://www.ostraining.com/class/performance/
 

Flood Table in Core Drupal with user ID/IP Management

As a Drupal professional you might have heard of Flood Table (user session management) but didn’t give much thought to it. 

Having little theoretical knowledge of the core behavior of Drupal is not bad. So allow me to explain what user session management is all about? And how it can protect you from bot or malware. I will also share few #Tweaks that help you to understand how to Flood & Unblock user from your site.

Drupal 6 does not provide security from login attempt attack from Core until you enable login security contributed module. In Drupal 7, however, the core has an in-built functionality to handle user account attack whether it is a bot or some sort of malware. In this scenario, Drupal protects your account from multiple hits either from one user id or one source ip. 

Drupal protects your site in two different ways:

  1. Failed login user id
  2. Failed login source IP

Drupal blocks particular user from login if he/she attempt to log in for more than five times within a time span of six hours, and source IP if there is 50 failed attempt within an hour. These data get stored in Flood Table provided by Drupal core. 

As shown below, we have event id (fid), event (user logged in attempt IP/logged in attempt by user id), identifier (value for logged in user ID/IP), timestamp (event occurrence unix timestamp), expiration (Expiration timestamp. Expired events are purged on cron run.)

The Table helps you to view locked user IP & ID on the Drupal website. In Drupal 8, you won’t find ‘FLOOD’ table by default until any of the user lock/user IP event occurs. Thereafter, Drupal create FLOOD table.

login attempt failed


Below is the Drupal 8 Table structure of Flood.

Flood table in database

Let’s say you, as an admin, have been blocked due to multiple wrong password entry. And unfortunately, you don’t have a mail server installed on the web so that you can request for Password Reset. 

In this case, you can Reset your password by running Drush command. If, somehow, you remember your password, but unable to log in due to multiple false attempts then clear your flood table first. 

When your account is locked, visit phpmyadmin using UI or log in to mysql or relevant database as a root user then search for Flood Table and clear the respective user ID/IP.
 

mysql login

 

flood table with data

 

Open related database. Look for Flood table and delete specific user row from Table entry. As you can see above table having two entries.

  1. User.failed_login_ip: Display user attempt was made from the IP address (127.0.0.1).
  2. User.failed_login_user: Display user ID & hit by source IP address (2-127.0.0.1).

 

Deleting data from flood table

The flood table has been cleared from the terminal and you have deleted specific user or IP. Now you can log in to your Drupal website. So simple. 

Let’s view the same scenario another way around. 

You don’t have ssh/putty access, but you have admin rights and you want to unlock one of the user account, who is blocked due to multiple false attempts. In this scenario, you can download & install Flood Unblock & Flood Control module. 

Drupal Flood Unblock provides an interface to the admin so that she/he can unblock user ID/IP either in bulk or individually. Use the following Drush command to clear user ID/IP:

drush flood_unblock all
drush flood_unblock ip
drush flood_unblock user

Contributed module Flood Unblock UI

 

Drupal Flood Control holds additional configurations to manage Failed IP limit and Failed user limit with the time range. Set this configuration as per your feasibility and save the configuration.

Contributed module Flood Control UI

 

Locking mechanism is being handled by Drupal user_login_authentication_validate()

// Set per-IP Drupal failed login attempts limit and window.
variable_set('user_failed_login_ip_limit', 50); 
variable_set('user_failed_login_ip_window', 3600); 

// Set per-user Drupal failed login attempts limit and window.
variable_set('user_failed_login_user_limit', 5) ;
variable_set('user_failed_login_user_window', 21600);

Run the following commands:

To Reset user password using drush:

drush user-password USERNAME --password="SOMEPASSWORD"
or 
drush upwd USERNAME --password="SOMEPASSWORD"

To Reset user password using Drupal Console:

drupal user:password:reset

To Reset user password using SQL-Query:

Generate hash code for your new password. By running one of the commands in the Drupal root directory:

./scripts/password-hash.sh newpwd 

For Windows user:

 php .\scripts\password-hash.sh newpwd

Once received encrypted password, execute sql query to run password update. And DONE.

UPDATE users SET pass 

='$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WLbhPT2K5TzKzML' WHERE uid = 1;

So far we have checked out functionality, mechanism, and recovery of Flood and Table structure. Here are few tips that will help you to protect user account especially admin account that every hacker tries to attack.

  1. Do not give admin username as an admin.
  2. Don’t allow the user to view username of admin.
  3. Hide confidential data like username from an anonymous user.
  4. Enable notification via mail/sms if super user logged in.
  5. Block uid =1 if no more required. & enable it in temporary, if they required it.

That’s it! This is all about Flood Table. 

Okay, so you know what is the purpose of Flood Table and you're convinced that you've got something new to learn. The goal of our blog post is to bring you valuable information to help out in difficult situations and grow your business. Hope you enjoyed this post! Please comment below and let me answer in case you have any doubts.

Drupal Commerce: Splitting a package into multiple shipments using Packer & PackerManager

Drupal 8 commerce shipping contributed module introduced an extendable and prioritized concept of Packer and PackerManager. Packer allows sites to automatically split an order into multiple shipments based on stock location, weight, dimensions, or some other criteria.

Let’s see what Packer and PackerManager do.

Packer and PackerManager

  1. Packer: Creates one or more shipments for a given order. We can create an end number of Commerce Packer class, which implements `Drupal\commerce_shipping\Packer\PackerInterface`. PackerInterface provides abstract methods:
    1. applies: Determines whether the packer applies to the given order.
    2. pack: Packs the given order.
  1. PackerManager: Runs the added packers one by one until one of them returns a result.

How PackerManager works

Based on each Packer priority, PackerManager will check whether the packer applies for an order or not. If packer applies for the concerned order than it will execute the pack method. This iteration will go on until any one of the Packer returns a proposed shipment.

Commerce shipping contributed module implement DefaultPacker, which creates a single shipment per order. If we have implemented one or more Packer classes, then we have to prioritize the packers.

Implementing multiple shipments

  1. Create Packer class.

  2. Implement applies method, here this custom packer doesn’t apply to China location.

  3. Implement pack method.

  4. Tag Packer in module services.yml

Finally, Packer class will be as below:

That’s it! This is how we split the package into multiple shipments in Drupal 8 Commerce. The method that I espouse above is all about creating a good experience for customers. We recommend you to try out Packer and PackerManager concept to find out what works well for your ongoing projects.

Configuring Memcache with Drupal 8 to reduce database load

Developers often come across a situation where they are required to reduce database load by caching DB objects in RAM. Here Memcache improves Drupal application performance by moving standard caches out of the database and by caching the results of other expensive database operations. 

Note that Drupal doesn’t support Memcache by default, and for this, we need to install it on the server. Let’s see how to install Memcache on the server and configure it with Drupal 8 to reduce the load on the database with every page load.

Let’s see how to install Memcache on server

Open the terminal on your local machine and run the following codes:

Step 1: sudo apt-get update

Step 2: sudo apt install memcached

Step 3: sudo apt install php-memcached

Step 4: Make sure Memcache daemon is working fine by running the following command: 

“ps aux | grep memcached”

Step 5: Also, check whether the Memcached extension is properly configured in PHP7 by creating info.php page.

nano /var/www/html/memcache/info.php

And enter the below code 

 

Step 6: Now restart both Memcached and php7-fpm services 

service memcached restart
service php7.0-fpm restart

Step 7: Go to any web browser and access info.php as 

“localhost/memcache/info.php”, and search for “Memcache” you will see the screen similar to the one mentioned below.

Memcache server

After installation of Memcache in your server, download Memcache module and Memcache Storage module.

 

Now go to “http://yourdomain.com/admin/modules” and enable the two modules.

Memcache Enabled

Configuring Memcache with Drupal 8:

Open your site settings.php and paste the below code. Here we are using Memcache storage for Drupal 8 as it provides an integration of D8 and Memcached PECL.

// Set’s default cache storage as Memcache and excludes database connection for cache
$settings['cache']['default'] = 'cache.backend.memcache_storage';
// Set’s Memcache key prefix for your site and useful in working sites with same memcache as backend.
$settings['memcache_storage']['key_prefix'] = '';
// Set’s Memcache storage server’s.
$settings['memcache_storage']['memcached_servers'] =  ['127.0.0.1:11211' => 'default'];

To debug Memcache include below code following above code in settings.php

// Enables to display total hits and misses
$settings['memcache_storage']['debug'] = TRUE;

Memcache debug

Note: Before uninstalling Memcache and Memcache storage, comment/delete Memcache settings code from your settings.php file.

That’s it! If you are planning to configure Memcache with Drupal, you need to look out for three things: which cache bins will be offloaded with Memcache; website traffic and volume of content; and the amount of RAM allocated to Memcache. 

Now you know how to configure Memcache with Drupal 8 to reduce database load. Go ahead and try it on your own website. In case you need any help in installing and configuring Memcache with Drupal 8, do leave a comment below and I will get back to you ASAP!

Related: Using SteemSQL to query Steem database

Below given is a presentation on "How to install Memcache on the server and configure it with Drupal 8."

References

dropsolid.com/en/blog/memcache-drupal-8 
https://www.drupal.org/node/2448995 
openconcept.ca/blog/mmallett/apc-varnish-memcache-and-caching-beyond-drupal-core

Resolving translation issue of Placeholder in Drupal 8

Hello Drupalers! Here is another #Tips&Trick to make your placeholder translatable. Recently, I have an opportunity to fix one of the issues in Drupal 8 instance where the website was not multilingual hence unable to handle internationalization. After fixing the issue, the contact form now supports more than 25 languages. Let me explain you, what exactly was the issue over here? And how did we overcome this issue?

Issue: Here, Drupal Contact Form Placeholder was not translatable from User Interface Translation.

As we all know anything passes through t() function is always translatable. The issue is generally found in Drupal 8, not sure whether it occurs in Drupal 7 or not. To check the same in Drupal 7, you need to use contributed locale module and check whether web form placeholder gets transformed or not when we do the translation. Remember, Placeholder does pass through t() function.

Notably, all text that passes through t() are visible in User Interface Translation. However, there is no such option to create the translation of a custom text. There many of us have difficulties in translating the text.

See the screenshot below for an example:

Core Drupal Translation UI

Workaround: To add Custom placeholder through your module in the form field.

Form Manage field placeholder setting

 

Don’t add it through field setting, leave it blank. We will add it through a custom module or custom Twig File. Here, Placeholder text should pass through t().

Adding Placeholder through custom module in the form

Scenario 1: To add custom placeholder to your form.

/**
 * Implements hook_form_form_id_alter().
 */

function custom_form_contact_message_feedback_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
          $form['field_name']['widget']['0']['value']['#placeholder'] = t('custom placeholder needs to be translate’);
}

Way to add through custom Twig file in your form

Scenario 2: To add custom string to your template file or twig.


 
{{ 'custom placeholder needs to be translate'|t }}

Once we have added our custom placeholder to custom module or twig, it should start displaying in User Interface Translation. And from there we can add translation for our choice of language. See the screenshot below for an example of ‘Filter Translatable Strings’.

Filtering Translation

Once it is visible on User Interface Translation, add text for your respective language and save the translation. Here I am adding text for the Hungarian language.

Custom Placeholder started displaying in Translation UI

 

Below is the sample for contact form after applying the solution.

Contact form Sample

The above step is one of the workarounds to translate custom text in Drupal 8 using custom code and Core User Interface Translation. Possibly, you can import .po file of respective languages by exploring & importing the same file with updated msgid & msgstr.  Let me know if you come up with a better solution for the above-mentioned issue.

Valuebound, we are fully on the Drupal 8 bandwagon - from an internal, client site development to consulting services. Our development team has been working with Drupal 8 as a group for over a year. Are you interested in learning more about how Drupal can help your business grow? Contact Us.

 

Build your own mobile app using Ionic and Drupal 8

Ever since the release of Drupal 8, the most popular keyword search in the framework is “Headless Drupal” also referred as Decoupled Drupal. Headless Drupal is something where you use Drupal to store data that can be accessed in multiple applications (via REST APIs). The front end frameworks like Ionic interacts with Drupal using HTTP requests.

Check out how to use this feature of Drupal and Ionic framework to build a hybrid mobile application.

What is Ionic?

In simple terms, Ionic is an open source framework that is built atop Apache Cordova to develop hybrid mobile apps. Hybrid apps are not developed specifically for a platform that means you can manage a single codebase for different platforms. Let’s build a simple movie listing page.

Prerequisites:

Installing Ionic:

  • To install Ionic you need to install  Apache Cordova, nodejs, npm in your system. Run the following codes.

sudo apt-get install nodejs
sudo apt-get install npm
sudo npm install -g cordova
sudo npm install -g ionic

Drupal Set up :

Enable the following modules for rest API

Modules required

  • Enable CORS (Cross Origin Resource Sharing) for accessing the data between applications. Change the CORS config as per the origins of services.yml file:
     
  • A content type of the movie :
    content type
  • A rest export view with a list of movies:


Rest View

  • Make the serializer format to be json.

    Integrating Drupal set up with Ionic

Step 1 - Create an Ionic menu-based app using the below command:

ionic start  sidemenu

You can choose tabs/blank instead of side menu for your app.

Step 2 - Run the app. Navigate to the app folder.

Ionic serve / ionic serve --lab (This allows you to view your app in both ios and Android platforms)

This opens the app in your desktop browser.

Step 3 - Create a page:

ionic generate page movie-list

Step 4 - Navigate to app folder. Edit the movie-list.ts from App Folder > src > pages > movie-list. This is where the view will be requested for data.

Step 5 - Now display the view data in the app.

The movies variable declared in movie-list.ts can be accessed in the movie-list.html. Below ion-header (similar to head in HTML), add ion-content (similar to body in HTML).

The sanitizer.bypassSecurityTrustHtml is used to save the html tags exposed from views.

Step 6 - To add the page to the menu, edit the app.component.ts file from App Folder > src > app.

Import your page at the top and add the page in pages variable.

Step 7 - Now check your app in the browser. You will be able to see the movie list page on the menu. You may see the output similar to the below screenshot. :

Result

You can apply the CSS for the ratings in app.scss file. The CSS applied here would be applied globally. If you want to apply styles to the specific page, you can create a .scss file in your page folder.

You may need to import some app components like HTTP, Headers for HTTP calls if facing any errors.

Login functionality can also be implemented as follows:

Login form in login.html would be

The form can be validated in login.ts.

The authenticated actions in Drupal like adding content can be done by passing the CSRF token stored in the local storage into headers.

You can also refer Ionic website to check out more details about deploying the app

In this way, you can use the Ionic framework to build the hybrid mobile apps and use the decoupling feature of Drupal to store the data. Try Ionic and see how it enhances digital experience. If you have any suggestions or queries please comment down let me try to answer.

 Below given is a presentation on "Building mobile app using Ionic framework."

 

 

Migrating Address Book in Drupal 8 website using Process plugin

Migration is a term, which all the developers who have started working in Drupal 8 have gone through once at least in their development cycle. Migration can be done of many things like site migration (i.e migrate from Drupal 7 to Drupal 8), user migration, content migration. In simple terms, we can migrate all types of entity in Drupal 8.

How this migration works:

Migrate works by reading a row from a source plugin then running each property through a pipeline of Process plugins thus, resulting in a row to a destination plugin.

Why we write Process plugin?

Each Process plugin gets the current value and returns a value.

Here we are going to look how this Process plugin works. We are going to migrate Address fields using Process plugin in Drupal 8. Follow the below steps.

Step 1: Install the following modules

  • Migrate Tools
  • Migrate plus
  • Migrate Source CSV

Step 2: Create a custom module. ‘custom_addressbook_migration’

  • Create a .info file :

Step 3: Create assets folder inside the module and paste your CSV file inside it.

  • Prepare the CSV as shown : 

Address_csv

 

Step 4: Create Process plugin

  • Add a new plugin class, called AddressFieldMigration, in your module at src/Plugin/migrate/process/AddressFieldMigration.php.
  • The @MigrateProcessPlugin annotation tells migrate about the new Process plugin and the id key is used to select this plugin in a migration’s mappings. The class should extend Drupal\migrate\ProcessPluginBase and override the transform() method. This method will be passed to the incoming source value and is responsible for returning the modified destination value.
  • Here, in CSV, we are passing the country name, but address requires country code so we have made use of  CountryManager Class to get the country code from given country name.
  • We get the region names in form of code mostly for Foreign Countries, In the CSV, you can see it is given as  ‘CA’. So, to get the state name we have to make use of methods from SubdivisionRepository Class.

Step 5: Now, we have to create a Migrate Configuration file and import this configuration.

Here,

  • Address is created under profile entity so the destination plugin name is entity: profile.
  • Process plugin is written to map all the columns given in source CSV file to its respective fields in address entity. In Migration, always we have to mention the source, destination, and process.

Step 6: Import the above configuration file into Drupal site.

  • Goto admin > config > development > configuration
  • Click on Import Tab and Choose Single Item
  • Select the Configuration Type as Migration
  • Paste the above configuration file and click on Import.

Step 7: Drush Commands to implement

  • drush ms - you will see the status of all the migrations.
  • drush mi address_fields_migration.('address_fields_migration' is the id in the configuration file)

Step 8: Conclusion :

  Now, Go to admin > config > people > profiles and you will see the list of address that has been migrated. This is how address fields are migrated using process plugin in Drupal 8.

To know more about migration using Process plugin, Refer Drupal 8 Process Plugin

Since I have mentioned only a few drush commands related to migration, you can check more about this Here

Please put your doubts, suggestions or queries related to above topic in the below comment box, and I will try to answer them. You may also like to check out our previous blog on "Drupal 8: Why & How to Migrate".

 

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch