Hot answers tagged

145

Some of the other answers were only correct during previous alpha/beta versions of Drupal 8, or seemed to be incomplete. As of beta7 (and hopefully permanently), the following rules should apply: For the current raw path (the un-aliased Drupal path): $current_path = \Drupal::service('path.current')->getPath(); For the current URI, which is pretty-much a ...


128

The parameter will have been upcasted from nid to full node object by the time you get access to it, so: $node = \Drupal::routeMatch()->getParameter('node'); if ($node instanceof \Drupal\node\NodeInterface) { // You can get nid and anything else you need from the node object. $nid = $node->id(); } See the change record for more information.


111

I guess you do not need to convert $entity into an array, this would simply work. $entity->get('field_name')->getValue(); FYI : Using kint() from the devel_kint module will let you know all the available methods that could be used to access the object elements, so comparatively var_dump() is less helpful.


102

This error message is coming from a feature that was added to Drupal 8 to protect against HTTP Host header attacks. The feature is also described in the change record that was generated for the patch. Essentially, it was possible to spoof the HTTP Host header for nefarious purposes, and trick Drupal into using a different domain name in several subsystems (...


96

You can get the hostname, "drupal8.local", directly from the getHost() request: $host = \Drupal::request()->getHost(); In some cases you might want to get the schema as well, fx https://drupal8.local: $host = \Drupal::request()->getSchemeAndHttpHost();


91

There are two types of blocks, and the method for rendering the two is a bit different: Content Blocks Content blocks are blocks that you create in the interface. They are much like nodes configurable data structures, with fields etc. If you want to render one of these, you can do what you would normally do with entities, load them and render them with the ...


90

Youu can get the UUID with drush config-get "system.site" uuid. You can change it with drush config-set "system.site" uuid [uuid].


90

The path to referenced entity is very long: // $id = some node ID // $field = field name for entity reference field $node = Node::load($id); /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $referenceItem */ $referenceItem = $node->get($field)->first(); /** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $...


87

You can use the method hasField(): $entity->hasField('abc')


83

From the change record: $name = $_POST['name']; // form param becomes $name = \Drupal::request()->request->get('name'); // form param Incidentally, for GET vars, you would use: $query = \Drupal::request()->query->get('name');


80

To get the current route name, use: $route_name = \Drupal::routeMatch()->getRouteName(); You can add the current page's route name as a variable in your theme's ".theme" file. Add a _preprocess_page function like this, and clear the drupal cache. /** * Implements hook_preprocess_page(). * */ function mytheme_preprocess_page(&$variables) { $...


79

/core contains all the files provided by core that doesn't have an explicit reason to be in the / directory. /libraries contains third-party libraries. It's not used by Drupal core, but it's commonly found in many sites. /modules is the directory into which all custom and contributed modules go. This directory contains the contrib and custom sub-directories, ...


72

To get the path alias for a node given its node ID use the path.alias_manager service, like the following code. $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid); In Drupal 8.8.0 and newer versions, the path.alias_manager service has been deprecated, removed in Drupal 9, and replaced by the path_alias.manager service. The ...


68

in drupal 8 , $node being of class node $node->field_machine_name->getValue(); or $node->get('field_machine_name')->getValue(); will return an array of values. If you expect only one, you might as well stringify the array with $node->field_machine_name->getString(); or $node->get('field_machine_name')->getString();


68

While accessing state directly works, you can also just use the API: drupal_set_installed_schema_version(), which has existed since 4.7, as visible on the linked documentation page. This function is deprecated in Drupal 9.3.0 and removed in 10.0.0, where you should use \Drupal\Core\Update\UpdateHookRegistry::setInstalledVersion() instead. To set it from ...


65

{{ entity.field_name.value }} to get the true raw value, includes tags and encoding. Example: {{ node.body.value }} result: <p>Batman &amp; Robin</p> {{ content.field_name.0 }} to get the raw value minus tags and encoding. Example: {{ content.body.0 }} result: Batman & Robin raw This filter should be avoided whenever possible,...


65

The following code will help you to save an image in a new node. use \Drupal\node\Entity\Node; use \Drupal\file\Entity\File; // Create file object from remote URL. $data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png'); $file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE); // Create node object with ...


64

\Drupal::l is deprecated. Maybe this case will be useful for somebody use Drupal\Core\Url; use Drupal\Core\Link; $url = Url::fromRoute('entity.node.edit_form', array('node' => NID)); $project_link = Link::fromTextAndUrl(t('Open Project'), $url); $project_link = $project_link->toRenderable(); // If you need some attributes. $project_link['...


64

For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous() method, e.g. if (\Drupal::currentUser()->isAnonymous()) { // Anonymous user... }


60

Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment. {{ file_url(node.field_image.entity.fileuri) }}


59

Your PHP from your latest edit would translate into twig like this: {{ node.field_my_link.0.url }} This works like this, 0 returns the first item of the field item list, url gets the url object and because twig will cast this object as a string this will call the magic method toString() and will output the url as a string value. You only need to use url, ...


57

you can use {{ base_path ~ directory }} which will fix the absolute problem, no need to do any preprocessing, both of these variables are included by core. For example <img src="{{ base_path ~ directory }}/images/logo.png" alt="My Logo" /> PS. the ~ helper in twig is concatenate. Edit: at least in the page*.html.twig templates base_path variable is ...


57

On a development site I would suggest uncommenting the following lines in the settings.php file. emacs sites/default/settings.php if (file_exists(__DIR__ . '/settings.local.php')) { include __DIR__ . '/settings.local.php'; } and then copying the file example.settings.local.php from /sites folder to /sites/default folder and rename it to settings....


56

The Drupal 7 system table data is now stored in the config table in Drupal 8 against the core.extension parameter. Solution 1: Update configuration You can run the following code using drush eval or may be using the Devel module's provision to Execute PHP Code. // Read the configuration. $module_data = \Drupal::config('core.extension')->get('module'); ...


56

The easiest way to do this at the moment is to use drush php (or core-cli) to open an interactive session. Then use: Drupal::configFactory()->getEditable('system.menu.devel')->delete(); This functionality will be added into Drupal console as well.


54

You need to use route:<nolink> to achieve this. Then it will validate and render without a link.


53

You can use Drupal::entityQuery() & Node::loadMultiple() to load all the nodes of your given type: $nids = \Drupal::entityQuery('node')->condition('type','my_custom_type')->execute(); $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);


50

Replacing a deprecated function is in most cases trivial. Just look at it. There you can see this: \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $parent, $max_depth, $load_entities); If you are looking for a function that was already removed, search for it on Change records for Drupal core page. Pretty much every function ...


Only top voted, non community-wiki answers of a minimum length are eligible