Hot answers tagged

85 votes
Accepted

How can I get the path alias from a node ID or node object?

To get the path for a node id use AliasManager::getAliasByPath: Drupal 8 $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid); Drupal 9 $alias = \Drupal::service('...
4uk4's user avatar
  • 99.2k
73 votes
Accepted

How can I programmatically create a node?

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://...
amitgoyal's user avatar
  • 1,312
61 votes
Accepted

Get all nodes of given type

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 ...
Shawn Conn's user avatar
  • 26.8k
54 votes

How to load a node by a field value?

The quickest way to load a specific node by field value is to use the method loadByProperties(). You specify one or more field values and returned is an array containing the nodes matching the field ...
4uk4's user avatar
  • 99.2k
51 votes

How do I get the node URL in a Twig template?

According to Functions - In Twig Templates you can use is simple by {{ path('entity.node.canonical', {'node': node.id}) }}
Yuseferi's user avatar
  • 22k
37 votes
Accepted

How can I get the node ID from a path alias?

I'm not sure if there's a direct function, but one route is to use the path alias manager service to lookup the internal path then regex it for a valid node id to perform an object load on: $path = \...
Shawn Conn's user avatar
  • 26.8k
37 votes

How can I get the path alias from a node ID or node object?

If you only have the nid, 4k4's solution of $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid); Works great. But if you already have a node object you can skip a step ...
Amy's user avatar
  • 5,662
35 votes
Accepted

Get the list of all content types

loadMultiple() should be fine for this: $types = \Drupal::entityTypeManager() ->getStorage('node_type') ->loadMultiple();
Clive's user avatar
  • 167k
35 votes
Accepted

How to get node object from node ID

There are a few ways. If your context allows for Dependency injection, inject the entity_type.manager service and use it like so: $node = $this->entityTypeManager->getStorage('node')->load($...
Clive's user avatar
  • 167k
32 votes

How to delete all nodes of a given content type?

In Drupal 8 one way is use the entityQuery() method with the EntityStorageInterface::delete() method: $result = \Drupal::entityQuery("node") ->condition("type", "YOUR_CONTENT_TYPE_NAME") //...
Adrian Cid Almaguer's user avatar
32 votes
Accepted

Programmatically updating a node

You can try this code <?php use Drupal\node\Entity\Node; $node = Node::load($nid); //set value for field $node->body->value = 'body'; $node->body->format = 'full_html'; //field tag $...
MrD's user avatar
  • 6,208
31 votes

Get all nodes of given type

Another way to do this would be using this snippet of code: // Set properties to filter. $values = [ 'type' => 'page', ]; // Get the nodes. $nodes = \Drupal::entityTypeManager() ->...
MrD's user avatar
  • 6,208
31 votes
Accepted

How to get the human readable content type name in a node template

You should be able to get the human-readable name of the content type (or the "label") by using the following snippet in your node Twig template. {{ node.type.entity.label }}
edwardchiapet's user avatar
25 votes
Accepted

How to get the url of a file field of a given node?

// Load the file. $file = \Drupal\file\Entity\File::load($fid); // Get the URL. $url = \Drupal::service('file_url_generator') ->generateAbsoluteString($file->getFileUri()); Before Drupal 10, ...
Kevin's user avatar
  • 2,558
24 votes

How do I get the current node ID?

It is correct to use \Drupal::routeMatch()->getParameter('node'). If you just need the node ID, you can use \Drupal::routeMatch()->getRawParameter('node').
Maouna's user avatar
  • 1,216
23 votes

How can I get the path alias from a node ID or node object?

What about using Url: use Drupal\Core\Url; ... $url = Url::fromRoute('entity.node.canonical', ['node' => $nid])->toString();
Kevin's user avatar
  • 27.8k
23 votes
Accepted

How do I programmatically update the allowed values of a list field?

You can't do this in a form alter hook, because the entity field validation will fail. You have to add a function to the field settings. This is not in the field UI, so you have to export the ...
4uk4's user avatar
  • 99.2k
22 votes
Accepted

How to embed a view in a specific node?

Twig Views Embed This module allows to embed views with a twig function. {{ views_embed_view('view_name', 'view_id') }} The above module was depreciated in favour of Twig Tweak Twig Tweak module ...
No Sssweat's user avatar
  • 31.1k
22 votes

Show node IDs along with titles in Entity reference Autocomplete list

Install the Views and Entity Reference modules, create a new View and Add a Entity Reference Display: Then Add in the fields the content title and the nid, click in the nid and check Exclude from ...
Adrian Cid Almaguer's user avatar
21 votes
Accepted

How to use presave hook to save a field value as node title?

You need to implement the hook_entity_presave() /** * Implements hook_entity_presave(). */ function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { switch ($entity->...
Adrian Cid Almaguer's user avatar
21 votes
Accepted

Override theme template from module without implementing a theme

You can do this in hook_theme() with the base hook 'node': function MY_MODULE_theme($existing, $type, $theme, $path) { return [ 'node__video_teaser' => [ 'template' => 'node--video-...
4uk4's user avatar
  • 99.2k
21 votes

How do I get the node URL in a Twig template?

In a node.html.twig you can directly use {{ url }} <a href="{{ url }}">read more</a> For more information read comment in core template : /core/modules/node/templates/node.html.twig : {...
toto21's user avatar
  • 311
20 votes

Get the list of all content types

You can load all of the NodeType entities (config entities) using the NodeType class: $node_types = \Drupal\node\Entity\NodeType::loadMultiple(); // If you need to display them in a drop down: $...
googletorp's user avatar
  • 35.4k
20 votes

Get all nodes of given type

Its actually very easy, \Drupal::entityTypeManager()->getStorage('node') ->loadByProperties(['type' => 'content_type', 'status' => 1]) If you would like all nodes also unpublished just ...
Remco Hoeneveld's user avatar
20 votes
Accepted

How to create a multilingual node programmatically?

Fortunately I found a post named Create and translate a multilingual nodes programmatically. And here is the code with some comments: use Drupal\node\Entity\Node; $node = Node::create([ // The ...
Adrian Cid Almaguer's user avatar
19 votes
Accepted

How to load a node by a field value?

You can achieve by using EntityFieldQuery. For D8 EntityFieldQuery has been rewritten. Drupal 8: $query = \Drupal::entityQuery('entity_test'); $default_langcode_group = $query->andConditionGroup(...
DRUPWAY's user avatar
  • 7,383
18 votes
Accepted

Is there a way to tell if the current page is a node?

\Drupal::request()->attributes->get('node'); Taken from here: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3Arequest/8 Now the docs say to never use this function, ...
Kevin's user avatar
  • 27.8k
18 votes
Accepted

Delete a node after X weeks it was created

If you're looking for a developer-centric solution, you can invoke hook_cron() in a custom module to clean up old nodes: function MYMODULE_cron() { // Other conditions can be altered/added as ...
Shawn Conn's user avatar
  • 26.8k
18 votes
Accepted

Check content type of node in preprocess hook

To get the content type of a node, you just use $variables['node']->getType() or $variables['node']->bundle(). The first method just calls the second, so calling one or the other one doesn't ...
apaderno's user avatar
  • 97.4k
18 votes
Accepted

Programmatically set a datetime field

Datetime fields in Drupal 8 are stored as strings. So you need to convert it into string. You can use the format method, e.g. $formatted_date = $date->format('Y-m-d H:i:s'); Refer Inserting the ...
DRUPWAY's user avatar
  • 7,383

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