Skip to content

Instantly share code, notes, and snippets.

@l3th2nh
Forked from bdlangton/Blocks.md
Created March 17, 2020 16:24
Show Gist options
  • Select an option

  • Save l3th2nh/2f7cc835ed6f0e9a31cb32feb8cd709f to your computer and use it in GitHub Desktop.

Select an option

Save l3th2nh/2f7cc835ed6f0e9a31cb32feb8cd709f to your computer and use it in GitHub Desktop.

Revisions

  1. @bdlangton bdlangton revised this gist Dec 27, 2019. 1 changed file with 8 additions and 2 deletions.
    10 changes: 8 additions & 2 deletions Views.md
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,17 @@
    ### Load a view, execute, render.
    ### Get render array for view.
    ```
    use Drupal\views\Views;
    $args = [];
    $view = Views::getView('my_view');
    $view->setDisplay('my_display');
    $view->preExecute();
    $view->execute();
    $view->render();
    $render_array = $view->buildRenderable('my_display', $args);
    ```

    Get rendered markup from above:
    ```
    Drupal::service('renderer')->renderRoot($render_array);
    ```

    ### Get various IDs and objects.
  2. @bdlangton bdlangton revised this gist Dec 20, 2019. 2 changed files with 28 additions and 24 deletions.
    24 changes: 0 additions & 24 deletions Misc.md
    Original file line number Diff line number Diff line change
    @@ -19,30 +19,6 @@ $path_args = explode('/', $path);
    $route_name = \Drupal::service('current_route_match')->getRouteName();
    ```

    ### Parameter bag ($_GET and $_POST values).
    ```
    // GET parameter bag.
    $bag = \Drupal::request()->query;
    // POST parameter bag.
    $bag = \Drupal::request()->request;
    // Get all parameters as array.
    $bag->all();
    // Get individual result.
    $bag->get('name');
    // Get count of parameters.
    $bag->count();
    ```


    ### Get the host (ex: www.google.com).
    ```
    $host = \Drupal::request()->getHost();
    ```

    ### Redirect.
    ```
    use Symfony\Component\HttpFoundation\RedirectResponse;
    28 changes: 28 additions & 0 deletions Request.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    ### Get headers.
    ```
    $referer = \Drupal::request()->headers->get('referer');
    ```

    ### Parameter bag ($_GET and $_POST values).
    ```
    // GET parameter bag.
    $bag = \Drupal::request()->query;
    // POST parameter bag.
    $bag = \Drupal::request()->request;
    // Get all parameters as array.
    $bag->all();
    // Get individual result.
    $bag->get('name');
    // Get count of parameters.
    $bag->count();
    ```


    ### Get the host (ex: www.google.com).
    ```
    $host = \Drupal::request()->getHost();
    ```
  3. @bdlangton bdlangton revised this gist Dec 19, 2019. 1 changed file with 15 additions and 6 deletions.
    21 changes: 15 additions & 6 deletions Misc.md
    Original file line number Diff line number Diff line change
    @@ -19,16 +19,25 @@ $path_args = explode('/', $path);
    $route_name = \Drupal::service('current_route_match')->getRouteName();
    ```

    ### Get the query parameter from a GET request.
    ```
    $name = \Drupal::request()->query->get('name');
    ### Parameter bag ($_GET and $_POST values).
    ```
    // GET parameter bag.
    $bag = \Drupal::request()->query;
    ### Get the parameter from a POST request.
    ```
    $name = \Drupal::request()->request->get('name');
    // POST parameter bag.
    $bag = \Drupal::request()->request;
    // Get all parameters as array.
    $bag->all();
    // Get individual result.
    $bag->get('name');
    // Get count of parameters.
    $bag->count();
    ```


    ### Get the host (ex: www.google.com).
    ```
    $host = \Drupal::request()->getHost();
  4. @bdlangton bdlangton revised this gist Dec 11, 2019. 1 changed file with 11 additions and 0 deletions.
    11 changes: 11 additions & 0 deletions Debugging.md
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,17 @@ ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    ```

    ### Display error messages to the screen
    Set this in settings.local.php so that it displays locally, but not on prod. The default Logging and errors should be 'None'.

    ```
    // none - display none
    // some - errors and warning
    // all - all messages
    // verbose - all messages with backtrace information
    $config['system.logging']['error_level'] = 'all';
    ```

    ### Set kint debug max level.
    If kint is taking forever to load or crashing the page, try reducing the max level.
    ```
  5. @bdlangton bdlangton revised this gist Dec 6, 2019. 1 changed file with 33 additions and 3 deletions.
    36 changes: 33 additions & 3 deletions Fields.md
    Original file line number Diff line number Diff line change
    @@ -1,14 +1,44 @@
    Whether a multifield or single field, you can use `->first()`, but if you leave it off, it'll automatically get the first value.
    ### Basics

    $node->field_example will return a `FieldItemList` object (or another class that extends `FieldItemList`

    If you want to drill down to values under the field, you can add `->first()` or leave it off and it'll automatically use the first item. This is true if the field is a single item or multi-values. Example: `$node->field_example->target_id` or `$node->field_example->first()->target_id`.

    If the field is an entity reference, you can get the full entity: `$node->field_example->entity` (this gets the first entity if it's a multi-value).

    On multi-value fields to get something other than the first you can use the array index: `$node->field_example[1]`.

    ### Entity reference
    ```
    $node->field_ref->target_id; // Entity ID.
    $node->field_ref->entity; // Full entity.
    // Both of these return the same Entity ID value.
    $node->field_ref->target_id;
    $node->field_ref->first()->target_id;
    // Get the full entity. "->entity" is only valid when the field is an entity reference.
    $node->field_ref->entity;
    // Get the value as an array: ['target_id' => '1'].
    $node->field_ref->getValue();
    // Will return null.
    $node->field_ref->value;
    ```

    ### URL
    ```
    $node->field_url->uri;
    $node->field_url->title;
    $node->field_url->options; // Array of options.
    $node->field_url->entity; // Returns null because it isn't an entity.
    $node->field_url->getValue(); // Returns ['uri' => '', 'title' => '', 'options => []]
    $node->field_url->value; // Returns null.
    ```

    ### Text values
    ```
    // Get the value as a string.
    $node->field_text->value;
    // Get the value as an array: ['value' => 'text'].
    $node->field_text->getValue();
    ```
  6. @bdlangton bdlangton revised this gist Nov 18, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion URLs and Links.md
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@
    ### URL from route.
    ```
    use Drupal\Core\Url;
    $url = Url::fromRoute($route_name, $params);
    $url = Url::fromRoute($route_name, $params, $options);
    ```

    ### URL from URI.
  7. @bdlangton bdlangton revised this gist Nov 14, 2019. 1 changed file with 16 additions and 0 deletions.
    16 changes: 16 additions & 0 deletions Libraries.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,14 @@
    ## Example Library
    In a module.libraries.yml file.
    ```
    dashboard:
    js:
    js/dashboard.js: {}
    dependencies:
    - core/drupal
    - core/jquery
    ```

    ## Adding Libraries
    ### In preprocess function or controller function.
    ```
    @@ -9,6 +20,11 @@ $variables['#attached']['library'][] = 'lotus/lotus-js';
    {{ attach_library('hcpl_zen/title-record') }}
    ```

    ### In a view (pre render hook).
    ```
    $view->element['#attached']['library'][] = 'custom/custom_view';
    ```

    ## Miscellaneous
    ### Overriding libraries
    ```
  8. @bdlangton bdlangton revised this gist Nov 8, 2019. 1 changed file with 25 additions and 0 deletions.
    25 changes: 25 additions & 0 deletions Routes.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    https://www.drupal.org/docs/8/api/routing-system

    ### Example route
    ```
    example.name:
    path: '/example/{name}'
    defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
    name: 'My name'
    requirements:
    _permission: 'access content'
    ```

    ### Using roles instead of permissions
    Using a `,` among multiple roles means the user has to have all roles. Using a `+` means they need to have one.
    ```
    requirements:
    _role: admin,accountant
    ```

    ### Allowing all access
    ```
    requirements:
    _access: TRUE
    ```
  9. @bdlangton bdlangton revised this gist Nov 7, 2019. 1 changed file with 10 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions Debugging.md
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,16 @@ ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    ```

    ### Set kint debug max level.
    If kint is taking forever to load or crashing the page, try reducing the max level.
    ```
    // Change kint maxLevels setting.
    include_once(DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php');
    if(class_exists('Kint')){
    Kint::$maxLevels = 5;
    }
    ```

    ### Services.yml debugging.
    You will need to copy `sites/example.settings.local.php` to `sites/default/settings.local.php` (and ensure settings.php includes settings.local.php) or put this in your settings.php file: `$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';`.

  10. @bdlangton bdlangton revised this gist Nov 5, 2019. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions DB Stuff.md
    Original file line number Diff line number Diff line change
    @@ -10,6 +10,13 @@ $results = \Drupal::database()->query('select * from purge_queue')->fetchAll();
    $entity_query->addTag('debug')->execute();
    ```

    ### BETWEEN checks on entityQuery.
    ```
    $result = \Drupal::entityQuery('node')
    ->condition('field_number', [1, 3], 'BETWEEN')
    ->execute();
    ```

    ### IS NULL (and IS NOT NULL) checks on entityQuery.
    ```
    $result = \Drupal::entityQuery('node')
  11. @bdlangton bdlangton revised this gist Oct 24, 2019. 1 changed file with 11 additions and 1 deletion.
    12 changes: 11 additions & 1 deletion Views.md
    Original file line number Diff line number Diff line change
    @@ -8,7 +8,17 @@ $view->execute();
    $view->render();
    ```

    ### Get query object (only after executing the view).
    ### Get various IDs and objects.
    ```
    // Get query object (only after executing the view).
    $query = $view->query;
    // Get view ID.
    $view->id();
    // Get current display.
    $view->current_display();
    // Get results (after execution).
    $view->result;
    ```
  12. @bdlangton bdlangton revised this gist Oct 3, 2019. 1 changed file with 4 additions and 2 deletions.
    6 changes: 4 additions & 2 deletions Debugging.md
    Original file line number Diff line number Diff line change
    @@ -6,8 +6,10 @@ ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    ```

    ### Twig debugging.
    In development.services.yml. You will also need to copy `sites/example.settings.local.php` to `sites/default/settings.local.php` or put this in your settings.php file: `$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';`.
    ### Services.yml debugging.
    You will need to copy `sites/example.settings.local.php` to `sites/default/settings.local.php` (and ensure settings.php includes settings.local.php) or put this in your settings.php file: `$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';`.

    Update `/sites/development.services.yml`:
    ```
    parameters:
    http.respone.debug_cacheability_headers: true
  13. @bdlangton bdlangton revised this gist Oct 3, 2019. 1 changed file with 11 additions and 0 deletions.
    11 changes: 11 additions & 0 deletions Debugging.md
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,17 @@ ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    ```

    ### Twig debugging.
    In development.services.yml. You will also need to copy `sites/example.settings.local.php` to `sites/default/settings.local.php` or put this in your settings.php file: `$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';`.
    ```
    parameters:
    http.respone.debug_cacheability_headers: true
    twig.config:
    debug: true
    auto_reload: true
    cache: false
    ```

    ### Pretty print arrays/objects printed to watchdog.
    ```
    \Drupal::logger('my_module')->debug(kpr($var, TRUE));
  14. @bdlangton bdlangton revised this gist Sep 24, 2019. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions Debugging.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,11 @@
    ## Debugging
    ### Display all errrors.
    ```
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    ```

    ### Pretty print arrays/objects printed to watchdog.
    ```
    \Drupal::logger('my_module')->debug(kpr($var, TRUE));
  15. @bdlangton bdlangton revised this gist Sep 20, 2019. 2 changed files with 15 additions and 0 deletions.
    1 change: 1 addition & 0 deletions Entities.md
    Original file line number Diff line number Diff line change
    @@ -36,3 +36,4 @@ Code | Field not empty | Field empty | Not a field
    :--- | :--- | :--- | :---
    !empty($node->field_entity_ref) | TRUE | TRUE | FALSE
    !empty($node->field_entity_ref->first()) | TRUE | FALSE | PHP Error
    !empty($node->field_entity_ref->first()->entity) | TRUE | FALSE | PHP Error
    14 changes: 14 additions & 0 deletions Fields.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    Whether a multifield or single field, you can use `->first()`, but if you leave it off, it'll automatically get the first value.

    ### Entity reference
    ```
    $node->field_ref->target_id; // Entity ID.
    $node->field_ref->entity; // Full entity.
    ```

    ### URL
    ```
    $node->field_url->uri;
    $node->field_url->title;
    $node->field_url->options; // Array of options.
    ```
  16. @bdlangton bdlangton revised this gist Sep 20, 2019. 1 changed file with 7 additions and 1 deletion.
    8 changes: 7 additions & 1 deletion Entities.md
    Original file line number Diff line number Diff line change
    @@ -29,4 +29,10 @@ $new_field = BaseFieldDefinition::create('string')
    ### Apply all updates to entities.
    ```
    \Drupal::entityDefinitionUpdateManager()->applyUpdates();
    ```
    ```

    ### Checking for existence of fields on entities
    Code | Field not empty | Field empty | Not a field
    :--- | :--- | :--- | :---
    !empty($node->field_entity_ref) | TRUE | TRUE | FALSE
    !empty($node->field_entity_ref->first()) | TRUE | FALSE | PHP Error
  17. @bdlangton bdlangton revised this gist Sep 19, 2019. 2 changed files with 24 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions Blocks.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    ### Render custom blocks
    ```
    $bid = 'myblock';
    $block = \Drupal\block_content\Entity\BlockContent::load($bid);
    $render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    ```

    ### Render plugin blocks
    ```
    $block_manager = \Drupal::service('plugin.manager.block');
    $config = [];
    $plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
    $access_result = $plugin_block->access(\Drupal::currentUser());
    if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
    return [];
    }
    $render = $plugin_block->build();
    ```
    6 changes: 6 additions & 0 deletions Rendering.md
    Original file line number Diff line number Diff line change
    @@ -23,4 +23,10 @@ $view = $view_builder->viewField($node->get('body'), [
    'settings' => ['link' => FALSE],
    ]);
    $output = render($view);
    ```

    ### Rendering something outside of a Drupal bootstrap (ex: testing)
    When you can't use `render()` then you need to do this:
    ```
    \Drupal::service('renderer')->renderRoot($render_array);
    ```
  18. @bdlangton bdlangton revised this gist Sep 18, 2019. 2 changed files with 19 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions Debugging.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,9 @@
    ## Debugging
    ### Pretty print arrays/objects printed to watchdog.
    ```
    \Drupal::logger('my_module')->debug(kpr($var, TRUE));
    ```

    ### Debug backtrace any error.
    ```
    // This function exists in core/includes/bootstrap.inc.
    14 changes: 14 additions & 0 deletions Views.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    ### Load a view, execute, render.
    ```
    use Drupal\views\Views;
    $view = Views::getView('my_view');
    $view->setDisplay('my_display');
    $view->preExecute();
    $view->execute();
    $view->render();
    ```

    ### Get query object (only after executing the view).
    ```
    $query = $view->query;
    ```
  19. @bdlangton bdlangton revised this gist Aug 16, 2019. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions Files.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    ### Load a file
    ```
    $file = \Drupal\file\Entity\File::load(1007);
    OR
    $file = \Drupal::entityTypeManager()->getStorage('file')->load(1007);
    ```

    ### Working with file entities
    ```
    // Get the URI (including wrapper, such as public://).
    $uri = $file->getFileUri();
    // Get the full URL path.
    $url = file_create_url($file->getFileUri());
    // Get relative path of the URL (w/o domain).
    $path = file_url_transform_relative($url);
    ```
  20. @bdlangton bdlangton revised this gist Aug 9, 2019. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions DB Stuff.md
    Original file line number Diff line number Diff line change
    @@ -10,6 +10,13 @@ $results = \Drupal::database()->query('select * from purge_queue')->fetchAll();
    $entity_query->addTag('debug')->execute();
    ```

    ### IS NULL (and IS NOT NULL) checks on entityQuery.
    ```
    $result = \Drupal::entityQuery('node')
    ->condition('field_banner_code', NULL, 'IS NULL')
    ->execute();
    ```

    ### Delete all 'event' nodes.
    ```
    $result = \Drupal::entityQuery('node')
  21. @bdlangton bdlangton revised this gist Aug 2, 2019. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions Config and State.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    ## Config

    ### Get a config.
    ```
    \Drupal::service('config.factory')->getEditable('system.performance');
    ```

    ### Update a config value.
    ```
    \Drupal::service('config.factory')->getEditable('system.performance')->set('cache.page.enabled', 1)->save();
    ```

    ## State

    ### Update a state value.
    ```
    \Drupal::service('state')->set('du_admission_steps.importer.last_run', NULL);
    ```
  22. @bdlangton bdlangton revised this gist Jul 2, 2019. 1 changed file with 5 additions and 1 deletion.
    6 changes: 5 additions & 1 deletion Drupal 8 Tips.md
    Original file line number Diff line number Diff line change
    @@ -6,4 +6,8 @@ https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-ad

    ### Adding Custom Variable to Drupal.settings

    https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/
    https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/

    ### Service Decorators

    https://www.axelerant.com/resources/team-blog/drupal-8-service-decorators
  23. @bdlangton bdlangton revised this gist Apr 25, 2019. 2 changed files with 18 additions and 10 deletions.
    10 changes: 0 additions & 10 deletions Adding Libraries.md
    Original file line number Diff line number Diff line change
    @@ -1,10 +0,0 @@
    ## Adding Libraries
    ### In preprocess function or controller function.
    ```
    $variables['#attached']['library'][] = 'lotus/lotus-js';
    ```

    ### In twig template file.
    ```
    {{ attach_library('hcpl_zen/title-record') }}
    ```
    18 changes: 18 additions & 0 deletions Libraries.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    ## Adding Libraries
    ### In preprocess function or controller function.
    ```
    $variables['#attached']['library'][] = 'lotus/lotus-js';
    ```

    ### In twig template file.
    ```
    {{ attach_library('hcpl_zen/title-record') }}
    ```

    ## Miscellaneous
    ### Overriding libraries
    ```
    // Libraries is an array of the library data.
    // Extension is 'core' or the module/theme that defined the libraries.
    function hook_library_info_alter(&$libraries, $extension)
    ```
  24. @bdlangton bdlangton revised this gist Apr 24, 2019. 5 changed files with 56 additions and 23 deletions.
    5 changes: 0 additions & 5 deletions Adding Libraries
    Original file line number Diff line number Diff line change
    @@ -1,5 +0,0 @@
    // In preprocess function or controller function.
    $variables['#attached']['library'][] = 'lotus/lotus-js';

    // In twig template file.
    {{ attach_library('hcpl_zen/title-record') }}
    10 changes: 10 additions & 0 deletions Adding Libraries.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    ## Adding Libraries
    ### In preprocess function or controller function.
    ```
    $variables['#attached']['library'][] = 'lotus/lotus-js';
    ```

    ### In twig template file.
    ```
    {{ attach_library('hcpl_zen/title-record') }}
    ```
    15 changes: 11 additions & 4 deletions Debugging.txt → Debugging.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,6 @@
    // Debug backtrace any error.
    ## Debugging
    ### Debug backtrace any error.
    ```
    // This function exists in core/includes/bootstrap.inc.
    // Just need to add lines 6-8 to it.
    function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
    @@ -8,13 +10,18 @@ function _drupal_error_handler($error_level, $message, $filename, $line, $contex
    ksm($message, $d);
    _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
    }
    ```

    // Debugging search API solr queries:
    ### Debugging search API solr queries:
    ```
    // You can output the Request object using kint/kpm, but it can be hard
    // to figure out where to set the debugging code. The best place is in
    // the executeRequest function in the following file:
    // search_api_solr/src/SolrConnector/SolrConnectorPluginBase.php
    ```

    // Starting point for debugging ElasticSearch stuff, in the file
    ### Starting point for debugging ElasticSearch stuff, in the file
    ```
    // src/ElasticSearch/Parameters/Builder/SearchBuilder.php:
    // Add ksm at the end of build() and getSearchQueryOptions()
    // Add ksm at the end of build() and getSearchQueryOptions()
    ```
    39 changes: 29 additions & 10 deletions Misc.php → Misc.md
    Original file line number Diff line number Diff line change
    @@ -1,30 +1,49 @@
    // Get the node from the current path.
    ## Miscellaneous
    ### Get the node from the current path.
    ```
    $node = \Drupal::routeMatch()->getParameter('node');
    ```

    // Get current path.
    ### Get current path.
    ```
    $path = \Drupal::service('path.current')->getPath();
    ```

    // Get path arguments (from path above).
    ### Get path arguments (from path above).
    ```
    $path_args = explode('/', $path);
    ```

    // Get the current route.
    ### Get the current route.
    ```
    $route_name = \Drupal::service('current_route_match')->getRouteName();
    ```

    // Get the query parameter from a GET request.
    ### Get the query parameter from a GET request.
    ```
    $name = \Drupal::request()->query->get('name');
    ```

    // Get the parameter from a POST request.
    ### Get the parameter from a POST request.
    ```
    $name = \Drupal::request()->request->get('name');
    ```

    // Get the host (ex: www.google.com).
    ### Get the host (ex: www.google.com).
    ```
    $host = \Drupal::request()->getHost();
    ```

    // Redirect.
    ### Redirect.
    ```
    use Symfony\Component\HttpFoundation\RedirectResponse;
    new RedirectResponse(\Drupal::url($route_name));
    ```

    // Add t() to classes (services, controllers, etc)
    ### Add t() to classes (services, controllers, etc)
    ```
    use Drupal\Core\StringTranslation\StringTranslationTrait;
    class MyClass {
    use StringTranslationTrait;
    }
    }
    ```
    10 changes: 6 additions & 4 deletions Search.php → Search.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,7 @@
    # Trigger select entities to be re-indexed through the Search API.
    # This is for Title Record entities, but any entity will do.

    ## Search
    ### Trigger select entities to be re-indexed through the Search API.
    ```
    // This is for Title Record entities, but any entity will do.
    use Drupal\search_api\Plugin\search_api\datasource\ContentEntity;
    use Drupal\omega_hub\Entity\TitleRecord;
    $entity_ids = [507863, 509240, 513703, 515100, 536124, 537058, 541569];
    @@ -12,4 +13,5 @@
    $indexes = ContentEntity::getIndexesForEntity($entity);
    foreach ($indexes as $index) {
    $index->trackItemsUpdated('entity:title_record', $update_ids);
    }
    }
    ```
  25. @bdlangton bdlangton revised this gist Apr 24, 2019. 4 changed files with 24 additions and 8 deletions.
    8 changes: 6 additions & 2 deletions DB Stuff.md
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,14 @@
    ## DB Stuff

    ### Simple database query.
    ```$results = \Drupal::database()->query('select * from purge_queue')->fetchAll();```
    ```
    $results = \Drupal::database()->query('select * from purge_queue')->fetchAll();
    ```

    ### Debugging an entity query, enable the devel module and add tag before execute.
    ```$entity_query->addTag('debug')->execute();```
    ```
    $entity_query->addTag('debug')->execute();
    ```

    ### Delete all 'event' nodes.
    ```
    8 changes: 6 additions & 2 deletions Entities.md
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,9 @@ $search_api_index = \Drupal::entityTypeManager()->getStorage('search_api')->load
    ```

    ### Load multiple entities (if no param is passed, all entities are loaded).
    ```$node = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);```
    ```
    $node = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);
    ```

    ### Delete multiple entities.
    ```
    @@ -25,4 +27,6 @@ $new_field = BaseFieldDefinition::create('string')
    ```

    ### Apply all updates to entities.
    ```\Drupal::entityDefinitionUpdateManager()->applyUpdates();```
    ```
    \Drupal::entityDefinitionUpdateManager()->applyUpdates();
    ```
    4 changes: 3 additions & 1 deletion URLs and Links.md
    Original file line number Diff line number Diff line change
    @@ -32,7 +32,9 @@ $renderable_link = Link::fromTextAndUrl($text, Url $url);
    ```

    ### Create a link from route (skip having to use Url class).
    ```Link::createFromRoute($text, $route_name, ['arg1' => 'value'], ['attributes' => ['class' => 'use-ajax']]);```
    ```
    Link::createFromRoute($text, $route_name, ['arg1' => 'value'], ['attributes' => ['class' => 'use-ajax']]);
    ```

    ### Convert above link to render array or link string.
    ```
    12 changes: 9 additions & 3 deletions Users.md
    Original file line number Diff line number Diff line change
    @@ -1,9 +1,15 @@
    ## Users
    ### Load a user.
    ```$node = \Drupal::entityTypeManager()->getStorage('user')->load(23);```
    ```
    $node = \Drupal::entityTypeManager()->getStorage('user')->load(23);
    ```

    ### Get current user.
    ```$account = \Drupal::currentUser();```
    ```
    $account = \Drupal::currentUser();
    ```

    ### Get current user ID.
    ```$account = \Drupal::currentUser()->id();```
    ```
    $account = \Drupal::currentUser()->id();
    ```
  26. @bdlangton bdlangton revised this gist Apr 24, 2019. 12 changed files with 97 additions and 69 deletions.
    12 changes: 8 additions & 4 deletions DB Stuff.md
    Original file line number Diff line number Diff line change
    @@ -7,29 +7,33 @@
    ```$entity_query->addTag('debug')->execute();```

    ### Delete all 'event' nodes.
    ```$result = \Drupal::entityQuery('node')
    ```
    $result = \Drupal::entityQuery('node')
    ->condition('type', 'event')
    ->execute();
    entity_delete_multiple('node', $result);
    // Add ->range(0, 10) to delete a range
    ```

    ### Insert statement.
    ```$query = \Drupal::database()->insert('purge_queue');
    ```
    $query = \Drupal::database()->insert('purge_queue');
    $query->fields(['data', 'created']);
    $query->values(['a:4:{i:0;s:3:"url";i:1;a:4:{s:10:"66849f6f11";i:3;s:10:"c990b129a0";i:3;s:10:"c618828456";i:3;s:10:"453d844ea2";i:3;}i:2;s:66:"http://www.example.com";i:3;a:0:{}}', time()]);
    $query->execute();
    ```

    ### Update statement.
    ```$query = \Drupal::database()->update('mcpl_events_feeds_item');
    ```
    $query = \Drupal::database()->update('mcpl_events_feeds_item');
    $query->fields(['hash' => 'update']);
    $query->condition('nid', 1);
    $query->execute();
    ```

    ### Delete statement.
    ```$query = \Drupal::database()->delete('purge_queue');
    ```
    $query = \Drupal::database()->delete('purge_queue');
    $query->condition('data', '%url%', 'LIKE');
    $query->execute();
    ```
    9 changes: 6 additions & 3 deletions Entities.md
    Original file line number Diff line number Diff line change
    @@ -1,21 +1,24 @@
    ## Entities
    ### Load an entity. Can be a config entity also.
    ```$node = \Drupal::entityTypeManager()->getStorage('node')->load(23);
    ```
    $node = \Drupal::entityTypeManager()->getStorage('node')->load(23);
    $search_api_index = \Drupal::entityTypeManager()->getStorage('search_api')->load('title_records');
    ```

    ### Load multiple entities (if no param is passed, all entities are loaded).
    ```$node = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);```

    ### Delete multiple entities.
    ```$result = \Drupal::entityQuery('taxonomy_term')
    ```
    $result = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'libraries')
    ->execute();
    entity_delete_multiple('taxonomy_term', $result);
    ```

    ### Adding a new field to a custom entity.
    ```$new_field = BaseFieldDefinition::create('string')
    ```
    $new_field = BaseFieldDefinition::create('string')
    ->setLabel(new TranslatableMarkup('New Field'))
    ->setDescription(new TranslatableMarkup('New field description.'));
    \Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('<field_name>', '<entity_type_id>', '<provider>', $new_field);
    9 changes: 6 additions & 3 deletions Images.md
    Original file line number Diff line number Diff line change
    @@ -1,18 +1,21 @@
    ## Images
    ### Render array for an image style.
    ```$render = [
    ```
    $render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => 'public://my-image.png',
    ];
    ```

    ### Image style, get URL (full URL including http://).
    ```$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
    ```
    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
    $image_url = $style->buildUrl('public://du_content_gallery-article.jpg');
    ```

    ### Image style, get URI (public://path-to-image-style).
    ```$style = ImageStyle::load('thumbnail');
    ```
    $style = ImageStyle::load('thumbnail');
    $image_url = $style->buildUri('public://du_content_gallery-article.jpg');
    ```
    17 changes: 13 additions & 4 deletions Migrations.php → Migrations.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,6 @@
    // Run an update migration.
    ## Migrations
    ### Run an update migration.
    ```
    // Remove the prepareUpdate() section if you just want a normal import.
    // To rollback just change 'import' to 'rollback'.
    $migration = \Drupal::service('plugin.manager.migration')->createInstance('machine_name');
    @@ -10,16 +12,22 @@
    // limit to limit the number of migrations to perform, and idlist to only migrate certain source
    // IDs.
    // Example: ['limit' => 10, 'idlist' => '1,2,3']
    ```

    // Interrupt a migration (stop it).
    ### Interrupt a migration (stop it).
    ```
    $migration = \Drupal::service('plugin.manager.migration')->createInstance('machine_name');
    $migration->interruptMigration(\Drupal\migrate\Plugin\MigrationInterface::RESULT_STOPPED);
    ```

    // Set a migration status to Idle.
    ### Set a migration status to Idle.
    ```
    $migration = \Drupal::service('plugin.manager.migration')->createInstance('machine_name');
    $migration->setStatus(\Drupal\migrate\Plugin\MigrationInterface::STATUS_IDLE);
    ```

    // Run a migration on page load (w/?start-migration appended) for xdebug walkthrough.
    ### Run a migration on page load (w/?start-migration appended) for xdebug walkthrough.
    ```
    use Drupal\migrate\MigrateExecutable;
    use Drupal\migrate\MigrateMessage;
    @@ -36,3 +44,4 @@ function example_module_preprocess_page(&$vars) {
    }
    }
    }
    ```
    6 changes: 6 additions & 0 deletions Modules.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    ## Modules
    ### Installing and uninstalling modules.
    ```
    \Drupal::service('module_installer')->install(['media']);
    \Drupal::service('module_installer')->uninstall(['media']);
    ```
    3 changes: 0 additions & 3 deletions Modules.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +0,0 @@
    // Installing and uninstalling modules.
    \Drupal::service('module_installer')->install(['media']);
    \Drupal::service('module_installer')->uninstall(['media']);
    14 changes: 0 additions & 14 deletions Purge Queue.php
    Original file line number Diff line number Diff line change
    @@ -1,14 +0,0 @@
    // Add URL to purge queue.

    // Get the purge services.
    $purgeInvalidationFactory = \Drupal::service('purge.invalidation.factory');
    $purgeQueuers = \Drupal::service('purge.queuers');
    $purgeQueue = \Drupal::service('purge.queue');

    // Get the urlpath queuer and add the full URL to invalidate.
    $queuer = $purgeQueuers->get('urlpath');
    $invalidations = [
    $purgeInvalidationFactory->get('url', '<url>'),
    ];
    $purgeQueue->add($queuer, $invalidations);

    11 changes: 8 additions & 3 deletions Rendering.php → Rendering.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,6 @@
    // Render an entity.
    ## Rendering
    ### Render an entity.
    ```
    $nid = 1;
    $entity_type = 'node';
    $view_mode = 'teaser';
    @@ -7,8 +9,10 @@
    $node = $storage->load($nid);
    $build = $view_builder->view($node, $view_mode);
    $output = render($build);
    ```

    // Render a field.
    ### Render a field.
    ```
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $storage = \Drupal::entityTypeManager()->getStorage('node');
    $nid = 1;
    @@ -18,4 +22,5 @@
    'label' => 'hidden',
    'settings' => ['link' => FALSE],
    ]);
    $output = render($view);
    $output = render($view);
    ```
    41 changes: 41 additions & 0 deletions URLs and Links.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    ## URLS
    ### URL from route.
    ```
    use Drupal\Core\Url;
    $url = Url::fromRoute($route_name, $params);
    ```

    ### URL from URI.
    ```
    use Drupal\Core\Url;
    $url = Url::fromUri('internal:/mypath/to/style.css');
    ```

    ### Add options to an existing URL (classes, target, etc).
    ```
    $url->setOptions([
    'attributes' => [
    'target' => '_blank',
    ],
    ]);
    ```

    ## Links
    ### Generate a link.
    ```
    $my_link = \Drupal::service('link_generator')->generate($text, Url $url);
    ```
    OR
    ```
    use Drupal\Core\Link;
    $renderable_link = Link::fromTextAndUrl($text, Url $url);
    ```

    ### Create a link from route (skip having to use Url class).
    ```Link::createFromRoute($text, $route_name, ['arg1' => 'value'], ['attributes' => ['class' => 'use-ajax']]);```

    ### Convert above link to render array or link string.
    ```
    $link_render_array = $renderable_link->toRenderable();
    $link_string = $renderable_link->toString();
    ```
    27 changes: 0 additions & 27 deletions URLs and Links.php
    Original file line number Diff line number Diff line change
    @@ -1,27 +0,0 @@
    // URL from route.
    use Drupal\Core\Url;
    $url = Url::fromRoute($route_name, $params);

    // URL from URI.
    use Drupal\Core\Url;
    $url = Url::fromUri('internal:/mypath/to/style.css');

    // Add options to an existing URL (classes, target, etc).
    $url->setOptions([
    'attributes' => [
    'target' => '_blank',
    ],
    ]);

    // Generate a link.
    $my_link = \Drupal::service('link_generator')->generate($text, Url $url);
    OR
    use Drupal\Core\Link;
    $renderable_link = Link::fromTextAndUrl($text, Url $url);

    // Create a link from route (skip having to use Url class).
    Link::createFromRoute($text, $route_name, ['arg1' => 'value'], ['attributes' => ['class' => 'use-ajax']]);

    // Convert above link to render array or link string.
    $link_render_array = $renderable_link->toRenderable();
    $link_string = $renderable_link->toString();
    8 changes: 0 additions & 8 deletions User.php
    Original file line number Diff line number Diff line change
    @@ -1,8 +0,0 @@
    // Load a user.
    $node = \Drupal::entityTypeManager()->getStorage('user')->load(23);

    // Get current user.
    $account = \Drupal::currentUser();

    // Get current user ID.
    $account = \Drupal::currentUser()->id();
    9 changes: 9 additions & 0 deletions Users.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    ## Users
    ### Load a user.
    ```$node = \Drupal::entityTypeManager()->getStorage('user')->load(23);```

    ### Get current user.
    ```$account = \Drupal::currentUser();```

    ### Get current user ID.
    ```$account = \Drupal::currentUser()->id();```
  27. @bdlangton bdlangton revised this gist Apr 24, 2019. 6 changed files with 59 additions and 45 deletions.
    20 changes: 12 additions & 8 deletions DB Stuff.md
    Original file line number Diff line number Diff line change
    @@ -6,26 +6,30 @@
    ### Debugging an entity query, enable the devel module and add tag before execute.
    ```$entity_query->addTag('debug')->execute();```

    // Delete all 'event' nodes.
    $result = \Drupal::entityQuery('node')
    ### Delete all 'event' nodes.
    ```$result = \Drupal::entityQuery('node')
    ->condition('type', 'event')
    ->execute();
    entity_delete_multiple('node', $result);
    // Add ->range(0, 10) to delete a range
    ```

    // Insert statement.
    $query = \Drupal::database()->insert('purge_queue');
    ### Insert statement.
    ```$query = \Drupal::database()->insert('purge_queue');
    $query->fields(['data', 'created']);
    $query->values(['a:4:{i:0;s:3:"url";i:1;a:4:{s:10:"66849f6f11";i:3;s:10:"c990b129a0";i:3;s:10:"c618828456";i:3;s:10:"453d844ea2";i:3;}i:2;s:66:"http://www.example.com";i:3;a:0:{}}', time()]);
    $query->execute();
    ```

    // Update statement.
    $query = \Drupal::database()->update('mcpl_events_feeds_item');
    ### Update statement.
    ```$query = \Drupal::database()->update('mcpl_events_feeds_item');
    $query->fields(['hash' => 'update']);
    $query->condition('nid', 1);
    $query->execute();
    ```

    // Delete statement.
    $query = \Drupal::database()->delete('purge_queue');
    ### Delete statement.
    ```$query = \Drupal::database()->delete('purge_queue');
    $query->condition('data', '%url%', 'LIKE');
    $query->execute();
    ```
    6 changes: 4 additions & 2 deletions Drupal 8 Tips.md
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,9 @@
    ## Alter existing routes
    ## Drupal 8 Tips

    ### Alter existing routes

    https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

    ## Adding Custom Variable to Drupal.settings
    ### Adding Custom Variable to Drupal.settings

    https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/
    25 changes: 25 additions & 0 deletions Entities.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    ## Entities
    ### Load an entity. Can be a config entity also.
    ```$node = \Drupal::entityTypeManager()->getStorage('node')->load(23);
    $search_api_index = \Drupal::entityTypeManager()->getStorage('search_api')->load('title_records');
    ```

    ### Load multiple entities (if no param is passed, all entities are loaded).
    ```$node = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);```

    ### Delete multiple entities.
    ```$result = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'libraries')
    ->execute();
    entity_delete_multiple('taxonomy_term', $result);
    ```

    ### Adding a new field to a custom entity.
    ```$new_field = BaseFieldDefinition::create('string')
    ->setLabel(new TranslatableMarkup('New Field'))
    ->setDescription(new TranslatableMarkup('New field description.'));
    \Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('<field_name>', '<entity_type_id>', '<provider>', $new_field);
    ```

    ### Apply all updates to entities.
    ```\Drupal::entityDefinitionUpdateManager()->applyUpdates();```
    21 changes: 0 additions & 21 deletions Entities.php
    Original file line number Diff line number Diff line change
    @@ -1,21 +0,0 @@
    // Load an entity. Can be a config entity also.
    $node = \Drupal::entityTypeManager()->getStorage('node')->load(23);
    $search_api_index = \Drupal::entityTypeManager()->getStorage('search_api')->load('title_records');

    // Load multiple entities (if no param is passed, all entities are loaded).
    $node = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);

    // Delete multiple entities.
    $result = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'libraries')
    ->execute();
    entity_delete_multiple('taxonomy_term', $result);

    // Adding a new field to a custom entity.
    $new_field = BaseFieldDefinition::create('string')
    ->setLabel(new TranslatableMarkup('New Field'))
    ->setDescription(new TranslatableMarkup('New field description.'));
    \Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('<field_name>', '<entity_type_id>', '<provider>', $new_field);

    // Apply all updates to entities.
    \Drupal::entityDefinitionUpdateManager()->applyUpdates();
    18 changes: 18 additions & 0 deletions Images.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    ## Images
    ### Render array for an image style.
    ```$render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => 'public://my-image.png',
    ];
    ```

    ### Image style, get URL (full URL including http://).
    ```$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
    $image_url = $style->buildUrl('public://du_content_gallery-article.jpg');
    ```

    ### Image style, get URI (public://path-to-image-style).
    ```$style = ImageStyle::load('thumbnail');
    $image_url = $style->buildUri('public://du_content_gallery-article.jpg');
    ```
    14 changes: 0 additions & 14 deletions Images.php
    Original file line number Diff line number Diff line change
    @@ -1,14 +0,0 @@
    // Render array for an image style.
    $render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => 'public://my-image.png',
    ];

    // Image style, get URL (full URL including http://).
    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
    $image_url = $style->buildUrl('public://du_content_gallery-article.jpg');

    // Image style, get URI (public://path-to-image-style).
    $style = ImageStyle::load('thumbnail');
    $image_url = $style->buildUri('public://du_content_gallery-article.jpg');
  28. @bdlangton bdlangton renamed this gist Apr 24, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  29. @bdlangton bdlangton revised this gist Apr 24, 2019. 1 changed file with 6 additions and 4 deletions.
    10 changes: 6 additions & 4 deletions DB Stuff.php
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,10 @@
    // Simple database query.
    $results = \Drupal::database()->query('select * from purge_queue')->fetchAll();
    ## DB Stuff

    // Debugging an entity query, enable the devel module and add tag before execute.
    $entity_query->addTag('debug')->execute();
    ### Simple database query.
    ```$results = \Drupal::database()->query('select * from purge_queue')->fetchAll();```

    ### Debugging an entity query, enable the devel module and add tag before execute.
    ```$entity_query->addTag('debug')->execute();```

    // Delete all 'event' nodes.
    $result = \Drupal::entityQuery('node')
  30. @bdlangton bdlangton revised this gist Apr 24, 2019. 1 changed file with 14 additions and 0 deletions.
    14 changes: 14 additions & 0 deletions Images.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    // Render array for an image style.
    $render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => 'public://my-image.png',
    ];

    // Image style, get URL (full URL including http://).
    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
    $image_url = $style->buildUrl('public://du_content_gallery-article.jpg');

    // Image style, get URI (public://path-to-image-style).
    $style = ImageStyle::load('thumbnail');
    $image_url = $style->buildUri('public://du_content_gallery-article.jpg');