How to Programatically Modify a View for an Entity Browser

Viewed 12

Here's my issue: I have an entity browser tied to a view. The view is relatively straight forward, but I need to modify the filter criteria programatically. The view is selecting nodes from two content types: A and B. Content type B needs to be fitered because we only want to display B if it's taxonomy is in Cars or Boats (not Trains, Planes, etc.).

Example SQL:

SELECT `nid`,
FROM `node_field_data`
JOIN `node__field_mytaxonomy_types` ON `node__field_mytaxonomy_types`.`entity_id` = `node_field_data`.`nid` AND (`node__field_mytaxonomy_types `.`field_mytaxonomy_types_target_id` = '1' OR `node__field_mytaxonomy_types `.`field_mytaxonomy_types_target_id` = '2')
WHERE (`node_field_data`.`type` IN (‘A’, ‘B’)) AND (`node_field_data`.`type` IN (‘B’)) AND (`node_field_data`.`status` = '1')

The join would ONLY happen if the user chooses content type B.

Note: I've tried creating filter groups, but it doesn't work. The entire query stops functioning correctly.

I thought creating a Views Filter would be the way to go, but after many hours of research, I've learned that Entity Browsers are special. So rather than being able to get the routeMatch() on a node

$current_node_or_nid = \Drupal::routeMatch()->getParameter("node");  // returns NULL

I returned all parameters to see what was available and the only on found was:

$params = \Drupal::routeMatch()->getParameters()->all();  // returns ['entity_browser_id]

Not helpful because I need to check the Node ID to see if that node is of content type B so I can check it's field for the taxonomy value.

Should I stick with Views Filter? Here's my code for the views filter:

public function query() {

$this->ensureMyTable();

$current_node_or_nid = \Drupal::routeMatch()->getParameter("node");
$current_node = "";

if (is_string($current_node_or_nid)) {
    $current_node = Node::load($current_node_or_nid);
}
else {
    $current_node = $current_node_or_nid;
}

if ($current_node) {
    if ($current_node->hasField("field_mytaxonomy_types")) {
        $mytaxonomy_type_info = $current_node->get("field_mytaxonomy_types")->getValue();
            if ($mytaxonomy_type_info == "Cars" or $news_type_info == "Boats") {
                $mytaxonomy_type_id = $mytaxonomy_type_info[0]["target_id"];
            }

        $join_configuration = array(
            "table" => "node__field_mytaxonomy_types",
            "field" => "entity_id",
            "left_table" => $this->table,
            "left_field" => "nid",
            "operator" => "="
        );

        $join = Views::pluginManager("join")->createInstance("standard", $join_configuration);
        $this->query->addRelationship("node__field_mytaxonomy_types", $join, $this->table);
        $this->query->addWhere("AND", "node__field_mytaxonomy_types.field_mytaxonomy_types_target_id", $mytaxonomy_type_id);
    }
}
}

If not, what is the preferred method?

Thanks.

0 Answers
Related