-
-
Save l3th2nh/2f7cc835ed6f0e9a31cb32feb8cd709f to your computer and use it in GitHub Desktop.
Revisions
-
bdlangton revised this gist
Dec 27, 2019 . 1 changed file with 8 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,11 +1,17 @@ ### Get render array for view. ``` use Drupal\views\Views; $args = []; $view = Views::getView('my_view'); $view->setDisplay('my_display'); $view->preExecute(); $view->execute(); $render_array = $view->buildRenderable('my_display', $args); ``` Get rendered markup from above: ``` Drupal::service('renderer')->renderRoot($render_array); ``` ### Get various IDs and objects. -
bdlangton revised this gist
Dec 20, 2019 . 2 changed files with 28 additions and 24 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); ``` ### Redirect. ``` use Symfony\Component\HttpFoundation\RedirectResponse; This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); ``` -
bdlangton revised this gist
Dec 19, 2019 . 1 changed file with 15 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); ``` ### 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(); -
bdlangton revised this gist
Dec 11, 2019 . 1 changed file with 11 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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. ``` -
bdlangton revised this gist
Dec 6, 2019 . 1 changed file with 33 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,14 +1,44 @@ ### 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 ``` // 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(); ``` -
bdlangton revised this gist
Nov 18, 2019 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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, $options); ``` ### URL from URI. -
bdlangton revised this gist
Nov 14, 2019 . 1 changed file with 16 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 ``` -
bdlangton revised this gist
Nov 8, 2019 . 1 changed file with 25 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 ``` -
bdlangton revised this gist
Nov 7, 2019 . 1 changed file with 10 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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';`. -
bdlangton revised this gist
Nov 5, 2019 . 1 changed file with 7 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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') -
bdlangton revised this gist
Oct 24, 2019 . 1 changed file with 11 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -8,7 +8,17 @@ $view->execute(); $view->render(); ``` ### 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; ``` -
bdlangton revised this gist
Oct 3, 2019 . 1 changed file with 4 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -6,8 +6,10 @@ ini_set('display_startup_errors', 1); error_reporting(E_ALL); ``` ### 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 -
bdlangton revised this gist
Oct 3, 2019 . 1 changed file with 11 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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)); -
bdlangton revised this gist
Sep 24, 2019 . 1 changed file with 7 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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)); -
bdlangton revised this gist
Sep 20, 2019 . 2 changed files with 15 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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. ``` -
bdlangton revised this gist
Sep 20, 2019 . 1 changed file with 7 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 -
bdlangton revised this gist
Sep 19, 2019 . 2 changed files with 24 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); ``` -
bdlangton revised this gist
Sep 18, 2019 . 2 changed files with 19 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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. This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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; ``` -
bdlangton revised this gist
Aug 16, 2019 . 1 changed file with 18 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); ``` -
bdlangton revised this gist
Aug 9, 2019 . 1 changed file with 7 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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') -
bdlangton revised this gist
Aug 2, 2019 . 1 changed file with 18 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); ``` -
bdlangton revised this gist
Jul 2, 2019 . 1 changed file with 5 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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/ ### Service Decorators https://www.axelerant.com/resources/team-blog/drupal-8-service-decorators -
bdlangton revised this gist
Apr 25, 2019 . 2 changed files with 18 additions and 10 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,10 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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) ``` -
bdlangton revised this gist
Apr 24, 2019 . 5 changed files with 56 additions and 23 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,5 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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') }} ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,6 @@ ## 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: ``` // 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 ``` // src/ElasticSearch/Parameters/Builder/SearchBuilder.php: // Add ksm at the end of build() and getSearchQueryOptions() ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,30 +1,49 @@ ## Miscellaneous ### Get the node from the current path. ``` $node = \Drupal::routeMatch()->getParameter('node'); ``` ### Get current path. ``` $path = \Drupal::service('path.current')->getPath(); ``` ### Get path arguments (from path above). ``` $path_args = explode('/', $path); ``` ### Get the current route. ``` $route_name = \Drupal::service('current_route_match')->getRouteName(); ``` ### Get the query parameter from a GET request. ``` $name = \Drupal::request()->query->get('name'); ``` ### Get the parameter from a POST request. ``` $name = \Drupal::request()->request->get('name'); ``` ### Get the host (ex: www.google.com). ``` $host = \Drupal::request()->getHost(); ``` ### Redirect. ``` use Symfony\Component\HttpFoundation\RedirectResponse; new RedirectResponse(\Drupal::url($route_name)); ``` ### Add t() to classes (services, controllers, etc) ``` use Drupal\Core\StringTranslation\StringTranslationTrait; class MyClass { use StringTranslationTrait; } ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,6 +1,7 @@ ## 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); } ``` -
bdlangton revised this gist
Apr 24, 2019 . 4 changed files with 24 additions and 8 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); ``` ### Debugging an entity query, enable the devel module and add tag before execute. ``` $entity_query->addTag('debug')->execute(); ``` ### Delete all 'event' nodes. ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); ``` ### Delete multiple entities. ``` @@ -25,4 +27,6 @@ $new_field = BaseFieldDefinition::create('string') ``` ### Apply all updates to entities. ``` \Drupal::entityDefinitionUpdateManager()->applyUpdates(); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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']]); ``` ### Convert above link to render array or link string. ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,9 +1,15 @@ ## 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(); ``` -
bdlangton revised this gist
Apr 24, 2019 . 12 changed files with 97 additions and 69 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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') ->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->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->fields(['hash' => 'update']); $query->condition('nid', 1); $query->execute(); ``` ### Delete statement. ``` $query = \Drupal::database()->delete('purge_queue'); $query->condition('data', '%url%', 'LIKE'); $query->execute(); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); $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); This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,18 +1,21 @@ ## 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'); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,6 @@ ## 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). ``` $migration = \Drupal::service('plugin.manager.migration')->createInstance('machine_name'); $migration->interruptMigration(\Drupal\migrate\Plugin\MigrationInterface::RESULT_STOPPED); ``` ### 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. ``` use Drupal\migrate\MigrateExecutable; use Drupal\migrate\MigrateMessage; @@ -36,3 +44,4 @@ function example_module_preprocess_page(&$vars) { } } } ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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']); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,3 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,14 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,6 @@ ## 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. ``` $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); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,27 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,8 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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();``` -
bdlangton revised this gist
Apr 24, 2019 . 6 changed files with 59 additions and 45 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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') ->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->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->fields(['hash' => 'update']); $query->condition('nid', 1); $query->execute(); ``` ### Delete statement. ```$query = \Drupal::database()->delete('purge_queue'); $query->condition('data', '%url%', 'LIKE'); $query->execute(); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,7 +1,9 @@ ## 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 https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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();``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,21 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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'); ``` This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,14 +0,0 @@ -
bdlangton renamed this gist
Apr 24, 2019 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
bdlangton revised this gist
Apr 24, 2019 . 1 changed file with 6 additions and 4 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,8 +1,10 @@ ## DB Stuff ### 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') -
bdlangton revised this gist
Apr 24, 2019 . 1 changed file with 14 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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');
NewerOlder