I have a drupal commerce website.
On my product, i've added a field "stock" which tell if is product is available (custom workflow) which is like the "visibility" field (list of all stores with checkboxes).
I've created a view which list all of my product for a specific store (each store is assign to 1 user).
In my view result, I rewrite the value ot stock. If my store is in the product stock list, I show "available" (else "not available") instead of the store IDs list.
So far, everything is great.
I'd like to add a filter with "available/not available". So on my view, i've added the filter "stock", as "group" and I've added 2 options (available/not available)
Now I'd like to "link" the filter with the "stock" field. I've created the mymodule_views_query_alter function to rewrite the condition to match my needs.
But it doesn't work as expected. The "available" option works with "IN/=" (don't get why "=" is working), it doesn't show the .
The "not available" options show every row (with NOT IN), even the available rows.
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query)
{
if($view->id() == "myview") {
foreach ($query->where as &$condition_group) {
foreach ($condition_group['conditions'] as &$condition) {
if ($condition['field'] == 'commerce_product__field_stock.field_stock_target_id') {
$current_user = \Drupal::currentUser()->id();
$stores = StoreHelper::getStoreByOwner($current_user);
$store = count($stores) ? $stores[array_key_first($stores)] : NULL;
$value = $condition['value'];
if($value == "true") {
$condition = [
'field' => $condition['field'],
'value' => "{$store->id()}", //2
'operator' => 'IN', // works with "="
];
} else if($value == "false") {
$condition = [
'field' => $condition['field'],
'value' => "{$store->id()}",
'operator' => 'NOT IN',
];
}
}
}
}
}
}
EDIT : the result ::
The database structure (which means the product is available for the store 4,2,6):
bundle |entity_id |field_stock
product | 38| 2
product | 38| 4
product | 38| 6