Skip to content

Instantly share code, notes, and snippets.

@radheymkumar
Last active July 20, 2021 01:57
Show Gist options
  • Save radheymkumar/bb068f98187cba93065802cb8e6a6851 to your computer and use it in GitHub Desktop.
Save radheymkumar/bb068f98187cba93065802cb8e6a6851 to your computer and use it in GitHub Desktop.
Drupal 8 Common Code
Example URL - http://xandeadx.ru/blog/drupal/946
---
$ composer require drush/drush
---
$link = \Drupal\Core\Link::createFromRoute('My link', 'entity.node.canonical', ['node' => 123]);
// По пути
$url = \Drupal\Core\Url::fromUri('base:path/to/target');
$link = \Drupal\Core\Link::fromTextAndUrl('My link', $url);
---
$site_mail = \Drupal::config('system.site')->get('mail');
---
\Drupal::messenger()->addMessage('Hello World!');
---
\Drupal::logger('modulename')->info('Hello World!');
\Drupal::logger('modulename')->error('It\'s error');
---
function modulename_page_attachments(array &$page) {
$page['#attached']['library'][] = 'modulename/libraryname';
}
---
$current_user_uid = \Drupal::currentUser()->id();
$current_user = \Drupal\user\Entity\User::load($current_user_uid);
---
if (\Drupal::currentUser()->isAnonymous()) {
...
}
---
if (\Drupal::currentUser()->hasPermission('administer site configuration')) {
...
}
---
if (in_array('administrator', \Drupal::currentUser()->getRoles())) {
// Current user has role "administrator"
}
---
// $_GET
$nid = \Drupal::request()->query->get('nid');
$all_get_params = \Drupal::request()->query->all();
// $_POST
$nid = \Drupal::request()->request->get('nid');
$all_post_params = \Drupal::request()->request->all();
// $_COOKIE
$nid = \Drupal::request()->cookies->get('nid');
$all_cookie_params = \Drupal::request()->cookies->all();
---
$string = \Drupal\Component\Utility\Html::escape('<b>Hello</b>'); // Переменная будет содержать "&lt;b&gt;Hello&lt;/b&gt;"
---
$string = new \Drupal\Component\Render\FormattableMarkup('My name is: @name', [
'@name' => $name,
]);
---
$string = new \Drupal\Component\Render\FormattableMarkup('My name is: @name', [
'@name' => \Drupal\Core\Render\Markup::create('<b>Dries</b>'),
]);
---
$string = \Drupal::translation()->formatPlural(123, '@count day', '@count days');
---
$truncated_text = \Drupal\Component\Utility\Unicode::truncate($text, 128);
---
use Drupal\Component\Serialization\Json;
$string = Json::encode($array);
$array = Json::decode($string);
---
$default_language = \Drupal::languageManager()->getDefaultLanguage();
$default_langcode = $default_language->getId();
---
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$formatted_date = $date_formatter->format(1558730206, 'short');
---
\Drupal::service('plugin.manager.mail')->mail(
'modulename',
'example_mail_key',
'to@gmail.com',
'en',
['myvar' => 123]
]);
function modulename_mail($key, &$message, $params) {
if ($key == 'example_mail_key') {
$message['subject'] = 'Example email subject';
$message['body'][] = 'Example email body. myvar = ' . $params['myvar'];
}
}
\Drupal::service('plugin.manager.mail')->mail('system', 'example_mail_key', 'example@gmail.com', 'en', [
'context' => [
'subject' => 'Subject',
'message' => \Drupal\Core\Render\Markup::create('Message'),
],
]);
---
$ip = \Drupal::request()->getClientIp();
---
$current_timestamp = \Drupal::time()->getCurrentTime();
---
class ExampleController extends ControllerBase {
public function export() {
$response = new Response();
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="example.txt"');
$response->setContent('Hello World!');
return $response;
}
}
---
// 404
throw new NotFoundHttpException();
// 403
throw new AccessDeniedHttpException();
---
/**
* Implements hook_token_info().
*/
function modulename_token_info() {
$token_info['tokens']['node']['example-token'] = [
'name' => 'Example node token',
];
return $token_info;
}
/**
* Implements hook_tokens().
*/
function modulename_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = [];
if ($type == 'node' && !empty($data['node'])) {
$node = $data['node']; /** @var NodeInterface $node */
foreach ($tokens as $name => $original) {
if ($name == 'example-token') {
$replacements[$original] = 'It\'s example token for node ' . $node->id();
}
}
}
return $replacements;
}
---
$string = \Drupal::token()->replace('Example string with [node:title] token', [
'node' => Node::load(123),
]);
---
class ExampleController extends ControllerBase {
public function exampleAction() {
$meta_description = [
'#tag' => 'meta',
'#attributes' => [
'name' => 'description',
'content' => ['#plain_text' => 'Random text'],
],
];
return [
'#attached' => [
'html_head' => [
[$meta_description, 'description']
],
],
...
];
}
}
---
$comment_count = (int)$entity->get('field_comment')->comment_count;
---
// С помощью статического метода load()
$node = \Drupal\node\Entity\Node::load(123);
$term = \Drupal\taxonomy\Entity\Term::load(234);
// С помощью сервиса entity_type.manager
$node = \Drupal::entityTypeManager()->getStorage('node')->load(123);
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(234);
---
$category_field = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page')['field_category'];
$category_field_storage = $field_definition->getFieldStorageDefinition();
---
if (!$entity->field_example->isEmpty()) {
...
}
---
if ($entity->hasField('field_example')) {
...
}
---
$entity_type = 'node';
$entity_bundle = 'page';
$field_name = 'field_example';
$field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);
if ($field_storage && in_array($entity_bundle, $field_storage->getBundles())) {
...
}
---
$field_example_label = $entity->get('field_example')->getFieldDefinition()->getLabel();
$field_example_label = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page')['field_example']->getLabel();
---
$date_start = $node->field_daterange->start_date;
$date_end = $node->field_daterange->end_date;
$days_between_dates = $date_end->diff($date_start)->format('%a');
---
$node_type = $node->get('type')->entity;
$node_type = NodeType::load($node->bundle());
---
$file = \Drupal\file\Entity\File::load(123);
$file_url = $file->url();
$file_uri = $file->getFileUri();
---
$file_uri = 'public://example.jpg';
if ($files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $file_uri])) {
$file = current($files); /** @var FileInterface $file */
}
---
$node = Node::load(123);
$node->delete();
---
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$nodes = $node_storage->loadMultiple([1, 2, 4]);
$node_storage->delete($nodes);
---
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/example-url-alias');
if (preg_match('/node\/(\d+)/', $path, $matches)) {
$node = \Drupal\node\Entity\Node::load($matches[1]);
}
---
/** @var TermStorageInterface $term_storage */
$term_storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
// Способ 1 - по id термина. Получает только непосредственных детей термина 123.
// Результат не отсортирован.
$childrens = $term_storage->loadChildren(123, 'category');
// Способ 2 - по объекту термина. Получает только непосредственных детей термина $term.
// Результат не отсортирован.
$childrens = $term_storage->getChildren($term);
// Способ 3 - по id термина. Получает всех детей термина 123 независимо от вложенности.
// Результат отсортирован по весу термина.
$childrens = $term_storage->loadTree('category', 123, NULL, TRUE);
---
$node = \Drupal\node\Entity\Node::load(123);
// Render-array поля, прошедшего через field.html.twig
$field_example_build = $node->field_example->view('full');
// Render-array первого значения поля, прошедшего через форматтер
$field_example_build = $node->field_example[0]->view('full');
---
$node = \Drupal\node\Entity\Node::load(123);
$node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$node_build = $node_view_builder->view($node, 'teaser');
---
$variables['my_html_var'] = \Drupal\Core\Render\Markup::create('<b>Hello</b> <i>World</i>');
---
$render_array = [
'#theme' => 'status_messages',
'#message_list' => [
'warning' => ['Warning!'],
],
];
$output = render($render_array);
---
$build = [
'#theme' => 'table',
'#header' => ['ID', 'Title', 'Date'],
'#rows' => [
[1, 'Title 1', '01.01.2019'],
[2, 'Title 2', '02.01.2019'],
[3, 'Title 3', '03.01.2019'],
],
'#empty' => 'Empty...',
];
---
/**
* Implements hook_entity_extra_field_info().
*/
function MODULENAME_entity_extra_field_info() {
$extra_fields['node']['article']['display']['author'] = [
'label' => t('Author name'),
'weight' => 0,
];
return $extra_fields;
}
/**
* Implements hook_ENTITY_TYPE_view(): node.
*/
function MODULENAME_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
if ($display->getComponent('author')) {
$build['author'] = ['#markup' => $node->getOwner()->getDisplayName()];
}
}
---
public function buildForm(array $form, FormStateInterface $form_state) {
...
$form['#method'] = 'get';
$form['#action'] = \Drupal::urlGenerator()->generateFromRoute('example.route');
...
}
---
public function buildForm(array $form, FormStateInterface $form_state) {
...
$form['#cache']['max-age'] = 0;
...
}
---
/**
* @Block(
* id = "my_block_with_form",
* admin_label = @Translation("My block with form"),
* category = @Translation("Forms")
* )
*/
class MyBlockWithForm extends BlockBase {
public function build() {
return [
'form' => \Drupal::formBuilder()->getForm('Drupal\modulename\Form\ExampleForm')
];
}
}
---
$form['example_select'] = [
'#type' => 'select',
'#options' => [
1 => 'Show',
2 => 'Hide',
],
];
$form['dependent_select'] = [
'#type' => 'select',
'#options' => [...],
'#states' => [
'visible' => [
':input[name="example_select"]' => ['value' => 1],
],
],
];
---
$form['#attributes']['novalidate'] = 'novalidate';
---
// Системный адрес. Аналог current_path().
$current_system_path = \Drupal::service('path.current')->getPath();
// Синоним адреса. Аналог request_path().
$current_system_path = \Drupal::service('path.current')->getPath();
$current_path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_system_path);
// Полный путь из строки браузера, с GET параметрами. Аналог request_uri().
$current_request_uri = \Drupal::request()->getRequestUri();
---
$base_path = base_path();
---
if (\Drupal::service('router.admin_context')->isAdminRoute()) {
...
}
---
if (\Drupal::service('path.matcher')->isFrontPage()) {
...
}
---
$current_route_name = \Drupal::routeMatch()->getRouteName();
---
if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
...
}
---
$nid = \Drupal::routeMatch()->getRawParameter('node'); // Integer
$node = \Drupal::routeMatch()->getParameter('node'); // Node object
---
$file_url = file_create_url('public://example.jpg');
---
$destination_array = \Drupal::destination()->getAsArray();
$url = \Drupal::urlGenerator()->generateFromRoute('example.route', [], ['query' => $destination_array]);
---
class ExampleController extends ControllerBase {
public function exampleAction() {
return $this->redirect('<front>');
}
}
---
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/example-url-alias');
---
$node_alias = $node->get('path')->alias; // "/example/node/path"
---
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment