Filter products using search & category checkbox

Silverstripe Version: 4

Question: I need to filter below products by checking the sizes checkbox while searching. The search function is working. Need assist to add the filtering function

image

**//-----Controller--------//**

public function getPaginatedBrochureProducts()

    {

        $products = SiteConfig::current_site_config()->getBrochureProducts()->filter([

            'Categories.ID' => $this->MemorialCategoryID

        ]);

        if ($filterTitle = $this->request->getVar('product')) {

            $products = $products->filter([

                'Title:PartialMatch' => $filterTitle

            ]);

        }

        return PaginatedList::create(

            $products,

            Controller::curr()->getRequest())

            ->setPageLength(24);

    }

    public function getSearchedParams()

    {

        return $this->request->getVar('product');

    }

    private static $url_handlers = [

        '' => 'index',

        'ContactDetailsForm' => 'ContactDetailsForm',

        'AddToCartForm' => 'AddToCartForm',

        'BrochureQuotationForm' => 'BrochureQuotationForm',

        '$URLSegment' => 'loadProduct',

    ];

    private static $allowed_actions = [

        'ContactDetailsForm',

        'AddToCartForm',

        'loadProduct',

        'BrochureQuotationForm'

    ];

    protected function init()

    {

        parent::init();

        Requirements::javascript('public/_resources/themes/retail/js/quotation-modal.js');

    }

    public function getProduct()

    {

        $_SESSION['ProductID'] = null;

        $url = $this->request->param('URLSegment');

        $product = BrochureProduct::get()->filter([

            'ClassName' => BrochureProduct::class,

            'URLSegment' => $url

        ])->first();

        if ($product && $product->exists()) {

            $_SESSION['ProductID'] = $product->ID;

            return $product;

        }

    }

    public function loadProduct()

    {

        $showModal = false;

        $vars = $this->request->getVar('modal');

        if ($vars == 'contact-details') {

            $showModal = true;

        }

        $product = $this->getProduct();

        if ($product) {

            return $this->customise([

                'BrochureProduct' => $product,

                'IsShowModal' => $showModal

            ]);

        }

    }
**//-----Brochure Product Model--------//**
private static $db = [

        'URLSegment' => 'Varchar',

        'Title' => 'Varchar',

        'Description' => 'HTMLText',

        'ColourSpecial' => 'Varchar',

        'CanBeInscribed' => 'Boolean',

        'ExemptFromCustomerDiscount' => 'Boolean',

        'AvailableForPurchase' => 'Boolean',

        'FreeShipping' => 'Boolean',

        'HideFromRetailSite' => 'Boolean',

    ];

    private static $has_one = [

        'Image' => Image::class,

        'Colour' => ProductColour::class,

    ];

    private static $many_many = [

        'FlowerHolders' => FlowerHolder::class,

        'Categories' => MemorialCategory::class,

        'Filters' => ProductFilter::class

    ];

    private static $has_many = [

        'Variants' => ProductVariant::class

    ];

    private static $owns = [

        'Image'

    ];

    private static $summary_fields = [

        'Image.CMSThumbnail' => 'Image',

        'Title',

        'ListCategories' => 'Categories'

    ];

    private static $defaults = [

        'AvailableForPurchase' => 1

    ];

    private static $table_name = 'BrochureProduct';

    public function ListCategories()

    {

        return DBText::create()->setValue(sprintf(implode(', ', $this->Categories()->map('ID', 'Title')->toArray())));

    }

    public function categoryPageLink()

    {

        $subsite = Subsite::currentSubsite();

        $pages = MemorialCategoryPage::get();

        if ($pages && $pages->exists()) {

            if ($subsite) {

                $pages->filter('SubsiteID', $subsite->ID);

            }else {

                $pages->filter('SubsiteID', 0);

            }

            foreach ($pages as $page) {

                if (strpos(str_replace(' ', '-', strtolower($this->Categories()->Title)), $page->URLSegment) !== false) {

                    return $page->URLSegment;

                }

            }

        }

    }

    public function Link()

    {

        return Controller::join_links(

            Director::absoluteBaseURL(),

            $this->getMemorialPageLink(),

            $this->categoryPageLink(),

            $this->URLSegment

        );

    }

    public function getMemorialPageLink()

    {

        $subsite = Subsite::currentSubsite();

        $page = MemorialsPage::get();

        if ($page && $page->exists()) {

            if ($subsite) {

                $page->filter('SubsiteID', $subsite->ID);

            }else {

                $page->filter('SubsiteID', 0);

            }

            return $page->first()->Link();

        }

    }

    public function onBeforeWrite()

    {

        parent::onBeforeWrite();

        $filter = URLSegmentFilter::create();

        $this->URLSegment = $filter->filter($this->Title);

        if (self::get()->exclude('ID', $this->ID)->find('URLSegment', $this->URLSegment)) {

            $this->URLSegment = $this->URLSegment . '-2';

            if (self::get()->exclude('ID', $this->ID)->find('URLSegment', $this->URLSegment)) {

                $this->URLSegment = ++$this->URLSegment;

            }

        }

    }
**//----Product Filter Model----//**

private static $db = [

        'Title' => 'Varchar',

    ];
**//---template.ss---//**

<section class="section brochure-product-form <% if $RemoveTopMargin %> mt-0 <% end_if %> <% if $RemoveBottomMargin %> mb-0 <% end_if %>">

    <div class="container md:max-w-screen-md brochure-product-form__wrapper">

        <% if not $HideSearchFilter %>

            <% if $Content %>

                <div class="container text-center md:max-w-screen-md memorial__title">

                    <h2>$Content.RAW</h2>

                    <br><br>

                    <form>

                        <% loop $ProductFilter %>

                            <% if $Title = "All Products" %>

                            <label class="checkbox-inline">

                                <input type="checkbox" value="$Title">  $Title

                            </label>

                            <% else %>

                            <label class="checkbox-inline">

                                <input type="checkbox" value="$Title">  $Title

                            </label>

                        <% end_if %>

                        <% end_loop %>

                    </form>

                </div>

            <% end_if %>

           

            <form class="brochure-product-form__form" action="" method="GET">

                <label class="sr-only" for="productSearch">Search products</label>

                <div class="relative w-full">

                    <input class="search-form-border" type="text" name="product" id="productSearch" value="$SearchedParams" placeholder="Find a product">

                <button class="brochure-product-form__btn">

                    Search

                <img src="public/_resources/themes/retail/images/search.png" class="material-symbols-outlined icon-search ml-3"  style="height: 16px; width: 100%;">

                </button>

                </div>

            </form>

        <% end_if %>

    </div>

</section>

<% if $PaginatedBrochureProducts %>

    <section class="section brochure-product">

        <div class="container">

            <ul class="brochure-product__lists">

                <% loop $PaginatedBrochureProducts %>

                    <li class="brochure-product__item">

                        <a href="$Top.Link($URLSegment)"

                           class="flex flex-col items-center text-center">

                           <% if $Image %>

                            <img class="w-full mb-5"

                                 src="$Image.Fill(600, 600).URL"

                                 width="600"

                                 height="600"

                                 alt="">

                            <% else %>

                                <img class="w-full mb-5"

                                src="public/_resources/themes/retail/images/marker-blue.png"

                                width="600"

                                height="600"

                                alt="IMG">

                            <% end_if %>

                            <h3 class="mb-3">$Title</h3>

                            <span class="mb-2">

                                From

                                <% if $Variants %>

                                    <span>

                                        £{$Variants.Sort('Price', 'ASC').First.Price}

                                    </span>

                                <% end_if %>

                            </span>

                            <small>More options available</small>

                        </a>

                    </li>

                <% end_loop %>

            </ul>

        </div>

    </section>

<% end_if %>

Assuming you have a list of products and each product has a ‘size’ attribute, and you are using a function called search:

Sample list of products

products = [
{‘name’: ‘Product A’, ‘size’: ‘Small’},
{‘name’: ‘Product B’, ‘size’: ‘Medium’},
{‘name’: ‘Product C’, ‘size’: ‘Large’},
# Add more products with size information
]

Function to filter products by size

def filter_by_size(product_list, selected_sizes):
return [product for product in product_list if product[‘size’] in selected_sizes]

Function to perform the search with size filtering

def search_and_filter(query, selected_sizes):
# Call your search function, assuming it returns a list of products
search_results = search(query)

# Filter the search results by selected sizes
filtered_results = filter_by_size(search_results, selected_sizes)

return filtered_results

Example usage

search_query = “your_search_query_here”
selected_sizes = [‘Small’, ‘Medium’]

Call the search and filter function

filtered_results = search_and_filter(search_query, selected_sizes)

Display the filtered results

print(“Filtered Results:”)
for product in filtered_results:
print(product)

In this example, the filter_by_size function takes a list of products and a list of selected sizes, and it returns a new list containing only the products that match the selected sizes.

The search_and_filter function calls your existing search function and then filters the results using the filter_by_size function based on the selected sizes.

Adjust the code according to your specific implementation details and the structure of your product data.

You forgot to tell ChatGPT to use PHP.

How can you filter by size if your model does not have anything related to its size?

Furthermore, if your choices are mutually exclusive (as it seems) use radio buttons instead of check boxes.