if ($view->id() === 'more_like_this' &&
$view->current_display === 'rest_similar_by_popularity'
) {
$product_id = $view->args[0];
$product = \Drupal::entityTypeManager()
->getStorage('commerce_product')
->load($product_id);
$term = $product->get('app_group')->referencedEntities()[0];
$top_term = get_top_level_parent($term);
if ($top_term) {
switch ($top_term->get('name')->value) {
case 'Kültéri lámpák' || 'Beltéri lámpák':
// Recommended manufacturer.
$manufacturer = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties([
'vid' => 'manufacturer',
'name' => 'AZzardo',
]);
$manufacturer = reset($manufacturer);
// Get all products belonging to the same term (group)
// and recommended manufacturer.
$products = \Drupal::entityTypeManager()
->getStorage('commerce_product')
->loadByProperties([
'app_group' => $term->id(),
'app_manufacturer' => $manufacturer->id(),
]);
foreach ($products as $key => $product) {
$onDiscount = checkIfOnDiscountAndOnStock($product);
if (!$onDiscount) {
unset($products[$key]);
}
}
$product_ids = [];
array_walk($products, function ($product) use (&$product_ids) {
$product_ids[] = $product->id();
});
$query->addWhere(0, 'product_id', $product_ids, 'IN');
break;
}
}
}
function checkIfOnDiscountAndOnStock($product): bool {
$variations = $product->getVariations();
foreach ($variations as $variation) {
if (!empty($variation->get('list_price')) && $variation->get('app_purchaseitem')->value == 1) {
if ($variation->get('list_price')->number > $variation->get('price')->number) {
return TRUE;
}
}
}
return FALSE;
}
function get_top_level_parent($term) {
if ($term->hasField('parent') && $term->get('parent')->target_id !== '0') {
$term = $term->get('parent')->referencedEntities()[0];
return get_top_level_parent($term);
}
else {
return $term;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter