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

 

Enabling custom web font in Drupal website

This blog will walk you through one the contributed module in Drupal community that has been a heave of sigh for me whenever I was in trouble for web building activity. A couple of weeks back, I have been assigned a task where the requirement was to enable ‘Benton-sans Regular’ font throughout the site. Initially, I thought it would be an easy task and can be done easily. But I was wrong.

No issues! If you facing similar difficulties. Here, I am going to discuss how you can enable ‘Benton-sans Regular’ font seamlessly using Drupal font-your-face module.

Firebug  Developer console

 

Earlier, I thought of writing a custom CSS for all the basic usable tags like

,,

,

,

,

,

,
,,,

by adding a font attribute ‘Font-family’. However, I was not cognizant of the font availability that it is equally important to render content with new fonts. At that point of time, the only values that were present on Firebug to debug was  -webkit-body, -webkit-pictograph, cursive, fantasy, inherit, initial, monospace, sans-serif, serif and Unset.

 

Solution: Here I am going to share the same solution that I applied to the above-mentioned issue. After doing little research I came across a font-your-face module that turned out to be a life savior for me. Note that there are many other lightweight modules available in community, such as  

  • , and

    Icon fonts (https://www.drupal.org/project/iconfonts)
    Google fonts (https://www.drupal.org/project/google_fonts)
    sweaver (https://www.drupal.org/project/sweaver)

    The reason behind choosing font-your-face module is that it offers admin interface to manage and apply new fonts. With this module, admin can also add module through CSS selector and enable font for the sub-theme.

    Prerequisites: Font file is required to enable Font. Here format should be EOT(embedded opentype) or TTF (truetype fonts) or WOFF (Web open font format), SVG (Scalable vector Graphics font format). Below is the list of the browser that supports Font format type.

    Font compatble browser list

     

    Let’s start by enabling the contributed module.

    Module enabling

     

    Here Providers display enabled font count, Advanced provides a checkbox (see below) and Preview holds sample text to be displayed while previewing enabled font.

    Checkbox

    Select the ‘Load fonts in all themes, including themes’ checkbox
     

    font-your-face configuration page

    Note: While adding a new font to the site, admin can provide basic information like font name, style of the font (Normal, Italic, Oblique), CSS font weight (Normal, bold, Bolder, lighter, 100, 200, 300, …..900).
     

    Import local font

     

    Browse local font

     

    By Font: This tab allows you to add CSS selector class. Select the checkbox and save the setting.

    Editing enabled font

    Once you save the setting, Font tab will start listing up Enabled Fonts.

    individual tag setting for font

    By CSS Selector: This tab lists HTML tag where admin can individually assign a font to each tag. Now click on save applied fonts.

    HTML tag selecting font setting page

     

    After assigning a new font to the desired tags, you can see the font reflection while loading the page.

    Note: Don’t forget to clear the cache.

    That's it! The above steps are walk-through for ‘@fontyourface’contributed module that supports multiple service provider like Typekit.com, google font, font.com, font Squirrel and Fontdeck. There are many other lightweight modules available in drupal.org that you can choose as per your requirement.

    We, at Valuebound, recommend trying out multiple font styles to find out what works well for your current project or requirements. Also, we invite you to comment below or ask any questions you may have.

      • Go for the normal installation as we do for all contributed module.
      • Click on Configure button, it will redirect you to 127.0.0.1/local/admin/config/user-interface/fontyourface
      • Now under General quick tab, you can see three different options: Providers, Advanced and Preview
      1. Load fonts in all themes, including admin themes.
      2. Keep detailed watchdog logs
      • Import Local Font quick tab having Font information fieldset with multiple font type upload option.
      • Now upload your choice of Font file like EOT/TTF/ WOFF/ SVG and click on confirm button.
      • Now under @font-your-face, enable fonts tab that has three sub-tabs, namely:
      1. By Font
      2. By CSS Selector
      3. In Themes

Getting started with Apache Cordova to build hybrid mobile apps

With the technological advancement, the demand for gadgets and their mobile apps are at its peak driving software industry to enhance digital experience. Interestingly, the apps designed for various operating systems are turning smartphones and tablets into miniature powerhouses of function and fun. Here I am going to share my first-hand experience of building a hybrid app using Apache Cordova.

So what is PhoneGap?

PhoneGap is an open source framework that allows us to build native mobile apps using various web-development languages such as HTML, CSS, and JScript; instead of relying on platform-specific APIs like those in iOS, Android or Windows. Developing mobile apps for each OS requires an optimum level of knowledge of different frameworks and languages, however, PhoneGap solves this issue by using standards-based web technologies.

How does it work?

The UI for PhoneGap applications is developed using the basic web-development languages and thus the browser takes 100% width and height of the device. Basically, it provides an API that enables to access native operating system functionality using JScript. You build your application logic using JavaScript, and the PhoneGap API handles communication with the native operating system.

PhoneGap

For demonstration, lets us build an app that will redirect us to a news publishing website. Run the codes to get the interface of a basic web page as shown in the image below.

When you will complete the installation, you will be redirected to the news page that contains the description of the news with a link to the main article. The following images are for reference.

Web page desktop version

 

Developing hybrid mobile application

Let’s gear up to turn the webpage into a hybrid mobile app. Here we will be pushing the code to the PhoneGap build cloud where the apps are developed on the specified preferences and requirements throughout all the mobile platforms.

To build a hybrid app through PhoneGap Build we require a config.xml file. We can find config.xml file in the root folder on the same level as that of the index.html.

Applications created with PhoneGap can be distributed to app stores, such as Apple App Store that can be installed on a user's device like any other native application.

Config.xml file:

This is the config.xml file which we are using in this example. Here you can find the whole set of code is enclosed in the widget tag.


Here,

 -- XML tags.

-- widget tag that has xmlns and xmlns:gap attribute which are for XML namespace

id = "com.valuebound.myapp"

-- The id attribute inside of the widget tag is used to uniquely identify the app on the PlayStore/iTunes and should be unique for every app and must be in the reverse domain notation.

versionCode = "10"

-- The versionCode attribute is used by the only android to identify different versions of the same app, so if you publish an app with versionCode=1 when you push an update to that app you will need to increment the number so for the next update you have to put versionCode=2 and so on.

version     = "1.0.0" >

-- The version attribute follows the  standard version system which is [major].[minor].[build]

PhoneGap TECHX

-- The name tag is the name of your app. This is not the name that will be used in the PlayStore/iTunes but it will be the name of the app on a device.



     An example for phonegap build docs.

--The description is pretty self-explanatory.



-- PhoneGap utilizes the tag to customise your application configuration. All tags in your config.xml are copied to the platform-specific configuration files, which implies that any preferences supported by the Cordova framework, or by any plugins.  [This is where we are specifying the preferences like for example the version of the Android or the screen resolution whether it should be portrait or landscape etc]



-- A plugin is a package of injected code that allows the Cordova web view within which the app renders to communicate with the native platform on which it runs. It provides access to device and platform functionality that is ordinarily unavailable to web-based apps. Have a look on other plugins.

PhoneGap web version

Notably, the above-mentioned UI is developed using PhoneGap Build and all the details (app name, app version etc.) that we provide in the config.xml file reflects here. This blog provides a reference for building Android mobile apps only. Here we are uploading the files to the cloud to build the app.

Once the config file is made we upload into the PhoneGap build cloud in a .tar file format. After completing the process, the interface will look similar to the web version of the smartphone.

Mobile Version

At the end, choosing the right framework for you will depend on your needs. Frameworks are made to make application development easier. It cuts off the time in making your site responsive in half. Try Apache Cordova to build your own app and see what it can do for you. If you have any suggestions or queries please comment down let me try to answer.

Below given is a presentation on Apache Cordova

 

References

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