Skip to content

Beautiful Open-Source Form Builder

Add multi-delete functionality for form submissions (#851)

Chirag Chhatralafeef23bd843f
diff --git a/api/app/Http/Controllers/Forms/FormSubmissionController.php b/api/app/Http/Controllers/Forms/FormSubmissionController.php
index 3b91115de..4278e6a63 100644
--- a/api/app/Http/Controllers/Forms/FormSubmissionController.php
+++ b/api/app/Http/Controllers/Forms/FormSubmissionController.php
@@ -15,6 +15,7 @@ use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Vinkla\Hashids\Facades\Hashids;
+use Illuminate\Http\Request;
class FormSubmissionController extends Controller
{
@@ -118,4 +119,29 @@ class FormSubmissionController extends Controller
'message' => 'Record successfully removed.',
]);
}
+
+ public function destroyMulti(Request $request, $id)
+ {
+ $request->validate([
+ 'submissionIds' => 'required|array',
+ 'submissionIds.*' => 'required|integer',
+ 'submissionIds.*' => 'exists:form_submissions,id',
+ ]);
+
+ $form = Form::findOrFail((int) $id);
+ $this->authorize('delete', $form);
+
+ $submissionIds = $request->submissionIds;
+ $form->submissions()
+ ->whereIn('id', $submissionIds)
+ ->chunk(100, function ($submissions) {
+ foreach ($submissions as $submission) {
+ $submission->delete();
+ }
+ });
+
+ return $this->success([
+ 'message' => 'Records successfully removed.',
+ ]);
+ }
}
diff --git a/api/routes/api.php b/api/routes/api.php
index 1de621533..6d43732c0 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -161,6 +161,7 @@ Route::group(['middleware' => 'auth.multi'], function () {
->withoutMiddleware(['auth.multi'])
->name('file');
Route::delete('/{submission_id}', [FormSubmissionController::class, 'destroy'])->name('destroy');
+ Route::post('/multi', [FormSubmissionController::class, 'destroyMulti'])->name('destroy-multi');
});
// Form Admin tool
diff --git a/api/tests/Feature/Submissions/SubmissionTest.php b/api/tests/Feature/Submissions/SubmissionTest.php
new file mode 100644
index 000000000..9c488b198
--- /dev/null
+++ b/api/tests/Feature/Submissions/SubmissionTest.php
@@ -0,0 +1,47 @@
+<?php
+
+it('can delete form submission', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $formData = $this->generateFormSubmissionData($form, ['text' => 'John']);
+ $this->postJson(route('forms.answer', $form->slug), $formData)
+ ->assertSuccessful()
+ ->assertJson([
+ 'type' => 'success',
+ 'message' => 'Form submission saved.',
+ ]);
+ $submission = $form->submissions()->first();
+ $this->deleteJson(route('open.forms.submissions.destroy', ['id' => $form->id, 'submission_id' => $submission->id]))
+ ->assertSuccessful()
+ ->assertJson([
+ 'type' => 'success',
+ 'message' => 'Record successfully removed.',
+ ]);
+ expect($form->submissions()->count())->toBe(0);
+});
+
+it('can delete multiple form submissions', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ // Create 5 submissions
+ for ($i = 1; $i <= 5; $i++) {
+ $form->submissions()->create();
+ }
+
+ // Get 2 random submission ids
+ $submissionIds = $form->submissions()->pluck('id')->random(2)->toArray();
+
+ // Delete 2 submissions
+ $this->postJson(route('open.forms.submissions.destroy-multi', ['id' => $form->id]), ['submissionIds' => $submissionIds])
+ ->assertSuccessful()
+ ->assertJson([
+ 'type' => 'success',
+ 'message' => 'Records successfully removed.',
+ ]);
+
+ // Check if the remaining submissions are still there
+ expect($form->submissions()->count())->toBe(3);
+});
diff --git a/client/api/forms.js b/client/api/forms.js
index 7fc87f1cc..63e9a7c57 100644
--- a/client/api/forms.js
+++ b/client/api/forms.js
@@ -24,6 +24,7 @@ export const formsApi = {
get: (slug, submissionId, options) => apiService.get(`/forms/${slug}/submissions/${submissionId}`, options),
update: (formId, submissionId, data) => apiService.put(`/open/forms/${formId}/submissions/${submissionId}`, data),
delete: (formId, submissionId) => apiService.delete(`/open/forms/${formId}/submissions/${submissionId}`),
+ deleteMulti: (formId, submissionIds) => apiService.post(`/open/forms/${formId}/submissions/multi`, { submissionIds }),
export: (formId, data) => apiService.post(`/open/forms/${formId}/submissions/export`, data),
answer: (slug, data, options) => apiService.post(`/forms/${slug}/answer`, data, options)
},
diff --git a/client/components/open/forms/components/FormSubmissions.vue b/client/components/open/forms/components/FormSubmissions.vue
index b3e88b0c8..1b1424e06 100644
--- a/client/components/open/forms/components/FormSubmissions.vue
+++ b/client/components/open/forms/components/FormSubmissions.vue
@@ -9,6 +9,7 @@
:form="form"
@deleted="onDeleteRecord"
@updated="(submission)=>onUpdateRecord(submission)"
+ @multi-delete="onDeleteMultiRecord"
/>
<!-- Submissions Table Skeleton -->
@@ -117,4 +118,9 @@ const onDeleteRecord = (submission) => {
recordStore.remove(submission)
}
+const onDeleteMultiRecord = (submissionIds) => {
+ submissionIds.forEach(id => {
+ recordStore.remove(id)
+ })
+}
</script>
diff --git a/client/components/open/tables/OpenTable.vue b/client/components/open/tables/OpenTable.vue
index 6fb1f325f..888700fa6 100644
--- a/client/components/open/tables/OpenTable.vue
+++ b/client/components/open/tables/OpenTable.vue
@@ -33,6 +33,16 @@
:table-state="tableState"
/>
+ <UButton
+ v-if="canModify && selectedIds.length > 0"
+ size="sm"
+ color="error"
+ variant="outline"
+ :label="`Delete (${selectedIds.length})`"
+ :loading="multiDeleteLoading"
+ @click="onDeleteMultiClick"
+ />
+
<UButton
size="sm"
color="neutral"
@@ -53,6 +63,7 @@
<UTable
v-if="form"
ref="table"
+ v-model:row-selection="rowSelection"
:columns="allColumns"
:column-visibility="columnVisibility"
:column-pinning="columnPinning"
@@ -68,6 +79,25 @@
td: 'px-3 py-2 overflow-hidden data-[pinned=left]:bg-white data-[pinned=left]:border-t data-[pinned=left]:border-r data-[pinned=left]:border-neutral-200 border-r',
}"
>
+ <template #select-header="{ table }">
+ <div class="flex items-center justify-center" :style="{ width: '45px' }">
+ <UCheckbox
+ :model-value="table?.getIsSomeRowsSelected?.() ? 'indeterminate' : (table?.getIsAllRowsSelected?.() || false)"
+ @update:model-value="() => table?.toggleAllRowsSelected?.()"
+ :disabled="filteredTableData.length === 0"
+ />
+ </div>
+ </template>
+
+ <template #select-cell="{ row }">
+ <div class="flex items-center justify-center" :style="{ width: '30px' }">
+ <UCheckbox
+ :model-value="row?.getIsSelected?.() || false"
+ @update:model-value="() => row?.toggleSelected?.()"
+ />
+ </div>
+ </template>
+
<template v-for="col in tableColumns" :key="`${col.id}-header`" #[`${col.id}-header`]="{ column }">
<TableHeader
:column="column"
@@ -144,21 +174,24 @@ const props = defineProps({
},
})
-defineEmits(["updated", "deleted"])
+const emit = defineEmits(["updated", "deleted", "multi-delete"])
// Get workspace for table state
const { current: workspace } = useCurrentWorkspace()
+// Check if the user can modify the table
+const canModify = computed(() => (workspace && !workspace.is_readonly))
+
// Initialize table state (includes preferences internally)
const tableState = useTableState(
computed(() => props.form),
- workspace && !workspace.is_readonly
+ canModify.value
)
const { tableColumns: allColumns, columnVisibility, columnPinning, columnSizing, columnWrapping, handleColumnResize: handleColumnResizeState } = tableState
const tableColumns = computed(() => {
- return allColumns.value.filter(column => column.id !== 'actions')
+ return allColumns.value.filter(column => !['actions', 'select'].includes(column.id))
})
const fieldComponents = {
@@ -192,6 +225,40 @@ const maxHeight = ref('800px') // fallback default
const search = ref("")
const debouncedSearch = refDebounced(search, 300)
const selectedStatus = ref('all')
+const alert = useAlert()
+
+// Table row selection
+const rowSelection = ref({})
+const multiDeleteLoading = ref(false)
+const selectedIds = computed(() => {
+ return table.value?.tableApi?.getFilteredSelectedRowModel()?.rows.map(row => row.original.id) || []
+})
+const clearSelection = () => {
+ rowSelection.value = {}
+}
+const onDeleteMultiClick = () => {
+ alert.confirm(`Do you really want to delete selected ${selectedIds.value.length} record${selectedIds.value.length > 1 ? 's' : ''}?`, deleteMultiRecord)
+}
+const deleteMultiRecord = () => {
+ multiDeleteLoading.value = true
+ formsApi.submissions.deleteMulti(props.form.id, selectedIds.value)
+ .then((data) => {
+ multiDeleteLoading.value = false
+ clearSelection()
+ if (data.type === "success") {
+ emit('multi-delete', selectedIds.value)
+ alert.success(data.message)
+ } else {
+ alert.error("Something went wrong!")
+ }
+ })
+ .catch((error) => {
+ multiDeleteLoading.value = false
+ clearSelection()
+ alert.error(error.data.message)
+ })
+}
+
const statusList = [
{ label: 'All', value: 'all' },
diff --git a/client/composables/components/tables/useTableState.js b/client/composables/components/tables/useTableState.js
index 884cd5ea4..2eebc5a48 100644
--- a/client/composables/components/tables/useTableState.js
+++ b/client/composables/components/tables/useTableState.js
@@ -311,8 +311,22 @@ export function useTableState(form, withActions = false) {
})
}
- // Add actions column if workspace is not readonly
+ // Add actions columns
if (import.meta.client && withActions) {
+ cols.unshift({
+ id: 'select',
+ accessorKey: 'select',
+ header: '',
+ enableResizing: false,
+ size: 40,
+ meta: {
+ class: {
+ th: 'bg-transparent',
+ td: 'backdrop-blur-xs bg-white/70'
+ }
+ }
+ })
+
cols.push({
id: 'actions',
accessorKey: 'actions',
@@ -323,7 +337,7 @@ export function useTableState(form, withActions = false) {
class: {
th: 'bg-transparent',
td: 'backdrop-blur-xs bg-white/70'
- }
+ }
}
})
}