Skip to main content

In Drupal 8, there is a need to store information associated with a user's session. There are two services for temporarily storing user-specific and non-user-specific data in key/value format, namely, use user.private_tempstore and user.shared_tempstore.

TempStore

A tempstore is for data that needs to be persisted between requests without being saved back to the canonical storage (such as an entity or configuration object).  

Two methods can be effectively used for  private_tempstore - Use "\Drupal::service()" and Dependency Injection.

Use "\Drupal::service()"

To set Temporary Data

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

To read Temporary Data

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->get('my_variable_name', $some_data);

PrivateTempStore

A PrivateTempStore can be used to make temporary, non-cache data available across requests. The data for the PrivateTempStore is stored in one key/value collection. PrivateTempStore data expires automatically after a given timeframe.

Dependency Injection

  • To use this service need to invoke the following “use” statement

          use Drupal\user\PrivateTempStoreFactory;

          use Symfony\Component\DependencyInjection\ContainerInterface;

  • Temporary store - that is private to the current user.

Storing session data vs storing temporary data

Which is efficient, storing data using session variable or use data for a limited term. Let's see which approach is preferable: 

  • Both are used for same purpose.
  • But Drupal 8 services provides needed abstraction and structure for interacting with a global construct. It's part of an overall architecture that allows Drupal developers to build and extend complex applications.
  • Use session manager for anonymous user to store the data.

Stay connected with the latest news on web strategy, design, and Drupal 8 development.
 

Site speed is crucial when you run a site. If a site takes too much time to load, visitors will get frustrated and leave the site to go elsewhere. Slower performing sites don't rank well on search engines.
 
Drupal performance optimization can be a complicated specialization in its own right. It takes too long to investigate performance issues and fix them. However, here are some quick fixes and simple methods to move you into the right direction. 
 
1. Keep the core, contrib module and themes updated
 
It is critical that you are running the most recent Drupal version as updates by and large contain bug fixes and performance improvements. Keep the core, contribs module, and themes with the latest Drupal update.
 
To run updates, navigate to “Reports” → “Available Updates.”
You can then click on “Check manually” to scan for additional updates.
 
     
2. Enable Page Caching  
 
To enable, navigate to “Configuration” → “Development” → “Performance.”
Enable “Cache pages for anonymous users” and also “Cache blocks.” You can then choose a time value for minimum cache lifetime and expiration of cached pages.
Click on “Save configuration.”
 
3. Turn on Block Caching 
 
Enable caching options for all the blocks that will boost the performance.
 
4. Aggregate Javascript and CSS files  
 
Browser doesn’t have to fetch as many files and it reduces the total number of HTTP requests being made. Enhance your frontend performance and download times by aggregating your CSS and Javascript files.
 
To enable, navigate to “Configuration” → “Development” → “Performance.”
Enable “Aggregate and compress CSS files” and “Aggregate Javascript files.”
Click on “Save configuration.”
 
5. Disable unnecessary modules
 
Every module adds to the amount of code that needs to be available for a page load. And it also increases the number of lookups. Wherever possible use a generic module in place of multiple module that does specific functionalities.
 
6. Cache views content
 
The views module is probably one of the most popular modules on Drupal 8 development. If you have it installed you can also enable caching on it.
 
To enable, navigate to “Administration” → “Structure” → “Views.”
Click “Edit” on the view you want to enable caching on.
Expand the “Advanced box.”
Select “Time-based” and click on “Apply (all displays).”
 
7. Disable DB logging 
 
When the Database Logging module is enabled, you're shown with a menu item in the "Logging and alerts" of the site configuration. When the Database Logging module is disabled, although the menu item for Database logging goes away, "Logging and Alerts" becomes empty and stays there. If you visit admin/settings/logging, you're shown with an empty page.
 
8. Reduce 404 Errors
 
Use third party services such as “online Broken Link Checker” or a tool like Screaming Frog and avoid using a module to check for 404s and save your server’s resources.
 
Stay away from expensive 404 errors using Drupal Fast 404 module as it can normally such errors with less than 1MB of memory.
 
9. Fast 404 Responses 
 
When your site has broken images or CSS file paths, it will reduce the page speed significantly The Fast 404 module changes the way 404 errors are handled, delivering fast 404 error messages.
 
10. Compress Images 
 
The loading speed of large image files are slow. Make the file size smaller so they are not larger than they need to be. For image fields, you can use image styles (admin/config/media/image-styles) to resize images to the desired size.
 
11. Use Sprite Sheets
 
An image sprite is an aggregation of a single image. A web page loaded with a number of images is slow to load and generates multiple server requests. Reduce multiple server requests with image sprites and save bandwidth.
 
12. Lazy Loading of Images 
 
Lazy loading images can substantially increase your page load times by ensuring the image will only load when it is visible to the browser window. “Image Lazyloader” is the most popular Drupal module over 18,000 downloads.
 
13. Content Delivery Network
 
Implementing a Content Delivery Network (CDN) with Drupal is a fast and easy way to instantly see decreased load times for your website. Protect your digital assets such as product images, javascript, CSS across the world will ensure that they are delivered faster to your visitors and reducing latency.
 
This represents a run down of 13 easier ways to boost the performance of Drupal sites. Track the changes to ensure that there is actually an improvement in the performance.
 
Let me know in the comments below if you can think of any more quick wins to improve performance of a Drupal site.
 
 

Drupal 8 Form API is similar to Drupal 7 form API. The forms are still represented with nested array structure as Drupal 7 to render the data. However, there is a separate validation and submission form as well.

Form Generation

  • There are different classes, functions and interfaces to choose depending on the type of form you are creating.
  • Drupal 8 has some new HTML 5 elements (telephone, email, date) to render array structure.
  • The basic workflow of a form is defined by buildForm, validateForm, and submitForm methods of the interface.
     

Create a Directory Structure

Create a directory within a new custom module. 

Example 

Create your formExample.module in below directory structure

modules/formExample/
css
js
src
    Controller
         formExampleController.php
    Form
         formExampleForm.php
    Entity
          tomato.php
formExample.info.yml
formExample.routing.yml
formExample.module

Form ID

This needs to return a string that is the unique ID of your form. Namespace the form ID based on your module's name.

Example

Drupal 8

public function getFormId() {
       return 'multistep_form_one';
}

Drupal 7

function multistep_form_one($form,$form_state) {

}

buildForm

This needs to returns a Form API array that defines each of the elements your form is composed of.

Example

public function bulidForm(array $form, FormStateInterface $form_state) {
       $form[‘name’] = array(
            ‘#type’ => ‘textfield’,
            ‘title’=> ‘name’,
       );
       return $form;
}

validateForm

Example

public function validateForm(array $form, FormStateInterface $form_state) {
       if(!is_numeric($form_state->getValue(‘name’)){
           $form_state->setErrorByName(“Enter only alphabets”);
       }
}

submitForm

Example

public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }
}

 

We are done with creating custom form elements, fields, field formatters, etc. in Drupal 8. Our expert Drupal developers will be covering session data storage with Drupal 8 in future posts in this series. Join the conversation by commenting below with any questions or feedback on using these Drupal 8 constructs.

Drupal is powered by best-of-the-breed technologies which makes Drupal highly customizable and scalable. Drupal is free and open source and supported by an active community of over 1.3 million members from 100,000+ contributing users resulting in more than 37,000+ free plug-in and modules as well as themes which extends its core capabilities. 

Drupal 8 provides built-in security by default and simply bug-free modules aren’t enough to address the security challenges. When your site comes under fire from hackers and spambots, you always need an extra layer of security modules that provide your website better protection against exploitable vulnerabilities.

To that end, we have compiled top rated six essential Drupal modules to better protect your website from security vulnerabilities and other risky elements. This will create a strong security layer around your website, and help Drupal developer keep all sorts of Drupal security issues at bay.

1. Password Policy

The Password Policy module is configured with pre-defined parameters for creating secure passwords after ensuring that certain conditions are validated. With a little quick and easy setting of constraints, this security module can keep that door bolted shut from vulnerabilities.

2. TwoFactor Authentification

This module is increasingly used by site administrators to provide an extra layer of security for accessing your Drupal website by using two-factor authentication with onetime password/PINs delivered on your mobile devices. When the pre-generated codes are successfully entered, access is granted to users. This mechanism protects the user account from attackers.

3. Automated Logouts

This module enables site administrators to create a policy of logging out users after a specified period of inactivity. It is highly customizable by role-based permissions to enforce different timeouts. It can be Automated Logout can be easily integrated with Javascript timers.

4. Security Review

This module performs automated testing for security vulnerabilities against traditional attackers. It does not actually make your site secure and locked down, but runs a series of security checks for arbitrary PHP execution, protection against XSS and a lot more, and provides solutions to fix issues.

5. Username Enumeration Prevention

Attackers can easily find usernames with loopholes in the system to access the Drupal site with username enumeration. Attackers can enter a username that does not exist or use the ‘forgot password form’ to get a confirmation message stating that the auth credentials are invalid. When the attacker persists by trying entering random usernames until the valid username has been found. This module will will make it impossible for the attacker to access the Drupal website. When this module is enabled, the error message will be replaced for the standard unknown username and the user will be redirected back to the login form. If the user does not exist, no password reset email will be sent. The attacker
Can no more exploit the username.

6. Security Kit

This module is reliable, user-friendly and provides Drupal with various security hardening options that can be used in your Drupal site to protect against different web application vulnerabilities. This module promises security for cross-site scripting, cross-site request forgery, clickjacking, and SSL/TLS.

Use these six Drupal modules to get maximum protection to your website from unwanted hackers and attackers. Keep your Drupal site safe and secure with all these modules, we would also recommend you to ensure the perfect dose of Drupal development needs with Anubavam.

There are more than 30,000 contributed modules created by Drupal developers to extend your site functionality beyond Drupal core. First up, we have compiled top rated 10 essential Drupal 7 modules that you can’t live without:

1. Administration menu

Administration menu is one of the most popular Drupal 7 module which provides user-friendly drop-down menus for the most common administrative tasks in your website.  

2. Views

This is one of the most essential module in every Drupal website to create customized lists and display content in multiple places and ways you like. Views lets you easily create custom displays of data, while making it simple to keep adding and editing great amount data.  

3. Ctools

Ctools is a powerful tool to create various pages on websites. It is used heavily in a number of cases along with Panels, Views, Page Manager and other modules.

4. Libraries API

Drupal 7 provides a common repository for external libraries (non-Drupal) in sites. Libraries API module eases the process of providing support to various externally developed and distributed libraries, such as jQuery plugin.

5. Panels

Panels module allows you to create customized layouts for pages with capabilities to improve the look-and-feel of various content types. The custom pages are highly flexible to create custom layouts for nodes and landing pages, while overriding default nodes and taxonomy page.

6. Token

Token module is a must-have module which provides a centralized API for inserting simple placeholder tokens and use them with associated values. Tokens use the strings of text such as username with the specific syntax and replace it with the name of the person.  

7. Pathauto

Setting patterns for any content in your website is easy using Pathauto module. Automatically generate nice URL aliases for your blog posts and improve visibility to your pages in the search engines. Pathauto patterns are user-friendly and supports multilingual URL aliases.  

8. Date

Easily schedule tasks, events and programs with the powerful Date module. This also includes two new date processing modules, Date Repeat Field and Date All Day modules, to create date fields and handle All Day values.

9. Webform

It is frustrating and time-consuming for users to stand in queues and fill out forms to accomplish tasks. Webform module enables you to create simple and easy-to-use forms for surveys, feedback, contacts, admission, employment, etc. Create custom forms and fields for specific needs and engage users in a productive way. Webforms with multiple types and fields can be created even by non-technical people to collect information from users.

10. Entity

We have entities which helps you bring every piece of specialized content together with nodes and much more, to provide the required functionality. You can easily create custom entity types stored in the database such as nodes, users and taxonomy.

Subscribe to Drupal Modules
 

start with anubavam today

You have an idea we have engineers to convert your ideas into reality

Request Quote