Beautiful Open-Source Form Builder
Multi select min-max options feature (#772)
Chirag Chhatrala993904a97879
diff --git a/api/app/Http/Requests/AnswerFormRequest.php b/api/app/Http/Requests/AnswerFormRequest.phpindex 29d71252e..6443bdd95 100644--- a/api/app/Http/Requests/AnswerFormRequest.php+++ b/api/app/Http/Requests/AnswerFormRequest.php@@ -118,6 +118,15 @@ class AnswerFormRequest extends FormRequest$propertyId = $property['id'];if (in_array($property['type'], ['multi_select'])) {$rules[] = 'array';++ // Add min/max selection constraints for multi_select+ if (isset($property['min_selection']) && $property['min_selection'] > 0) {+ $rules[] = 'min:' . $property['min_selection'];+ }+ if (isset($property['max_selection']) && $property['max_selection'] > 0) {+ $rules[] = 'max:' . $property['max_selection'];+ }+$this->requestRules[$propertyId . '.*'] = $this->getPropertyRules($property);} else {$rules = array_merge($rules, $this->getPropertyRules($property));@@ -172,12 +181,20 @@ class AnswerFormRequest extends FormRequest$messages = [];foreach ($this->form->properties as $property) {if ($property['type'] == 'date' && isset($property['date_range']) && $property['date_range']) {- $messages[$property['id'] . '.0.required_with'] = 'From date is required';- $messages[$property['id'] . '.1.required_with'] = 'To date is required';- $messages[$property['id'] . '.0.before_or_equal'] = 'From date must be before or equal To date';+ $messages[$property['id'] . '.0.required_with'] = __('validation.from_date_required');+ $messages[$property['id'] . '.1.required_with'] = __('validation.to_date_required');+ $messages[$property['id'] . '.0.before_or_equal'] = __('validation.from_date_before_or_equal');}if ($property['type'] == 'rating') {- $messages[$property['id'] . '.min'] = 'A rating must be selected';+ $messages[$property['id'] . '.min'] = __('validation.rating_min');+ }+ if ($property['type'] == 'multi_select') {+ if (isset($property['min_selection']) && $property['min_selection'] > 0) {+ $messages[$property['id'] . '.min'] = __('validation.select_min', ['min' => $property['min_selection']]);+ }+ if (isset($property['max_selection']) && $property['max_selection'] > 0) {+ $messages[$property['id'] . '.max'] = __('validation.select_max', ['max' => $property['max_selection']]);+ }}}diff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.phpindex af6166746..10cb4953d 100644--- a/api/app/Http/Requests/UserFormRequest.php+++ b/api/app/Http/Requests/UserFormRequest.php@@ -184,6 +184,8 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest// Select / Multi Select field'properties.*.allow_creation' => 'boolean|nullable','properties.*.without_dropdown' => 'boolean|nullable',+ 'properties.*.min_selection' => 'integer|nullable|min:0',+ 'properties.*.max_selection' => 'integer|nullable|min:1',// Advanced Options'properties.*.generates_uuid' => 'boolean|nullable',diff --git a/api/resources/lang/en/validation.php b/api/resources/lang/en/validation.phpindex d5f3aeeb2..5b5963550 100644--- a/api/resources/lang/en/validation.php+++ b/api/resources/lang/en/validation.php@@ -154,4 +154,11 @@ return ['complete_captcha' => 'Please complete the captcha.','yes' => 'Yes','no' => 'No',++ 'from_date_required' => 'From date is required',+ 'to_date_required' => 'To date is required',+ 'from_date_before_or_equal' => 'From date must be before or equal to To date',+ 'rating_min' => 'A rating must be selected',+ 'select_min' => 'Please select at least :min options',+ 'select_max' => 'Please select no more than :max options',];diff --git a/api/tests/Feature/Forms/AnswerFormTest.php b/api/tests/Feature/Forms/AnswerFormTest.phpindex c3c5a1064..4d764ca54 100644--- a/api/tests/Feature/Forms/AnswerFormTest.php+++ b/api/tests/Feature/Forms/AnswerFormTest.php@@ -386,3 +386,194 @@ it('can update form submission if database fields update is set', function () {$this->assertEquals('[email protected]', $submission->data[$emailField['id']]);$this->assertEquals('Test 1', $submission->data[$nameField['id']]);});++it('can submit form with valid multi select min/max constraints', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ // Add multi_select field with constraints+ $multiSelectField = [+ 'id' => 'test_multi_select',+ 'name' => 'Test Multi Select',+ 'type' => 'multi_select',+ 'required' => true,+ 'min_selection' => 2,+ 'max_selection' => 3,+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'Option 1'],+ ['id' => 'option2', 'name' => 'Option 2'],+ ['id' => 'option3', 'name' => 'Option 3'],+ ['id' => 'option4', 'name' => 'Option 4'],+ ]+ ]+ ];++ $form->properties = array_merge($form->properties, [$multiSelectField]);+ $form->save();++ // Submit valid data (2 selections, within min=2, max=3)+ $formData = $this->generateFormSubmissionData($form, [+ 'test_multi_select' => ['Option 1', 'Option 2']+ ]);++ $this->postJson(route('forms.answer', $form->slug), $formData)+ ->assertSuccessful()+ ->assertJson([+ 'type' => 'success',+ 'message' => 'Form submission saved.',+ ]);+});++it('rejects multi select submission below minimum selection', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ // Add multi_select field with min constraint+ $multiSelectField = [+ 'id' => 'test_multi_select_min',+ 'name' => 'Test Multi Select Min',+ 'type' => 'multi_select',+ 'required' => true,+ 'min_selection' => 3,+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'Option A'],+ ['id' => 'option2', 'name' => 'Option B'],+ ['id' => 'option3', 'name' => 'Option C'],+ ['id' => 'option4', 'name' => 'Option D'],+ ]+ ]+ ];++ $form->properties = array_merge($form->properties, [$multiSelectField]);+ $form->save();++ // Submit invalid data (only 2 selections, but min=3)+ $formData = $this->generateFormSubmissionData($form, [+ 'test_multi_select_min' => ['Option A', 'Option B']+ ]);++ $this->postJson(route('forms.answer', $form->slug), $formData)+ ->assertStatus(422)+ ->assertJson([+ 'message' => 'Please select at least 3 options',+ ]);+});++it('rejects multi select submission above maximum selection', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ // Add multi_select field with max constraint+ $multiSelectField = [+ 'id' => 'test_multi_select_max',+ 'name' => 'Test Multi Select Max',+ 'type' => 'multi_select',+ 'required' => true,+ 'max_selection' => 2,+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'Choice 1'],+ ['id' => 'option2', 'name' => 'Choice 2'],+ ['id' => 'option3', 'name' => 'Choice 3'],+ ['id' => 'option4', 'name' => 'Choice 4'],+ ]+ ]+ ];++ $form->properties = array_merge($form->properties, [$multiSelectField]);+ $form->save();++ // Submit invalid data (3 selections, but max=2)+ $formData = $this->generateFormSubmissionData($form, [+ 'test_multi_select_max' => ['Choice 1', 'Choice 2', 'Choice 3']+ ]);++ $this->postJson(route('forms.answer', $form->slug), $formData)+ ->assertStatus(422)+ ->assertJson([+ 'message' => 'Please select no more than 2 options',+ ]);+});++it('accepts multi select submission at exact min/max boundaries', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ // Add multi_select field with both constraints (exact boundary)+ $multiSelectField = [+ 'id' => 'test_multi_select_boundary',+ 'name' => 'Test Multi Select Boundary',+ 'type' => 'multi_select',+ 'required' => true,+ 'min_selection' => 2,+ 'max_selection' => 2, // Exact constraint - must select exactly 2+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'First'],+ ['id' => 'option2', 'name' => 'Second'],+ ['id' => 'option3', 'name' => 'Third'],+ ]+ ]+ ];++ $form->properties = array_merge($form->properties, [$multiSelectField]);+ $form->save();++ // Submit valid data (exactly 2 selections)+ $formData = $this->generateFormSubmissionData($form, [+ 'test_multi_select_boundary' => ['First', 'Second']+ ]);++ $this->postJson(route('forms.answer', $form->slug), $formData)+ ->assertSuccessful()+ ->assertJson([+ 'type' => 'success',+ 'message' => 'Form submission saved.',+ ]);+});++it('accepts multi select with only min constraint', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ // Add multi_select field with only min constraint (no max limit)+ $multiSelectField = [+ 'id' => 'test_multi_select_min_only',+ 'name' => 'Test Multi Select Min Only',+ 'type' => 'multi_select',+ 'required' => true,+ 'min_selection' => 2,+ // No max_selection - unlimited selections allowed+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'One'],+ ['id' => 'option2', 'name' => 'Two'],+ ['id' => 'option3', 'name' => 'Three'],+ ['id' => 'option4', 'name' => 'Four'],+ ['id' => 'option5', 'name' => 'Five'],+ ]+ ]+ ];++ $form->properties = array_merge($form->properties, [$multiSelectField]);+ $form->save();++ // Submit valid data (5 selections, min=2, no max limit)+ $formData = $this->generateFormSubmissionData($form, [+ 'test_multi_select_min_only' => ['One', 'Two', 'Three', 'Four', 'Five']+ ]);++ $this->postJson(route('forms.answer', $form->slug), $formData)+ ->assertSuccessful()+ ->assertJson([+ 'type' => 'success',+ 'message' => 'Form submission saved.',+ ]);+});diff --git a/api/tests/Feature/Forms/FormTest.php b/api/tests/Feature/Forms/FormTest.phpindex 6a109295e..fbc09398b 100644--- a/api/tests/Feature/Forms/FormTest.php+++ b/api/tests/Feature/Forms/FormTest.php@@ -298,3 +298,121 @@ it('can update form with custom slug when self hosted', function () {'slug' => 'updated-custom-slug']);});++it('can create form with multi select min/max selection constraints', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ // Add multi_select field with min/max constraints+ $form->properties = array_merge($form->properties, [+ [+ 'id' => 'multi_select_field',+ 'name' => 'Multi Select Field',+ 'type' => 'multi_select',+ 'required' => true,+ 'min_selection' => 2,+ 'max_selection' => 4,+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'Option 1'],+ ['id' => 'option2', 'name' => 'Option 2'],+ ['id' => 'option3', 'name' => 'Option 3'],+ ['id' => 'option4', 'name' => 'Option 4'],+ ['id' => 'option5', 'name' => 'Option 5'],+ ]+ ]+ ]+ ]);++ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());++ $response = $this->postJson(route('open.forms.store', $formData))+ ->assertSuccessful()+ ->assertJson([+ 'type' => 'success',+ 'message' => 'Form created.',+ ]);++ // Verify the constraints are saved+ $createdForm = \App\Models\Forms\Form::find($response->json('form.id'));+ $multiSelectField = collect($createdForm->properties)->firstWhere('id', 'multi_select_field');++ expect($multiSelectField)->not->toBeNull('Multi select field should exist');+ expect($multiSelectField)->toHaveKey('min_selection');+ expect($multiSelectField)->toHaveKey('max_selection');+ expect($multiSelectField['min_selection'])->toBe('2');+ expect($multiSelectField['max_selection'])->toBe('4');+});++it('can update form with multi select min/max selection constraints', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ // Update form to add multi_select field with constraints+ $form->properties = array_merge($form->properties, [+ [+ 'id' => 'updated_multi_select',+ 'name' => 'Updated Multi Select',+ 'type' => 'multi_select',+ 'required' => false,+ 'min_selection' => 1,+ 'max_selection' => 3,+ 'multi_select' => [+ 'options' => [+ ['id' => 'opt1', 'name' => 'Choice 1'],+ ['id' => 'opt2', 'name' => 'Choice 2'],+ ['id' => 'opt3', 'name' => 'Choice 3'],+ ]+ ]+ ]+ ]);++ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());++ $this->putJson(route('open.forms.update', $form->id), $formData)+ ->assertSuccessful()+ ->assertJson([+ 'type' => 'success',+ 'message' => 'Form updated.',+ ]);++ // Verify the constraints are updated correctly+ $form->refresh();+ $multiSelectField = collect($form->properties)->firstWhere('id', 'updated_multi_select');++ expect($multiSelectField['min_selection'])->toBe(1);+ expect($multiSelectField['max_selection'])->toBe(3);+});++it('validates min/max selection constraints format in form creation', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ // Add invalid constraints (negative min, zero max)+ $form->properties = array_merge($form->properties, [+ [+ 'id' => 'invalid_field',+ 'name' => 'Invalid Field',+ 'type' => 'multi_select',+ 'min_selection' => -1, // Invalid: negative+ 'max_selection' => 0, // Invalid: zero+ 'multi_select' => [+ 'options' => [+ ['id' => 'option1', 'name' => 'Option 1'],+ ]+ ]+ ]+ ]);++ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());++ $this->postJson(route('open.forms.store', $formData))+ ->assertUnprocessable()+ ->assertJsonValidationErrors([+ 'properties.14.min_selection',+ 'properties.14.max_selection'+ ]);+});diff --git a/client/components/forms/core/FlatSelectInput.vue b/client/components/forms/core/FlatSelectInput.vueindex ed2b74970..db9e88281 100644--- a/client/components/forms/core/FlatSelectInput.vue+++ b/client/components/forms/core/FlatSelectInput.vue@@ -88,6 +88,24 @@<template #help><slot name="help" /></template>++ <template+ v-if="multiple && (minSelection || maxSelection) && selectedCount > 0"+ #bottom_after_help+ >+ <small :class="theme.default.help">+ <span v-if="minSelection && maxSelection">+ {{ selectedCount }} of {{ minSelection }}-{{ maxSelection }}+ </span>+ <span v-else-if="minSelection">+ {{ selectedCount }} selected (min {{ minSelection }})+ </span>+ <span v-else-if="maxSelection">+ {{ selectedCount }}/{{ maxSelection }} selected+ </span>+ </small>+ </template>+<template #error><slot name="error" /></template>@@ -117,6 +135,8 @@ export default {disableOptions: { type: Array, default: () => [] },disableOptionsTooltip: { type: String, default: "Not allowed" },clearable: { type: Boolean, default: false },+ minSelection: { type: Number, default: null },+ maxSelection: { type: Number, default: null }},setup(props, context) {return {@@ -136,10 +156,18 @@ export default {return this.options.find(option => option[this.optionKey] === this.compVal) || null},+ selectedCount() {+ if (!this.multiple || !Array.isArray(this.compVal)) return 0+ return this.compVal.length+ },+ maxSelectionReached() {+ if (!this.multiple || !this.maxSelection) return false+ return this.selectedCount >= this.maxSelection+ },},methods: {onSelect(value) {- if (this.disabled || this.disableOptions.includes(value)) {+ if (this.disabled || this.disableOptions.includes(value) || this.isOptionDisabled(value)) {return}@@ -172,6 +200,12 @@ export default {}return this.compVal === value},+ isOptionDisabled(value) {+ if (!this.multiple || !this.maxSelection) return false+ // Allow deselection of already selected options+ const isSelected = this.isSelected(value)+ return !isSelected && this.maxSelectionReached+ },getOptionName(option) {return option ? option[this.displayKey] : ''},diff --git a/client/components/forms/core/SelectInput.vue b/client/components/forms/core/SelectInput.vueindex 5915dd5b3..b69df9554 100644--- a/client/components/forms/core/SelectInput.vue+++ b/client/components/forms/core/SelectInput.vue@@ -27,6 +27,8 @@:help-position="helpPosition":remote="remote":dropdown-class="dropdownClass"+ :min-selection="minSelection"+ :max-selection="maxSelection"@update-options="updateOptions"@update:model-value="updateModelValue">@@ -94,6 +96,23 @@<slot name="help" /></template>+ <template+ v-if="multiple && (minSelection || maxSelection) && selectedCount > 0"+ #bottom_after_help+ >+ <small :class="theme.default.help">+ <span v-if="minSelection && maxSelection">+ {{ selectedCount }} of {{ minSelection }}-{{ maxSelection }}+ </span>+ <span v-else-if="minSelection">+ {{ selectedCount }} selected (min {{ minSelection }})+ </span>+ <span v-else-if="maxSelection">+ {{ selectedCount }}/{{ maxSelection }} selected+ </span>+ </small>+ </template>+<template #error><slot name="error" /></template>@@ -122,7 +141,9 @@ export default {clearable: { type: Boolean, default: false },allowCreation: { type: Boolean, default: false },dropdownClass: { type: String, default: 'w-full' },- remote: { type: Function, default: null }+ remote: { type: Function, default: null },+ minSelection: { type: Number, default: null },+ maxSelection: { type: Number, default: null }},setup(props, context) {return {@@ -138,7 +159,11 @@ export default {computed: {finalOptions() {return this.options.concat(this.additionalOptions)- }+ },+ selectedCount() {+ if (!this.multiple || !Array.isArray(this.selectedValues)) return 0+ return this.selectedValues.length+ },},watch: {compVal: {diff --git a/client/components/forms/core/components/VSelect.vue b/client/components/forms/core/components/VSelect.vueindex 86ed6af56..7288967cc 100644--- a/client/components/forms/core/components/VSelect.vue+++ b/client/components/forms/core/components/VSelect.vue@@ -172,8 +172,12 @@theme.SelectInput.spacing.horizontal,theme.SelectInput.spacing.vertical,{ 'pr-9': multiple},+ {+ 'opacity-50 cursor-not-allowed': disabledOptionsMap[item[optionKey]],+ 'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-900': !disabledOptionsMap[item[optionKey]]+ }]"- class="text-neutral-900 dark:text-neutral-50 select-none relative cursor-pointer group hover:bg-neutral-100 dark:hover:bg-neutral-900 rounded-sm focus:outline-hidden"+ class="text-neutral-900 dark:text-neutral-50 select-none relative group rounded-sm focus:outline-hidden"@click="select(item)"><slot@@ -254,7 +258,9 @@ export default {}},allowCreation: { type: Boolean, default: false },- disabled: { type: Boolean, default: false }+ disabled: { type: Boolean, default: false },+ minSelection: { type: Number, default: null },+ maxSelection: { type: Number, default: null }},emits: ['update:modelValue', 'update-options', 'focus', 'blur'],data () {@@ -302,6 +308,24 @@ export default {},isEmpty () {return this.multiple ? !this.modelValue || this.modelValue.length === 0 : !this.modelValue+ },+ selectedCount () {+ if (!this.multiple || !Array.isArray(this.modelValue)) return 0+ return this.modelValue.length+ },+ maxSelectionReached () {+ if (!this.multiple || !this.maxSelection) return false+ return this.selectedCount >= this.maxSelection+ },+ disabledOptionsMap () {+ if (!this.multiple || !this.maxSelection || !this.data) return {}++ const map = {}+ for (const item of this.data) {+ const isSelected = this.isSelected(item)+ map[item[this.optionKey]] = !isSelected && this.maxSelectionReached+ }+ return map}},watch: {@@ -359,6 +383,11 @@ export default {}},select (value) {+ // Check if option is disabled (similar to how we check for input disabled)+ if (this.disabledOptionsMap[value[this.optionKey]]) {+ return+ }+if (!this.multiple) {// Close after selectthis.toggleDropdown()diff --git a/client/components/open/forms/OpenFormField.vue b/client/components/open/forms/OpenFormField.vueindex 134cc18b4..aa7bdaa4a 100644--- a/client/components/open/forms/OpenFormField.vue+++ b/client/components/open/forms/OpenFormField.vue@@ -365,6 +365,12 @@ function inputProperties(field) {inputProperties.multiple = (field.type === 'multi_select')inputProperties.allowCreation = (field.allow_creation === true)inputProperties.searchable = (inputProperties.options.length > 4)++ // Add min/max selection constraints for multi_select+ if (field.type === 'multi_select') {+ inputProperties.minSelection = field.min_selection || null+ inputProperties.maxSelection = field.max_selection || null+ }} else if (field.type === 'date') {inputProperties.dateFormat = field.date_formatinputProperties.timeFormat = field.time_formatdiff --git a/client/components/open/forms/fields/components/FieldOptions.vue b/client/components/open/forms/fields/components/FieldOptions.vueindex d5c9fecb5..fcf1fad4e 100644--- a/client/components/open/forms/fields/components/FieldOptions.vue+++ b/client/components/open/forms/fields/components/FieldOptions.vue@@ -328,6 +328,41 @@help="Options won't be in a dropdown anymore, but will all be visible"@update:model-value="onFieldWithoutDropdownChange"/>++ <!-- Min/Max Selection Constraints for multi_select only -->+ <template v-if="field.type === 'multi_select'">+ <div class="flex gap-1">+ <text-input+ name="min_selection"+ native-type="number"+ :min="0"+ class="flex-1"+ :form="field"+ label="Min. required"+ placeholder="1"+ @update:model-value="onFieldMinSelectionChange"+ />+ <text-input+ name="max_selection"+ native-type="number"+ :min="1"+ class="flex-1"+ :form="field"+ label="Max. allowed"+ placeholder="2"+ @update:model-value="onFieldMaxSelectionChange"+ />+ <UButton+ icon="i-heroicons-backspace"+ color="neutral"+ variant="outline"+ class="self-end mb-1"+ title="Clear both values"+ @click="clearMinMaxSelection"+ />+ </div>+ <InputHelp help="Set min/max options allowed, or leave empty for unlimited. Save form to test changes." />+ </template></div><!-- Customization - Placeholder, Prefill, Relabel, Field Help -->@@ -904,6 +939,16 @@ export default {if(!this.field.max_char_limit) {this.field.show_char_limit = false}+ },+ onFieldMinSelectionChange(val) {+ this.field.min_selection = val ? parseInt(val) : null+ },+ onFieldMaxSelectionChange(val) {+ this.field.max_selection = val ? parseInt(val) : null+ },+ clearMinMaxSelection() {+ this.field.min_selection = null+ this.field.max_selection = null}}}