I am working with drupal 8.6.10.
I am using group module.
I have a view that shows Public's Content, and Group's Content for users with group.
This view Shows only Public content for user without group

So for people who are members of a group I added a filter In this Filter I need differents Options :

  • All
  • Public (content with group id null)
  • Private (content with group id Not null)
  • user group1 (content with group id define to 4 for example)
  • user group2 (content with group id define to 7 for example)
  • ...

So my filter is based on group id.
I tried to combine the view settings that able to select Null and Not Null Value.
I Added a hook to alter form filter
All, Null Or not null work
But when I select other filter value (a group name) it doesn't work : when I select a group in the filter it s like I select 'All'.

The view settings : the view settings

My code

 * Implements hook_form_alter().
function btw_features_form_alter(&$form, &$form_state, $form_id) {

  if ($form['#id'] == "views-exposed-form-all-events-page") {
    //Init the computed user group(s) array
    $computedOptions = [];

    //Get the computed user group(s).
    $user= \Drupal::currentUser();
    $grp_membership_service = \Drupal::service('group.membership_loader');
    $grps = $grp_membership_service->loadByUser($user);
    foreach ($grps as $grp) {
      $grpId = $grp->getGroup()->id();
      $grpLabel = $grp->getGroup()->label();
      $computedOptions[$grpId] = t($grpLabel);

    // Update the filter 'filter-user-group'
    if(isset($form['filter-user-group'])) {
       $options = $form['filter-user-group']['#options'];
      if(count($computedOptions) > 0) {
        $form['filter-user-group']['#empty_option'] = t('-- Sélectionner un groupe --');
        $form['filter-user-group']['#options'] = $options + $computedOptions ;
      } else {
         // hide the filter for user without group
         $form['filter-user-group']['#type']         = 'hidden';

What am I doing wrong ?

Thanks for help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.