If you're using the wonderful Drupal Commerce, you may run into situations, where the product prices should not be shown (yet), e.g. if you're just preparing the shop or orders should just be requests first.
Sometimes you'd also want to hide prices from certain user roles.
The following snippet can be used to hide Drupal Commerce Product prices:
/**
* Implements hook_entity_field_access().
*/
function HOOK_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, ?\Drupal\Core\Field\FieldItemListInterface $items = NULL) {
// Hide the price fields displays:
if ($operation === 'view') {
if (in_array($field_definition->getName(), ['price', 'list_price', 'unit_price', 'total_price'])) {
return AccessResult::forbidden();
}
}
return AccessResult::neutral();
}
This can even be modified for more complex cases like: Hide the price, dimensions or weight, if the value equals zero:
/**
* Implements hook_entity_field_access().
*/
function HOOK_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, ?\Drupal\Core\Field\FieldItemListInterface $items = NULL) {
// Hide the product variation price if empty:
if (in_array($field_definition->getName(), ['price', 'list_price', 'unit_price', 'total_price'])) {
$value = $items?->getValue();
// Hide price if empty:
return \Drupal\Core\Access\AccessResult::forbiddenIf((isset($value[0]['number']) && empty((float) $value[0]['number'])), 'Empty prices are hidden by drowl_customer_entity_field_access');
}
// Hide the product variation dimensions, if empty
if (in_array($field_definition->getName(), ['dimensions'])) {
$value = $items?->getValue();
// Hide price if empty:
return \Drupal\Core\Access\AccessResult::forbiddenIf((isset($value[0]['length']) && empty((float) $value[0]['length']) && empty((float) $value[0]['width']) && empty((float) $value[0]['height'])), 'Empty dimensions are hidden by drowl_customer_entity_field_access');
}
// Hide product variation weight if empty:
if (in_array($field_definition->getName(), ['weight'])) {
$value = $items?->getValue();
return \Drupal\Core\Access\AccessResult::forbiddenIf((isset($value[0]['number']) && empty((float) $value[0]['number'])), 'Empty prices are hidden by drowl_customer_entity_field_access');
}
}
return \Drupal\Core\Access\AccessResult::neutral();
}
I also requested a field formatter settings for that at Drupal Commerce: https://www.drupal.org/project/commerce/issues/3468958
It's inspired by the great field_permissions module!