Showing posts with label Drupal 8. Show all posts
Showing posts with label Drupal 8. Show all posts

Drupal 10 Interview Question Bank (With Answers)

 Multiple databases can be connected to Drupal using the Database API and configuring settings.php file.

     Use the Database API to connect to additional databases

     Add the database connection details to settings.php file

     Use the db_set_active() function to switch between databases

     Use the db_query() function to execute queries on the selected database


#Drupal 8

#Adding additional databases to your configuration

Preferably you would add your configuration to the settings.php file for your site so that all modules can interact with the new database.

In your settings.php:

$databases['default']['default'] = array (
  'database' => 'drupal8_default',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['second']['default'] = array (
  'database' => 'drupal8_second',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

#Connect to the correct data base:

//To get the default database key "default"
$con = \Drupal\Core\Database\Database::getConnection();

//To get another database (here : 'second')
$con = \Drupal\Core\Database\Database::getConnection('default','second');

//To set the active connection
$conn = \Drupal\Core\Database\Database::setActiveConnection('second');

What is Patch and How to create a patch in Drupal

A patch is a software update comprised code inserted (or patched) into the code of an executable program. Typically, a patch is installed into an existing software program. Patches are often temporary fixes between full releases of a software package.

Patch is a file that consists of a list of differences and is usually created with the help of the git diff command. In the Drupal community, developers make use of this patch file as a contribution to fix an issue or enhance a feature in a module, theme, or even for Drupal core.

Below are the step for creating a patch

1 - Create and set up a repository on GitHub specifically for creating patch files. It is best to maintain a single git repository for the patch files that you will be applying to your drupal project.

2 - Move the module/theme or core files that you need to generate patches to the newly created git repository

3 - Make the necessary changes to a file on your local

4 - Verify that the “git status” command shows the file that you have modified.

5 - To generate the patch, use the following command:
      
        git diff --no-prefix [file-name] > ./file-name.patch
 

drupal 8 how i create a custom form to programmatically created block and assign to it in variable in preprocess

Preprocess page assign a custom block to variables code

$customblock = \Drupal::service('plugin.manager.block')-  >createInstance('custom_block_id', []);

 $variables['home_meal_plan'] = $customblock->build(); 

*******************************************************************************

1 - Creating custom form

goto - custom_module\src\Form and create a customform.php

<?php

namespace Drupal\meal_plan\Form;

use Drupal\Core\Form\FormBase;

use Drupal\Core\Form\FormStateInterface;

use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\cms_pages\Controller\CommonFunc;

/**

 * Provides meal plan form.

 *

 * @internal

 */

class HomeMealForm extends FormBase {

  /**

   * {@inheritdoc}

   */

  public function getFormId() {

    return 'home_meal_form';

  }

  /**

   * {@inheritdoc}

   */

  public function buildForm(array $form, FormStateInterface $form_state) {

    global $base_url;

    $hindi = CommonFunc::isHindi();

    if (\Drupal::currentUser()->isAnonymous()) {

      $footer_content = CommonFunc::getCmsContent('field_meal_plan_footer_content');

      $meal_plan_heading = CommonFunc::getCmsContent('field_meal_plan_heading');

        $form['age'] = [

          '#type' => 'textfield',

  '#attributes' => array('class' => array('inptFld'), 'id' => array('home-meal-age') ,'autocomplete' => array('off')),

          '#default_value' => '',

          '#placeholder' => 'Eg. 7',

          '#required' =>TRUE

        ];

      $query = \Drupal::entityQuery('taxonomy_term');

      $query->condition('vid', 'food_type');

      $query->sort('name');

      $tids = $query->execute();

      $options = [];

      $options = [

    'Vegan' => t('Vegan'),

        'Veg' => t('Veg'),

'Eggetarian' => t('Eggetarian'),

'Pescatarian' => t('Pescatarian'),

        'Nonveg' => t('Non-Veg'),

      ];

  $options1 = [

    '2-12' => t('2-12'),

        '13-17' => t('13-17'),

'18-25' => t('18-25'),

'25-50' => t('25-50'),

      ];


      $form['food_type'] = [

        '#type' => 'radios',

        '#options' => $options,

        '#default_value' => 'Vegan',

        '#required' => TRUE,

      ];

  

  $form['age_range'] = [

        '#type' => 'radios',

        '#options' => $options1,

        '#default_value' => '2-12',

        '#required' => TRUE,

      ];  

      $form['footer_content'] =[

        '#markup' => $footer_content,

      ];

      $form['submit'] = [

        '#type' => 'submit',

        '#value' => t("Apply"),

'#attributes' => array('class' => array('primary-button hvr-ripple-out')),

        '#validate' => ['::submitValidateMeal'],

      ];

      $form['#theme'] = 'HomeMealForm';

      $form['#meal_plan_heading'] = $meal_plan_heading;

      $form['#attached']['library'][] = 'meal_plan/meal_style';

      return $form;

    }

  }

  /**

   * {@inheritdoc}

   */

  public function submitValidateMeal(array &$form, FormStateInterface $form_state) {

    if ($form_state->getValue('age') == '') {

        $form_state->setErrorByName('age', 'Please select date of birth');

    } 

    elseif ($form_state->getValue('age') < 1) {

      $form_state->setErrorByName('age', 'Minimum required age is 1 year.');

    } 

    elseif ($form_state->getValue('age') > 12) {

      $form_state->setErrorByName('age', 'The recommendations are for healthy children between 1 year to 12 years of age. Please enter appropriate age.');

    }

  }

  /**

   * {@inheritdoc}

   */

  public function submitForm(array &$form, FormStateInterface $form_state) {

    global $base_url;

    $age = $form_state->getValue('age');

    $food_type = $form_state->getValue('food_type');

   $age_range = $form_state->getValue('age_range');

    $meal_data = ['age' => $age, 'food_preference' => $food_type];

    $session = \Drupal::request()->getSession();

    $session->set('meal_data', $meal_data);

    $form_state->setRedirect('meal_plan.unreg_routine');

  }

}

2- creating a custom block

Goto - custom_module\src\Plugin\Block

create a php file customblock.php

<?php

namespace Drupal\meal_plan\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * @Block(
 *   id = "home_custom_meal_form_block",
 *   admin_label = @Translation("Custom Meal Plan Block"),
 *   category = @Translation("Custom Meal Plan Block")
 * )
 */
 
class customblock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\meal_plan\Form\HomeMealForm');
    return $form;

  }
}

3- assign custom create Block to a variable in preprocess : in theme.theme file

/**

 * Implements hook_preprocess().

 */

function theme_new_preprocess(array &$variables, $hook) {

$variables['base_path'] = base_path();

$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();

$current_path = \Drupal::service('path.current')->getPath();

$variables['current_path'] = $current_path;

$alised_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

$alised_path = ltrim($alised_path, '/');

$variables['alised_path'] = $alised_path;

$current_url = explode("/", $alised_path);

if($variables['is_front']) {

$customblock = \Drupal::service('plugin.manager.block')->createInstance('home_custom_meal_form_block', []);

        $variables['home_meal_plan'] = $customblock->build();

}

}


Drupal 8 and Drupal 9 set and get COOKIE example with symphony HttpFoundation Component

Setting Cookies

The response cookies can be implemented through the headers public attribute:

use Symfony\Component\HttpFoundation\Cookie;

$response->headers->setCookie(Cookie::create('foo', 'bar'));

The setCookie() method takes an instance of Cookie as an argument.

You can clear a cookie via the clearCookie() method.

In addition to the Cookie::create() method, you can create a Cookie object from a raw header value using fromString() method. You can also use the with*() methods to change some Cookie property (or to build the entire Cookie using a fluent interface). Each with*() method returns a new object with the modified property:

$cookie = Cookie::create('foo')
    ->withValue('bar')
    ->withExpires(strtotime('Fri, 20-May-2011 15:25:52 GMT'))
    ->withDomain('.example.com')
    ->withSecure(true);
n addition to the Cookie::create() method, you can create a Cookie object from a raw header value using fromString() method. You can also use the with*() methods to change

Drupal 8 cookies can be set using ResponseHeaderBag from the Symfony\Component\HttpFoundation\Response object.
Set new cookie value 
 use Symfony\Component\HttpFoundation\Cookie; 
 $cookie = new use Cookie('cookie_name', TRUE); 
$response->headers->setCookie($cookie); 
return $response; 
Get cookies value 
 $request->cookies->get('cookie_name');

Pathauto Module functionalities and usage

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

What are the functionalities and usage of the Paragraph Module


The Drupal 8+ Paragraphs module is a complete rewrite of the D7 module. Although based on the Entity Reference module in core, Paragraphs requires the Entity Reference Revisions module .

The Drupal Paragraphs module can make processes like these much more manageable for non-technical users while also giving developers the ability to control the formatting and appearance of such specially formatted elements at the theme level.

In practice, Paragraphs allows us to insert elements much like content fields, but instead of adding these around the body of any given piece of content, they are effectually inserted throughout the body.

Paragraphs defines

  • A selection method for the Entity Reference field
  • A widget for the Entity Reference Revisions field
  • Paragraph types

Features

This module has some overlapping functionality with field_collection, but this module has some advantages over field_collection.

  • Different fields per paragraph bundle
  • Using different paragraph bundles in a single paragraph field
  • Displays per paragraph bundle
  • Bundles are exportable with features.
  • Entities, so: exportable field bases/instances, usable in Search API, usable in View
Theming Paragraphs in Drupal 8

Paragraphs uses template naming suggestions like core Drupal modules. The default paragraphs template is provided in paragraphs/templates/paragraph.html.twig.

The following suggestions are available, from most specific (used first) to least specific:

  1. paragraph--[type]--[view-mode].html.twig  (e.g. paragraph--image--default.html.twig)
  2. paragraph--[type].html.twig (e.g. paragraph--image.html.twig)
  3. paragraph--[view-mode].html.twig (e.g. paragraph--default.html.twig)
  4. paragraph.html.twig

After adding a template, you must rebuild the cache in order for Drupal to discover your new template.

It is possible to create custom template name suggestions using the hook_theme_suggestions_HOOK_alter() function.

How to Create Directory in Drupal 8 and Drupal 9

Drupal 8

function drupal_mkdir

drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL)

Creates a directory, optionally creating missing components in the path to the directory.

Code

function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {

  return \Drupal::service('file_system')->mkdir($uri, $mode, $recursive, $context);
}

Deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::mkdir().

Drupal 9

public function FileSystem::mkdir

public FileSystem::mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL)

Creates a directory, optionally creating missing components in the path to the directory.

When PHP's mkdir() creates a directory, the requested mode is affected by the process's umask. This function overrides the umask and sets the mode explicitly for all directory components created.

@todo Update with open_basedir compatible recursion logic from \Drupal\Component\PhpStorage\FileStorage::ensureDirectory().

Parameters

string $uri: A URI or pathname.

int $mode: Mode given to created directories. Defaults to the directory mode configured in the Drupal installation. It must have a leading zero.

bool $recursive: Create directories recursively, defaults to FALSE. Cannot work with a mode which denies writing or execution to the owner of the process.

resource $context: Refer to http://php.net/manual/ref.stream.php

Return value

bool Boolean TRUE on success, or FALSE on failure.

Overrides FileSystemInterface::mkdir 

Drupal 7

function drupal_mkdir

Creates a directory, optionally creating missing components in the path to the directory.

When PHP's mkdir() creates a directory, the requested mode is affected by the process's umask. This function overrides the umask and sets the mode explicitly for all directory components created.

Parameters

$uri: A URI or pathname.

$mode: Mode given to created directories. Defaults to the directory mode configured in the Drupal installation. It must have a leading zero.

$recursive: Create directories recursively, defaults to FALSE. Cannot work with a mode which denies writing or execution to the owner of the process.

$context: Refer to http://php.net/manual/ref.stream.php

Return value

Boolean TRUE on success, or FALSE on failure.



DRUPAL 9 - Module Required for Development

1- Admin Toolbar

The Admin Toolbar module intends to improve the default Toolbar (the administration menu at the top of your site) to transform it into a drop-down menu, providing a fast access to all administration pages.
The module works on the top of the default toolbar core module and is therefore a light module and keeps all the toolbar functionalities (shortcut / media responsive).

2- Token

Provides additional tokens not supported by core (most notably fields), as well as a UI for browsing tokens.
Example:
Site Information: name,login_url,email,slogan etc
Required Module for pathauto, google Analytics etc.

3- Chaos Tool Suite (ctools)

This suite is primarily a set of APIs and tools to improve the developer experience. It also contains a module called the Page Manager whose job is to manage pages. In particular it manages panel pages, but as it grows it will be able to manage far more than just Panels.

For the moment, it includes the following tools:

Plugins -- tools to make it easy for modules to let other modules implement plugins from .inc files.
Exportables -- tools to make it easier for modules to have objects that live in database or live in code, such as 'default views'.
AJAX responder -- tools to make it easier for the server to handle AJAX requests and tell the client what to do with them.
Form tools -- tools to make it easier for forms to deal with AJAX.
Object caching -- tool to make it easier to edit an object across multiple page requests and cache the editing work.
Contexts -- the notion of wrapping objects in a unified wrapper and providing an API to create and accept these contexts as input.
Modal dialog -- tool to make it simple to put a form in a modal dialog.
Dependent -- a simple form widget to make form items appear and disappear based upon the selections in another item.
Content -- pluggable content types used as panes in Panels and other modules like Dashboard.
Form wizard -- an API to make multi-step forms much easier.
CSS tools -- tools to cache and sanitize CSS easily to make user-input CSS safe.

4- Devel

Devel module contains helper functions and pages for Drupal developers and
inquisitive admins:

A block and toolbar for quickly accessing devel pages
Debug functions for inspecting a variable such as dpm($variable)

Debug a SQL query dpq($query or print a backtrace ddebug_backtrace()

A block for masquerading as other users (useful for testing)
A mail-system class which redirects outbound email to files
Drush commands such as fn-hook, fn-event, token, uuid, and devel-services


Webprofiler. Adds a debug bar at bottom of all pages with tons of useful
information like a query list, cache hit/miss data, memory profiling, page
speed, php info, session info, etc.

Devel Generate. Bulk creates nodes, users, comment, taxonomy, media, menus for development. Has
Drush integration.

This module is safe to use on a production site. Just be sure to only grant
access development information permission to developers.

5- Pathauto

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

6- Paragraphs

Paragraphs is the new way of content creation!
It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.

Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.

Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.

Paragraphs module does not come with any default Paragraph Types but since they are basic Drupal Entities you can have complete control over what fields they should be composed of and what they should look like through the typical Drupal Manage Fields and Manage Display screens.

You can also add custom option fields and do conditional coding in your CSS, JS and preprocess functions so that end-users can have more control over the look and feel of each item. This is way much cleaner and stable than adding inline CSS or classes inside the body field's source.

Some more examples:

Add a block of text with an image left to it
Add a slideshow between blocks of text
Add a youtube embed between your text
Add quotes between your content blocks

Paragraph






Paragraphs





















7- Redirect

Provides the ability to create manual redirects and maintain a canonical URL for all content, redirecting all other requests to that path.

This module provides a common API for loading, deleting, and saving redirects. It also provides case-sensitive redirect matching with a hook to allow the other modules to decrease the candidate redirects.

8- Twig Tweak

Twig Tweak is a small module which provides a Twig extension with some useful functions and filters that can improve development experience.

Drupal View

{{ drupal_view('whos-s_new','block_1')}}

Drupal View Result

{{ drupal_view_result('who_s_new','block_1')}}

9- Webform

The Webform module allows you to build any type of form to collect any type of data, which can be submitted to any application or system.

Every single behavior and aspect of your forms and their inputs are customizable. Whether you need a multi-page form containing a multi-column input layout with conditional logic or a simple contact form that pushes data to a SalesForce/CRM, it is all possible using the Webform module for Drupal 8/9.

10-Backup and Migrate

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

11-Advanced CSS/JS Aggregation

AdvAgg allows you to improve the frontend performance of your site. Be sure to do a before and after comparison by using Google's PageSpeed Insights and WebPagetest.org. The performance benefits are achieved by using some of the features found in AdvAgg and its sub modules. Out of the box AdvAgg's frontend performance will be similar to cores.

13- Diff, Shield & Socket

Diff 

This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.

Shield 

PHP Authentication shield. It creates a simple shield for the site with Apache authentication. It hides the sites, if the user does not know a simple username/password. It handles Drupal as a "walled garden".
This module helps you to protect your (dev) site with HTTP authentication.

Socket

SecKit provides Drupal with various security-hardening options. This lets your mitigate the risks of exploitation of different web application vulnerabilities.

Cross-site Scripting
Content Security Policy implementation via Сontent-Security-Policy (official name), X-Content-Security-Policy (Firefox and IE) and X-WebKit-CSP (Chrome and Safari) HTTP response headers (configuration page and reporting CSP violations to watchdog)

Control over Internet Explorer / Apple Safari / Google Chrome internal XSS filter via X-XSS-Protection HTTP response header

14- Environment Indicator

This module will help you to keep sane while working on your different environments by adding a configurable color bar to each one of your environments. The Environment Indicator adds a coloured bar on the site informing you which environment you're currently in (Development, Staging, Production, etc.). This is incredibly useful if you have multiple environments for each of your sites, and like me, are prone to forgetting which version of the site you are currently looking at.

This module can help you avoid making configuration changes to your live server by mistake by adding a coloured strip to the side of your site, clearly marking each version of the site.


15- Configuration Split

This module allows to define sets of configuration that will get exported to separate directories when exporting, and get merged together when importing. It is possible to define in settings.php which of these sets should be active and considered for the export and import.



Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...