1

I have a user that has a taxonomy vocabulary attached their account and a content type with the same taxonomy vocabulary attached to it.

How do I get a page view filter to only display the nodes that have the same taxonomy term that is attached to the user vocabulary?

2 Answers 2

2

You can do this with a combination of Relationships and Contextual filters.

  1. Create Page Display Views listing your Content nodes
  2. Add the Relationship towards the Taxonomy term through your Taxonomy reference fields Taxonomy term referenced from field_[mytaxonomy]". You can Require this Relationship if you don't want any nodes to appear that have that field empty
  3. Add another Relationship User using field_music. It will automatically use the first Relationship.
  4. Add the Contextual Filter User ID and configure it:
    Relationship field_[mytaxonomy]
    When the filter value is NOT available
    Provide default value
    User ID from route context
    When the filter value IS available or a default is provided
    Override title
    Content matching Taxonomy chosen by the user {{ arguments.uid }} (check your argument token under Replacement patterns)
    Specify validation criteria
    User ID
  5. Optional: Change your Path setting to user/%user/[Vocabularyname] and Menu to Menu tab "[Your tab name]". This will add a Drupal tab on the user profile pages that shows this Views, listing content that is related to the terms chosen by the user in their profile settings.

If you get duplicates in the results you can turn the Aggregation on and it will help to show each node only once.

1

One way to do it is a bit of a multi-step process.

First, in the view itself under ADVANCED -> CONTEXTUAL FILTERS set up a contextual filter for the taxonomy field you want to filter the view based on (make sure that field is also added to the view's fields.

second, you'll need to add a bit of code to a custom module. You'll want to implement hook_views_pre_view

/**
 * Implements hook_views_pre_view().
 *
 * @param ViewExecutable $view
 * @param string $display_id
 * @param array $args
 * @return void
 */
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $account = \Drupal::currentUser();

  // DO A LOOKUP FOR THE USER'S FIELD
  $VALUE_FROM_USER_FIELD_LOOKUP = 'SOMETHING';

  // IF WE ARE IN THE RIGHT VIEW AND DISPLAY
  if($view->id() == 'MY VIEW ID' && $view->getDisplay()->display['id'] == 'MY DISPLAY ID') {
    // ADD SOME CUSTOM ARGS TO THE CONTEXT FILTER
    $args = [implode("+", $VALUE_FROM_USER_FIELD_LOOKUP)]; //implode on + or some other character? for multi-value contextual filters...
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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