Data manipulation is the changing of data to make it easier to read or be more organized. For example, a log of data could be organized in alphabetical order, making individual entries easier to locate. Data manipulation is often used on web server logs to allow a website owner to view their most popular pages, and their traffic sources.

Inline with this customizable variables and data manipulation is the most basic requirement that has to be met by any content management system. This is an important aspect which allows the user to create or update new variables and define new functions. Data management is essential in all web systems in a way that we can easily handle and mold in our specific need and to function correctly. The need for data manipulation becomes even more important with a growing volume of data being used and processed, thus in Drupal, this is provided in a neat manner. One way to do it is by using a preprocess, preprocess functions are specially-named functions that can be used to add new variables to a twig template file. 

They are commonly used by themes to add new variables based on custom PHP logic and simplify accessing the data contained in complex entity structures. Preprocess functions expose the dynamic data and manage to Twig template files, or to alter data provided by another module based on custom logic. 

Below is a sample implementation of a hook_preprocess_page on the .theme file that will create the variable ‘custom_variable’ and have a value of ‘custom value’ and passed together with the other default variables that is set on the drupal page. To practice this feature we just need to perform this following in .theme or .module files and were ready to go.


# 1. Implement a hook_preprocess

/sites/default/files/assets/images/article-image/Anosa/Screen%20Shot%202021-03-03%20at%2010.50.59.png


Note :

  • Don't forget to replace [THEME_NAME] with your theme’s machine name
  • The if statement asks, “If there isn’t already a value in the variable called custom_variable set it to this default, custom_value.”

 

# 2. Use new variables in the partial template

/sites/default/files/assets/images/article-image/Anosa/Screen%20Shot%202021-03-03%20at%2010.57.40.png


This twig file will return the value “custom_value” that we set on the preprocess. And with this we’re finished in creating custom variables that we can call or use in our twig files. This is also handy in our custom module, they have the same process but instead of using the .theme file we'll use the .module file. Here is the sample.

/sites/default/files/assets/images/article-image/Anosa/Screen%20Shot%202021-03-09%20at%2016.22.51.png

Note :

  • Don't forget to replace [MODULE_NAME] with your module machine name.

 

This is just the steps we need to take in creating our own variables. Easy peasy right? So start creating your own and enjoy!

Reference:

    https://www.computerhope.com/jargon/d/datamani.html