drupal

Install optional config

// Install optional config.
$path_to_module = \Drupal::service('extension.path.resolver')->getPath('module', 'dev_tools');
$config_path = $path_to_module . '/config';
$config_source = new FileStorage($config_path);
\Drupal::service('config.installer')->installOptionalConfig($config_source);

Database query examples

Update the 'pair' field using an expression to concatenate the fields.

$database = \Drupal::service('database');
$database->update('mono_currency_rates')
  ->expression('pair', "CONCAT(currency_code_sell, '/', currency_code_buy)")
  ->isNull('pair')
  ->execute();

Sort:

Key Symfony Components Used in Drupal

  1. HttpFoundation: This component replaces PHP's native global variables, offering a more powerful and flexible way to handle HTTP requests and responses. It standardizes how Drupal handles web requests and responses, improving consistency and reliability.
  2. Routing: Symfony's Routing component is used to map URLs to specific controllers and actions in Drupal.

Create custom Drush command

Create in module directory file named drush.services.yml with similar content:

services:
  custom_base.commands:
    class: Drupal\custom_base\Commands\CustomCommands
    arguments:
      - '@config.factory'
      - '@entity_type.manager'
      - '@database'
    tags:
      -  { name: drush.command }

In Drupal\custom_base\src\Commands need to create file CustomCommands.php:

Git commands

To remove files from the GIT repository based on .gitignore, without deleting them from the local file system:

git ls-files -i -c -X .gitignore | xargs git rm --cached

Restore admin user

Programaticaly restore admin user could be done with this code:

use Drupal\user\Entity\User;
$user = User::create([ 
'name' => 'admin', 
'mail' => 'admin@example.com', 
'status' => 1,
'roles' => ['administrator'],
'pass' => 'newpassword',
]); 
$user->save();

Translate

<h1>{{ 'Hello world'|t }}</h1>
<div class="mt-3 alert alert-warning">
    <p>{% trans %}Do you know how translation works?{% endtrans %}</p>
</div>

Using translate function with parameters:

{{ 'Last checked: @time ago'|t({'@time': time}) }}

 

 

{{ "Text to translate"|t({}, {'context' : 'Context name'}) }}

and

Commerce

Load Order and change it status to "Cancelled":

$order = \Drupal::entityTypeManager()
->getStorage('commerce_order')
 ->load(1);
$order->getState()->applyTransitionById('cancel');
$order->save();
Subscribe to drupal