Score:0

How to create a custom Views filter to filter nodes on a field value (string) if it's in multi-value field on the user's profile?

ng flag

We have a Drupal 9 site where we need to filter a view showing nodes where their "US State" field value is contained in the user's "Assigned States" multi-value field.

Node: "US State" field is a plain text list single value field: "node__field_state_new"

User: "Assigned State(s)" is a multiple value check box field: "field_assigned_state"

We've created a custom filter but are stuck on getting it to work correctly. I suspect we may need to create joins in the query but not sure.

MODULE.views.inc:

function MODULE_views_data() {
  $data['views']['state_admin_filter'] = [
    'title' => t('Is State Admin'),
    'filter' => [
      'title' => t('Is State Admin'),
      'group' => t('Custom'),
      'help' => t('Provides a custom filter to filter state admins.'),
      'id' => 'state_admin_filter',
    ],
  ];
  return $data;
}

/src/Plugin/views/filter/StateAdminFilter.php

class StateAdminFilter extends StringFilter  {

  public $operator = 'IN';

  public function query() {
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $assigned_states = $user->field_assigned_state->getValue();
    $this->query->addWhere('AND', 'node__field_state_new.field_state_new_value', serialize($assigned_states), 'IN');
  }

}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.