# Nodes

### Get Current Node information

```php
$node = \Drupal::routeMatch()->getParameter('node'); // get node

$node_type = $node->getType(); // Node type
$node_bundle = $node->bundle(); // Node type

$nid = $node->id(); // Node id

$title = $node->getTitle(); // Node title
```

### Get current Node information on preview page

```php
  $routeMatch   = \Drupal::routeMatch();
  $node_preview = $routeMatch->getParameter( 'node_preview' );
```

### Get info of a specific Node - NODE::load()

```php
$NODE_TITLE =  Node::load(ID)->getTitle(); // Node title
```

### Query Nodes

There are two methods that I use to query nodes, the first one is the `EntityQuery` and the second one is the `EntityTypeManager`. These two are almost exactly the same, if you were to look at the code, you would see that they are using the same methods. The only difference is that the `EntityTypeManager` is a bit more flexible and it's easier to use.

#### Get info of a specific Nodes - EntityQuery

```php
$node_ids = Drupal::entityQuery('node')
      ->condition('type', CONTENT_TYPE)
      ->condition('FIELD_NAME', FIELD_ID)
      ->execute(); // Get all the node ids that match these conditions
$nodes = Node::loadMultiple($node_ids); // All the nodes in an assoc array
```

#### Get info of a specific Nodes - EntityTypeManager

```php
$node = \Drupal::entityTypeManager()->getStorage('node')
        ->getQuery()
        ->condition('nid', $nid, '=')
        ->condition('type', 'blog')
        ->condition('status', 1)
        ->sort('nid', 'ASC')
        ->range(0, 1)
        ->execute();

$node = array_values($node);
$node = $node[0];

// Or we could use $node = reset($node)

$titulo =  Node::load($node)->getTitle(); // Title

$link = \Drupal::service('path_alias.manager')
          ->getAliasByPath('/node/' . $node);  // Relative url
```

#### Reference

For more information about the Node class, check the [Node Methods](https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Entity%21Node.php/class/Node/9.1.x)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://drupal.bermaki.com/drupal-documentation-and-guides/backend/nodes.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
