diff --git a/commerce.views.inc b/commerce.views.inc index 4918380..e8bbcee 100644 --- a/commerce.views.inc +++ b/commerce.views.inc @@ -4,7 +4,7 @@ * Implements hook_views_data_alter(). */ function commerce_views_data_alter(array &$data) { - // Override the bundle views field handler for commerce content entities.. + // Override the bundle views handlers for commerce content entities. $entity_types = \Drupal::service('entity_type.manager')->getDefinitions(); foreach ($entity_types as $entity_type) { if ($entity_type instanceof \Drupal\Core\Entity\ContentEntityType && strpos($entity_type->id(), 'commerce_') === 0) { @@ -12,9 +12,11 @@ function commerce_views_data_alter(array &$data) { // (such as Order) have only a base table. if ($data_table = $entity_type->getDataTable()) { $data[$data_table][$entity_type->getKey('bundle')]['field']['id'] = 'entity_bundle'; + $data[$data_table][$entity_type->getKey('bundle')]['filter']['id'] = 'entity_bundle'; } else { $data[$entity_type->getBaseTable()][$entity_type->getKey('bundle')]['field']['id'] = 'entity_bundle'; + $data[$entity_type->getBaseTable()][$entity_type->getKey('bundle')]['filter']['id'] = 'entity_bundle'; } } } diff --git a/src/Plugin/views/filter/EntityBundle.php b/src/Plugin/views/filter/EntityBundle.php new file mode 100644 index 0000000..f134f52 --- /dev/null +++ b/src/Plugin/views/filter/EntityBundle.php @@ -0,0 +1,67 @@ +options['expose']['hide_single_bundle'] = FALSE; + } + + protected function defineOptions() { + $options = parent::defineOptions(); + + $options['expose']['contains']['hide_single_bundle'] = array('default' => FALSE); + + return $options; + } + + /** + * {@inheritdoc} + */ + public function buildOptionsForm(&$form, FormStateInterface $form_state) { + parent::buildOptionsForm($form, $form_state); + + // Option to hide the bundle name if there is only one bundle. + $form['expose']['hide_single_bundle'] = [ + '#type' => 'checkbox', + '#title' => t('Hide if there is only one bundle.'), + '#default_value' => $this->options['expose']['hide_single_bundle'], + ]; + } + + /** + * {@inheritdoc} + */ + public function buildExposedForm(&$form, FormStateInterface $form_state) { + if ($this->options['expose']['hide_single_bundle']) { + $entity_type = $this->getEntityType(); + $bundles = $this->entityManager->getBundleInfo($entity_type); + // Hide bundle exposed filter if there is only one bundle. + if (count($bundles) == 1) { + $this->options['expose'] = FALSE; + $form = []; + } + } + + // Build the exposed filter. + parent::buildExposedForm($form, $form_state); + } + +}