The Global Training Day, Bangalore

April 9 was a day filled with enthusiasm as we set forth with “The Drupal Global Day training” here at Valuebound. With a crowd of over 20 people and 5 trainers the knowledge sharing session was very fruitful.

The session started with an introductory note on Drupal to the diversified audience from different industries right from IT & ERP to Digital Marketing. Having gained the basics of Drupal, trainers encouraged the attendees to start with their first hands on experience of Drupal.  The participants were excited to create their own website without using a single line of code.

The session was filled with lot of queries & heated discussions making it an interactive conclave. Drupal Global Training Day turned out to be successful when a large part of the crowd showed interest in taking the session to the next level. Many were interested in being a part of the upcoming Drupal Camp, Bangalore in July’16.

Here are a few shares on the same.

How to build your Drupal 8 theme using Bootstrap & Less

Bootstrap is a true blessing for web developers which is a sleek, intuitive and powerful mobile first front-end framework for faster and easier web development. When you mix that with LESS pre-processor you get a mighty tool for creating a Drupal 8 theme.

In this tutorial we will be looking into initiating your own custom theme using Drupal’s Bootstrap base theme. The Drupal Bootstrap base theme bridges the gap between Drupal and Bootstrap framework. Drupal 8 being relatively new, has very little documentation available to use Bootstrap, which now has a stable release for Drupal 8.

To spare you some frustration and as a source of resource for our staff, I've arranged an orderly guide for making your own sub-theme.

  1. Download, extract and place the Bootstrap base theme in your “theme” folder. It doesn’t make any difference if the theme stays disabled as we will be using it just as a parent theme for our sub-theme. N.B. : Unlike Drupal 7, Bootstrap for Drupal 8 does not require jQuery Update module.
     
  2. Copy the entire less folder from “/themes/bootstrap/starterkits” and place it in “/themes” along with bootstrap directory.bling

     

  3. Rename the less folder as the name of your theme. Let’s say we call it “bling”less
     
  4. Rename the following files in your “bling” theme directory:
  • THEMENAME.libraries.yml to bling.libraries.yml (All the libraries associated with your theme will be entered in this file)
  • THEMENAME.starterkit.yml to bling.info.yml (The info file for your theme)
  • THEMENAME.theme to bling.theme (SImilar to template.php in Drupal 7)
  • config/install/THEMENAME.settings.yml to config/install/bling.settings.yml (This file is only used to override existing settings.)
  • config/schema/THEMENAME.schema.yml to config/schema/bling.schema.yml (Schema for the theme setting configuration file of your theme.)

5. Update your bling.info.yml

6. Download Bootstrap Source and upload it to “bling” folder. The source directory is named as bootstrap, which  contains the Source Less, JavaScript, and font files.

7. Next compile the less file which will create the style.css file. On compilation the style.css will be filled up all the Drupal specific overrides, Bootstrap CSS and also your custom css.
lessc less/style.less > css/style.css

8. Enable your theme from Drupal UI and you should see the base Bootstrap theme in action.

 

homepage

Brownie Points:

  • Add theme.js file:
    • Create a directory “js” in your theme
    • Add a file named theme.js which will hold the JavaScript applicable sitewide.
    • Add the library in the bling.libraries.yml as:
      js:
        js/theme.js: {}

 

  • Add a FontAwesome CDN for getting font icons:
    • Add this to bling.libraries.yml under css directive:
      'maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css': {type: external}

Your libraries file should look like this after adding these two items:

How to write the custom Drush Commands in Drupal 8?

Writing custom drush commands in Drupal 8 is not exactly like Drupal 7 but it is similar. Here also, we are implementing hook_drush_command().   

The only difference is in the file structure.  As we all know In Drupal 8 ‘.module’ file is not mandatory in the module root folder. Hence In Drupal 8 for creating custom drush commands, we only need two files.

  1. MyModuleName.info.yml
  2. MyModuleName.drush.inc

Where,description will be listed under Other commands: (custom_drush_command)

'description' => 'Echo the name you type with Say hello commandSay hello.'

drush_command

 

The command can be accessible in two ways by typing item_id say-hello' or using alias say:hello

drupal dependencies' => ['custom_drush_command'],
This tells to drupal that our drush command which has dependency, will work if we have our custom “custom_drush_command" installed.

 

In this way we can execute our custom new drush command using drush say:hello ‘your name’ or  drush say-hello ‘your name’

drush_command_execution

 

drush_alias_command_execution

 

How to enable and use:

  1. Install the module
  2. Open the terminal and ‘cd’  to your drupal root folder.
  3. drush cache-clear drush
  4. drush cr
  5. drush say:hello ‘your name’ or  drush say-hello ‘your name’


Source Code: https://github.com/rakeshjames/custom_drush_command

How to reduce the risk of your Drupal 8 application using Backup & Restore?

Imagine this! You are typing hundred lines of code, fixing bugs after bugs and finally after countless efforts the program successfully runs. Uff!! What a feel when you finally crack the code! But wait, what if in a blink of an eye everything vanishes off? What if, your site which was running properly suddenly stumbles a minute later?
Isn’t it any coder’s nightmare? You curse yourself for not taking backup. This article will save you from that dreadful situation.
 
Not only is creating and storing site backup a good practise, but it also ensures site stability and helps in further updation.
 
In order to backup a Drupal site you need to take care of code and database.

  • The first problem we came across is placing the Drupal directory trees under revision control.
  • The second one is about database which requires a more careful analysis.

     

Before we learn about how to use Backup & Migrate module along with Drush, let us cover some of the optimal strategies for backing up and restoring MySQL database.

General practices:
 

  1. Always backup the entire site before updating or upgrading.
     
  2. Date your backups. Save each file with a title that includes the date of the backup.
     
  3. Save a copy of backup in a different location other than your web server. Remember, if your web server crashes, you may lose your backup files too.
     
  4. Inquire about your ISP or web host's backup policies. Most good web hosts have a backup plan that kicks in every 24 hours.
     
  5. In addition to your web host's backups, routinely do it yourself. Periodically run a separate backup monthly, weekly, daily or whatever fits your site's needs.
     
  6. Restore your backups using the same method as you took the backup.
     

Why should I backup?
 

  1. If for some reason your website goes awry, sometimes restoring it from a recent backup is the only option available.
     
  2. New development environments can be created easily.
     
  3. Module upgradation and patches can be tested better when using a recent backup of your production site.

Tools available for Backup & Restore
If you are on Linux you can do Mysql Database Backup / Restore using below mysql and mysqldump command lines


Backup Local Database without password
mysqldump db_name > db_file.sql
 
Backup / Local / Remote Database With Password
mysqldump -u USERNAME -p dico db_name > db_file.sql
 
Backup A Table
mysqldump -uUSERNAME -p db_name tab_name > tab_file.sql
 
Backup and compress using gzip
mysqldump -uUSERNAME -p db_name  | gzip > db_file.sql.gz
 
Restore a Database
mysql -uUSERNAME -pPASSWORD db_name < db_name.sql
 
Restore a gzip compressed file using gunzip

gunzip < db_file.sql.gz | mysql -uUSERNAME -pPASSWORD db_name


Backup & Migrate:
This module facilitates emergency recovery and site migration. We can configure it for automatic backups saved to the file system - with more frequent backups during development. We can also create a manual backup. That way, you have a "restore point" in case of disaster.
 
While there may be some issues of security when you save the database and content as a file, the benefits of having a rollback in case of disaster are significant.
 
Drush
Drush is a command line shell and UNIX scripting interface for Drupal. Drush core ships with lots of useful commands for interacting with code like modules/themes/profiles. Similarly, it runs update.php, executes sql queries and DB migrations, and misc utilities like run cron or clear cache.
 
To use Drush you need to have shell (SSH) terminal access to your server and be able to install and configure the Drush utility code.

Step 1: Drupal has known problems in clearing some cache tables, that are left unaffected by the normal cache clearing in Drupal or Drush. Solve this by clearing expired cache elements manually by running Drush.
 
The most convenient way to rebuild Drupal's cache is by using Drush
RUN drush cache-rebuild
alias: drush cr
alias: drush rebuild

cache_clear


Step 2: Once you cleared the cache, the next step is running the backup command.
RUN: drush archive-dump

archive_dump



So, we can view our site dump is being downloaded to
/home/valuebound/drush-backups/archive-dump/20160217071827/drupal8.20160217_071828.tar.gz
This .tar file carry site & database dump.
 
If you would like to take just the sql dump,
RUN: drush sql-dump > ~/
This will create .sql file in your home directory.

sql_dump

 

Step 3: To Restore sql dump.
 
RUN: drush sql-cli < db_name.sql
Open a SQL command-line interface using Drupal's credentials.

data_restore


FTP
The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network.

FTP is built on client-server model architecture and uses separate control and data connections between the client and the server.

FTP

Where section a is local Directory
            section b is currently uploaded file location folder.
            section c is remote server folder list.
            section d is remote server file listing.
 
By pressing right key we can easily get the copy / download option for the particular folder.
 
Step 1:
Backup all the files and folders inside your Drupal directory. You can do that by downloading them via your favourite FTP client.
 
Step 2: Backup/Export your database. Then, you have to export your Drupal database. You can do that by using PHPMyAdmin.
 
Please, make sure that you choose the correct database, which your Drupal application uses. If you are unsure about the Drupal database name, you will be able to find it in the settings.php file.
 
Now you can sit back and relax as you have successfully backed up your data and you can restore it any time you want!

How to render blocks in twig files

After lot of research, finally got the way to render blocks in twig files.

Basically there are two type of renders.

  1. When there is an existing instance of the block in the layout. The the block can be rendered in twig using preprocess as
    $block = Block::load('mediablock');
      $variables['social_links'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
    
  2. There is no instance or configurations for the block. Then in the preprocessor we need to create the instance, build the block and then render it
    $block_manager = \Drupal::service('plugin.manager.block');
      $config = [];
      $plugin_block = $block_manager->createInstance('farmjournal_social_sharing', $config);
      $render = $plugin_block->build();
      $variables['farmjournal_social_sharing'] = render($render);
    

How to send mail programmatically in Drupal 8

Sometime we require emails to be sent on certain events e.g. for a blog website or a news site we may need to send email after creating new article or blog or in case of e-commerce site we may need to send  confirmation mail after successful completion of an order. In this article we are going to explore how we can use Mail API in Drupal 8 programmatically for sending emails.

Here we will be looking on how to send the email after successful creation of article.

Sending email in Drupal is a two steps process:

  • Define your email properties (like subject, body, headers, etc.) in an appropriate hook_mail() implementation.
  • Use Mail manager to send email

Step 1:

When we send an email programmatically, we need to specify the module name that implements hook_mail().

Now lets see how do we implement it.



 

This is a simple implementation that defines one template identified as test_message (the $key). The other two function arguments are:

$message: passed by reference, and inside which we add as much boilerplate about our email as we need

$params: an array of extra data that needs to go in the email and that is passed from the mail manager when we try to send the email

This was all about implementation of hook_mail().

Step 2 : Using Mail manager to send email

This will gets triggered every time any Article will be created.

Every time when we will create any Article, we load the Drupal Mail manager service and start setting values for email. We need the following information:

  • $module : the module name that implements hook_mail() and defines our template
  • $key : the template id
  • $to :the recipient email address (the one found on the current user account)
  • $langcode :the language which goes inside the $params array and which will be used to translate the subject message
  • $params['subject'] : email subject
  • $params['message'] the email body
  • $send : the boolean value indicating whether the email should be actually sent

We then pass all these values to the mail() method of the mail manager. The latter is responsible for building the email (calling the right hook_mail() implementation being one aspect of this) and finally delegating the actual delivery to the responsible plugin. By default, this will be PHPMail, which uses the default mail() function that comes with PHP.

And this is all about sending emails programmatically using Drupal 8. We have seen the steps required to send email programmatically by the mail manager whenever we want it. We have also mentioned the default mail delivery plugin which is used to send emails in Drupal 8.

Source : https://github.com/adityaanurag/demoMail.git



 



Advance Your Business: Drupal 8 Support Ends - Take Action!

 

Managing user roles &amp; permission in Drupal 8

One of the reason why Drupal is hugely popular for content management application development, because of customizable content authoring workflow. We can simulate good old editorial experience where authors create the article, sub-editor review it and finally editors will confirm & publish if all organization lead criteria are met. In Drupal we create this permission system by creating roles.

Instead of assigning specific permissions to each user, permissions are assigned to roles. And then specific users are assigned role(s) e.g. author, reviewer, editor.

In this post we will explore how to create roles, specify permission for the role and assign specific role to user.

Step 1: First step is to go to Manage >> People >> Roles. Here you will find three default roles of "Anonymous", "Authenticated", and "Administrator" along with option to  add new roles  by clicking on +Add role.


Anonymous: Site visitors not signed in to your website. Generally they can view the pages of website.
Authenticated: Signed-in site visitors who are registered users on Drupal site.
Administrator: Signed-in administrative "super-users" of site. This role is always assigned every permission for every module which is enabled. Administrators have full access to all available functionality on your site. If we need, we can remove permission for certain functionalities.

user_role_page

Step 2: click on +Add role to add new role, which can be assigned to user. Here I’m creating a role called “Content Manager”.

creating_role

Once the role is added,. it will show up in role listing page.

listing_new_role_in_role_page

Step 3: Now it’s a time to assign our custom role “Content Manager” to the user.
Go to user listing page & edit one of the user.

user_created_with_no_role

On user edit page go to Roles section. check on “Content Manager” and click on save  button.

role_listing_in_user_edit_page

So, we have assign “Content Manager” role to one of the user. and it start listing on user listing page with new role.

user_role_assign_as_content_manager

Permissions:
Site permission let you control what users can do and see on your website. there are Many different functions and features available on Drupal site that can have a  permission that you can enable or disable.Permissions control access to administrative tasks and general website usage such as viewing published content.

permission page

Step 4: Finally, we can configure permissions for Content Manager at Manage >>People >> Permissions tab. To give Content Manager the ability to edit any page within the site, scroll down the permissions page and click the checkbox next to 'edit any' for each content type.

giving_permission_to_content_manager_to_edit_any_content

Now login with new user we just assigned the role of “Content Manager”. You will get edit option for all the basic page like below.  

 content_manager_getting_edit_option_in_node_page

This was one of the simplest role with permission we have added. This can be used as foundation to create organization specific content authoring workflow.

User creation with additional field

We always talk about building a community platform using Drupal. In large website we also need lot of user having different roles and associated permission. In this post we are going to explore how can we add users as well adding fields to user profile page. As a site admin, we have ability to add multiple user at any point of time. We can enable permission to allow anonymous users to create new account in your site.

1. How to create a new user account

Step 1.1: Log in as admin.


Step 1.2: Go to Manage >> People

 admin_toolbar

Step 1.3: Once you click on People link, you will be redirected to user adding page.

user_listing_page

Step 1.4: Click on +Add user for new user.

This page requires user email address, Username, Password, Confirm password, Status,    roles, profile picture, locale settings with contact settings.

Email address: The email address of the user, though not required, highly recommended. This information is kept private.

Username: This will be the username for the member and will appear on the site. Spaces are allowed as well as limited punctuation (.-'_).

Password: The user's password. make sure to use a strong password. combination of special character, lower & upper case with numbers and punctuation. Under that you will need to enter the same password again in the Confirm password field.

Status: This allows you to set a user to either Active status or Blocked, meaning they cannot use the site as a member.

Roles: This allows you to give members different roles. The two default roles are Authenticated User user and Administrator. More than one can be selected for a member.

Profile picture: Upload a user avatar in this section if you wish.

Contact settings: Allow other users to contact you via a personal contact form which keeps your email address hidden.

Locale settings: for selecting time zone.

adding_new_user

Step 1.5: Once we have entered user data, click on the Create new account button at the bottom of the page. Your new member will now appear in the list for all users.

added_new_usernew_user_created

like this an admin can add new user to his own site.

2. How to add custom field to user.


Incase if you wants to add few more field for user registration. you can do with few easy step.

Step 2.1: Go to Manage >> Configuration >> Account settings >> Manage fields and click on +Add field. currently i am adding Date of Birth field to user addition page.

people_field_settinglimit_field

 Step 2.2: Once you have saved field setting. it will start appearing on user page.

people_field_settinguser-account-setting-page

 

As we can see the new field “Date of Birth” is listed on user registration page.

creating_new_account

3. Enable Anonymous user to create new account

Similar to Drupal 7, 8 also has feature related to user account setting. These options are to allows admin to enable registration by either Administrators only, Visitors or Visitors, but administrator approval is required.

Drupal 7 user setting page

drupal-7-account-setting

Drupal 8 User settings page

drupal-8-account-setting

 

Option 1:
To check available option, i am selecting Administration only as a option.
In this case Anonymous user won’t get the option to register into Drupal site while visiting drupal-8/user/login.

drupal-8-only-admin-can-register

Option 2: By selecting visitors, anonymous user will get the option to register on site.

drupal-8enabled-anonymou-user-registration

Option 3: By selecting Visitors, but administrator approval is required will help anonymous user to create an account with blocked status. Once admin has approved the particular account will help user to login to the site.

account_created_require_admin_approval

Once admin has changed the user status from Blocked to Active, application will allow specific user to be login to drupal site.

How to Create a Website with Drupal 8

Drupal 8 has amazing features for everyone that can help you to build any Web site you want to. easier to customize components than never before. Drupal 8 uses Semantic HTML5 helps you to create interactions. You can make content structures easier to understand for people with disabilities.

In last couple of weeks we have covered varioous topics of Drupal 8 site building learning. Below is compiled list of articles which you can use as reference while building your first website.


  1. Setup Drupal 8 in windows with xampp stack package / Installing Drupal with Drush, the Basics - before we begin with Drupal 8 site creation, we need to install Drupal 8 to our local web server.
     
  2. Understanding Block layout in Drupal theme structure - we will go through layouts structure & custom block library and how to assign  basic content blocks in selected region.
     
  3. Changing the Appearance of your new site - we will learn How to install new theme & configure their settings according to the requirement.
     
  4. Using the Content Type to manage content consistently  - Manage Content by Creating custom content type and adding fields to those content type.
     
  5. Manage your articles using Taxonomy in Drupal 8 - we will create a fresh new vocabulary and add terms to those vocabulary. adding those terms to a fresh content.
     
  6. Newly introduced mobile first Menu management in Drupal 8 - create a new menu type with custom links and assign the same menu block to one specific region.
     
  7. Learn how to use views which is part of core module in Drupal 8 - we will learn how can we create view block and view page to showcase specified content type with few fields.
     
  8. Creating Home page and basic pages - How an admin can create a Basic Page and Homepage with few simple steps.
     
  9. Getting Comment on your article - Create an comment type and field to the same and assign those comment to different entity.

Creating Home page and basic pages

Creating a home page or front page in Drupal 8 is quite similar to the way we used to do Drupal 7. By default home page will list out all the nodes in teaser view. We just need to create a new page and schedule it  to display on page or you can also promote other node  to be displayed on home page. However, most of time we would like to have a custom page as our site home page not like listing of teaser view. In this blog post I will explain the process of changing the front page of your new Drupal 8 website.

Step 1 :  Log into your Drupal 8    
Step 2 : select “manage”  menu from the toolbar from   the main menu on the top.

admin_toolbar_menu

Under manage there is option of  “configuration

admin_toolbar_menu_expanded

 

Step 3 : clicking on configuration will redirect you to Home >> Administration
click on “site information” under SYSTEM. Under Front Page provide the Default Front page url & that page would be assigned as home page for our site.

I have assigned node id 4 to display as page.

site_information_setting

After entering the chosen node, click on the Save Configuration. Now when you click the site logo or Home menu link, you should see the newly assigned node as home page.

Default page: when we don’t have any assigned page in our site setting in that case user page of logged in user  itself becomes the front page of your drupal site.

drupal_default_home_page


 

home_page_assign_to_node

Creating a Basic page

Step 1: To add Basic page  go to content >> Add content >> Basic Page

creating_basic_page


Step 2: If you would like to add some additional field on Basic page click on Structure >> Content types >> Basic page >>  Manage fields >> Add field

manage_field

 

Step 3: Let's add one email field for basic page with label “Mail”. For this we need to go to admin >> structure >> types >> manage >> page  >> fields and click on Add field.

mange_field_label

Step 4: Limit the no of values for email field. In this case I am limiting it to 2

 manage_field_no_of_values

Step 5: Next we will change label name, help text, default value etc for the fields we added above.

manage_field_settings

 

Step 6: So now we are done with adding the field,.we can view the field under page manage field tab.

custom_field_displaying

Step 7: Add a new page by visiting https://drupal-8.0.2/node/add/page .
we can see our newly added two mail field with default value. Fill up all the detail and Save and Publish the page.

create_page

Step 8: Once basic page has been submitted you will be redirected to node view page.

page_with_additional_info

We have completed how to assign a specific node to Home page  as well as create a new basic page.

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