I have a taxonomy vocabulary like this:

   |-- C(branch_field)

   |-- Z(branch_field)

Each user has a reference to a taxonomy term. I need to create a view where I pass taxonomy term attached to user for filtering data, but I need also to use the taxonomy term field "branch" in the view but I don't manage it.

This is what I see using Devel about user fields:

[field_category_user] => Array
                [x-default] => Array
                        [0] => Array
                                [target_id] => 39



Can I expose term field and target id?


You can implement hook_views_query_alter()

  1. In your view create a filter (not exposed) to field_category_user, with default value -1. If field_category_user is not aviable you need create a realation to taxonomy.
  2. Create a hook_views_query_alter() in file [module_name].views_execution.inc with some like this:

    // Implements hook_views_query_alter().

    function [module_name]_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    $id = $view->id();
    switch ($id) {
        case '[your_view_id]':
            $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
            $field_category_user = !$user->field_category_user->isEmpty() ? $user->field_category_user->value : null;
            //Set field_category_user id to where condition
            foreach ($query->where as $key => $item) {
                foreach($item['conditions'] as $items){
                    if ($items['field'] == 'field_category_user') { //Verify if field_category_user is the id of filter
                        $query->where[$key]['conditions'][0]['value'] = $field_category_user->id();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.