1

In my preprocess function, I have the current node id, and an array with all node ids for a content type called recipes:

$current_node_id = \Drupal::routeMatch()->getParameter('node');
$nids = \Drupal::entityQuery('node')->condition('type','recipes')->execute();
$recipes_id =  \Drupal\node\Entity\Node::loadMultiple($nids);

The result of $recipes_id is as follows in the picture:

enter image description here

Next, I want to loop through all the ids and get the ID that is equal to the current id:

 $i = 0;
 foreach($recipes_id as $key => $value) {
    if($key == $current_node_id->id()) {

    }
    $i++;
 }

In the if statement, I want to access the id that is after the $key variable. so if the current id is 150 I should access 159, etc. For that, inside the if statement I added the following:

$variables['node'] = $recipes_id[$i];

When I view the page though, I see a null:

{{ kint(node) }}

Here is my entire function:

function amarula_preprocess_page(&$variables) {

    /**
     * get current node id
     */ 
    $current_node_id = \Drupal::routeMatch()->getParameter('node');

    /**
     * check the current language
     */
    $current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $variables['current_lang'] = $current_lang; //current language code

    /**
     * get all recipes node id
     */
    $nids = \Drupal::entityQuery('node')->condition('type','recipes')->execute();
    $recipes_id =  \Drupal\node\Entity\Node::loadMultiple($nids);
    $variables['recipes_id'] = $recipes_id; // recipes node ID

    $i = 0;
    foreach($recipes_id as $key => $value)
    {
        if($key == $current_node_id->id())
        {
            $variables['node'] = $recipes_id[$i + 1];
            break;
        }
        $i++;
    }
}

Having the current ID, how can I find the ID after that in the array?

3
  • Why loop through the arary if you already know the key Commented Mar 5, 2020 at 16:26
  • Why not use array_keys for that? Commented Mar 5, 2020 at 16:27
  • @RiggsFolly an answer with code would sound better if you do not mind. Commented Mar 5, 2020 at 16:32

1 Answer 1

1

here is how you get the next key.

$keys = array_keys($recipes_id);
$i = 0;
foreach($keys as $value)
{
    if($value == $current_node_id->id()){
        $variables['node'] = $keys[$i + 1];
        break;
    }
    $i++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@useragent if you have array structure like this it should just work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.