php – Drupal 8 get value of next node id when visiting a node page-ThrowExceptions

Exception or error:

I have a list of the recipes node type, and when I visit a single recipe< i want to show a button that has the link of the next recipe id. From there I will be able to find the node alias and have a URL ready to be placed in the twig file.

In my logic, I queried the database I retrieve a list of all node ids that are of type recipe and the language code is equal to the current page language.

$current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$current_node_id = \Drupal::routeMatch()->getParameter('node'); // get the ID of the current page being visited
$nids = \Drupal::entityQuery('node')->condition('type','recipes')->execute();
$recipes_id = \Drupal\node\Entity\Node::loadMultiple($nids);
$recipe_keys = array_keys($recipes_id); // creates an array with all recipes page ID

$database = \Drupal::database();
$query = $database->query("SELECT nid FROM node WHERE type = 'recipes' AND langcode = '" . $current_lang . "'");
$results = $query->fetchAll();

So far, I get it to work.

$language_ids = [];

for($i = 0; $i < count($results); $i++)
    array_push($language_ids, $results[$i]->nid);

If I var dump $language_ids I see the list of all IDs.
Now next I want to loop through the array($language_ids) and find the id that is equal to my current page/node ID.
After finding that in $language_ids I want to access the next id if there is one.
In the absence of next element in the array, I want to just access the value in the first position.

Below is the rest of my logic:

for( $j = 0; $j < count($language_ids); $j++ )
    if( $language_ids[$j] = $current_node_id )
            $variables['next_node'] = $language_ids[0];
        else {
            $next_node_id = $language_ids[4];
            $variables['next_node'] = $language_ids[$j + 1];

If I var_dump $next_node, I get a null value.
Also, if I replace this:

$variables['next_node'] = $language_ids[$j + 1];

for this:

$variables['next_node'] = $language_ids[1];

I get the following:

enter image description here

How can I get the next value of my $language_ids ?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *