I’m trying to create a card grid component using paragraphs. I have a reference entity which references different card types with unlimited cardinality. I’m able to pull the values from the reference entity with the below code but this only pulls the initial values so I’m only getting data from one entity instead of each individual entity as they are added to the grid. I’m not sure why my foreach loop is not working in my preprocess paragraph function, can anyone steer me in the right direction?
if ($paragraph->getType() == 'card_grid') {
if (!$paragraph->field_select_card_type->isEmpty()) {
$field_select_card_type = $paragraph->field_select_card_type->referencedEntities();
$card_array = [];
foreach($field_select_card_type as $key => $card_type) {
$card_title = "";
$card_image = "";
$card_url = "";
$card_meta_description = "";
$card_type_data = $card_type->get('field_select_a_page')->referencedEntities();
$node_id = $card_type_data[0]->id();
$node_data = \Drupal\node\Entity\Node::load($node_id);
if($node_data) {
$card_title = $node_data->title->value;
if ($node_data->bundle() == "article") {
$card_image = !$node_data->field_image->isEmpty() ? $node_data->field_image->entity->getFileUri() : "";
}
if ($node_data->bundle() == "page") {
$card_image = !$node_data->field_featured_image->isEmpty() ? $node_data->field_featured_image->entity->getFileUri() : "";
}
$card_url = $node_data->toUrl()->toString();
}
$card_title = $card_type->field_override_title_->value ? $card_type->field_override_title_->value : $card_title;
if($card_type->hasField('field_override_image')){
$card_image = !$card_type->field_override_image->isEmpty() ? $card_type->field_override_image->entity->getFileUri() : $card_image;
}
$card_meta_description = $card_type->field_override_meta_description->value ? $card_type->field_override_meta_description->value : $card_meta_description;
$card_array[$key]['card_title'] = $card_title;
$card_array[$key]['card_image'] = $card_image;
$card_array[$key]['card_url'] = $card_url;
$card_array[$key]['card_meta_description'] = $card_meta_description;
}
$variables['card_array'] = $card_array;
}
}