How to filter options in a select2_grouped field based on webshop_id? #1279
-
Hi, I’ve created a select2_grouped field in my Backpack CRUD:
Now, I need to filter the products shown in the dropdown, so it only displays products where webshop_id = $this->webshopId. I’ve successfully implemented a filter for a simple select field like this:
However, I’m not sure how to apply a similar filter to a select2_grouped field. Is there a way to achieve this? Thanks in advance for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
To filter options in a select2_grouped field based on webshop_id, you can use the CRUD::field('most_sold_product_1_id')
->label('Meest verkocht product 1')
->type('select2_grouped')
->entity('most_sold_product_1')
->attribute('title')
->group_by('sub_categories')
->group_by_attribute('title')
->group_by_relationship_back('products')
->options(function ($query) {
return $query->where('webshop_id', $this->webshopId)
->where('active', 1)
->orderBy('title', 'ASC')
->get();
})
->wrapper(['class' => 'form-group col-md-6']); This approach should filter the products shown in the dropdown to only display products where webshop_id matches $this->webshopId and are active, ordered by title in ascending order. However, it's important to note that the One such alternative could be to create a custom model that includes the filtering logic, as suggested in the How to filter the options in a select field documentation. You could create a new model that extends your original model and includes a global scope for the webshop_id filter, then use this new model in your select2_grouped field. If you encounter any issues or need further assistance, I recommend reaching out to the Backpack community or consulting the official documentation for the most up-to-date information on handling complex filtering scenarios with select2_grouped fields. ℹ️ Please note our AI Bot does not reply to follow-ups, this will be the only AI answer in this thread. If the AI helped you find the answer, please mark it as answered or write details below so it can learn. Then close the conversation. If not, please give more information for when a human reads this. ℹ️ Relevant sources: Github Issue (closed): Add a scope to Select2 |
Beta Was this translation helpful? Give feedback.
-
Fixed with static::addGlobalScope() in the model |
Beta Was this translation helpful? Give feedback.
-
Hello @ceeckhout I'm glad you make this work, and thanks for sharing the way to do it. I will close this issue, but please feel free to re-open or create a new one if needed. Cheers. |
Beta Was this translation helpful? Give feedback.
Fixed with static::addGlobalScope() in the model