Created
April 12, 2023 06:37
-
-
Save prashantdsala/c026507a0d8a78698e799d790eeaefdc to your computer and use it in GitHub Desktop.
Drupal - Alter views query and add where conditions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_views_query_alter(). | |
*/ | |
function mymodule_announcements_views_query_alter(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\query\QueryPluginBase $query) { | |
// Alter annoucements views. | |
if (($view->id() == 'announcements')) { | |
if ($view->current_display == 'page_announcements' || $view->current_display == 'block_announcements') { | |
$current_user_id = \Drupal::currentUser()->id(); | |
$user_service = \Drupal::service('my_service.user'); | |
$roles = $user_service->getUserRoles(); | |
$definition = [ | |
'table' => 'node__field_role', | |
'field' => 'entity_id', | |
'left_table' => 'node_field_data', | |
'left_field' => 'nid', | |
'operator' => '=', | |
'type' => 'INNER' | |
]; | |
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition); | |
$query->addRelationship('node__field_role', $join, 'node_field_data'); | |
$query->addField('node__field_role', 'field_role_target_id'); | |
$query->addWhere("conditions", "node__field_role.field_role_target_id", $roles, 'IN'); | |
$definition = [ | |
'table' => 'node__field_user', | |
'field' => 'entity_id', | |
'left_table' => 'node_field_data', | |
'left_field' => 'nid', | |
'operator' => '=', | |
'type' => 'LEFT' | |
]; | |
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition); | |
$query->addRelationship('node__field_user', $join, 'node_field_data'); | |
$query->addField('node__field_user', 'field_user_target_id'); | |
$query->addWhere("conditions", "node__field_user.field_user_target_id", [$current_user_id], 'IN'); | |
$query->where['conditions']['type'] = 'OR'; | |
} | |
} | |
// Alter entity reference view for users autocomplete. | |
// Display only group users in the select list. | |
if ($view->id() == 'entity_reference_users') { | |
$user_service = \Drupal::service('my_service.user'); | |
$current_user_id = \Drupal::currentUser()->id(); | |
$groups = $user_service->getUserGroups(); | |
$groups = array_values(array_flip($groups)); | |
if ($view->current_display == 'entity_reference_group_users') { | |
$query->addWhere("conditions", "group_content_field_data_users_field_data.gid", $groups, 'IN'); | |
$query->addWhere("conditions", "group_content_field_data_users_field_data.entity_id", $current_user_id, '!='); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment