Max Selectable Options in Checkbox List

Hello,

Is there any way I can limit the Checkbox list with Max selectable options?
I have around 50+ options to select from and I want users to only select any 5 options. After 5 options it should not let the user check any checkbox.

currently, I am just preventing this by using rules.

CheckboxList::make('courses')
      ->label('Select Courses')
      ->options(ShopProduct::all()->whereNotNull('single_course')->pluck('product_name','single_course'))
      ->required()
      ->reactive()
      ->searchable()
      ->columns(3)
      ->gridDirection('row')
      ->extraAttributes(['class'=>'overflow-y-auto h-96 p-2'])
      ->rules([
          fn (Get $get): Closure => function (string $attribute, $value, Closure $fail) use ($get) {
              if (isset($this->product->automation->shop_trigger_automation['action']) && ($this->product->automation->shop_trigger_automation['action'] === 'select_learning_courses')) {
                  if($this->product->automation->shop_trigger_automation['quantity'] != count($value)) {
                      $fail("Please select any {$this->product->automation->shop_trigger_automation['quantity']} courses.");
                  }
              }
          },
      ])


Could anyone please suggest anything? πŸ™‚

Thank you.
Solution
Does combining your Rule with a closure on disableWhen work? The closure could count how many are selected and return true when it's too many.
https://filamentphp.com/docs/3.x/forms/fields/checkbox-list#disabling-specific-options
Was this page helpful?