Formulare: visueller Baukasten, CSV-Auswahl, Einbindung unter Beiträgen
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m59s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m5s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m11s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m6s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 3m2s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m3s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m37s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m39s
CI / Build-Artefakte aktuell (pull_request) Failing after 52s

- Visueller Formularbaukasten im Portal (/redaktion/formulare/{id}): Formular
  wie ausgefüllt, Bezeichnungen/Optionen/Hinweise direkt bearbeiten, Ziehen
  und Ablegen aus der Palette, Pflicht/Breite in der Werkzeugleiste,
  Einstellungen und Bedingungen in der Seitenleiste, Vorschau mit Bedingungen
- Admin: Felder-Reiter führt in den Baukasten; nach dem Anlegen direkt dorthin
- CSV: in der Formularliste, im Redaktionsbereich und für ausgewählte Einsendungen
- Neuigkeiten: Formular unter dem Beitrag (über den Pagebuilder-Block, ohne
  Abhängigkeit vom Formular-Plugin)
- Kein Menüpunkt „Formulare“ im Portal; Redaktionsbereich „Formulare“

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 09:35:39 +00:00
parent 11123fecc0
commit 435960725d
139 changed files with 1735 additions and 432 deletions

View file

@ -2,6 +2,7 @@
import { computed } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import { CircleCheck, EyeOff, LoaderCircle, Paperclip, Send, X } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
@ -14,6 +15,8 @@ import NativeSelect from '@/components/NativeSelect.vue';
const props = defineProps({
form: { type: Object, required: true },
compact: { type: Boolean, default: false },
// Vorschau im Baukasten: nichts wird gesendet.
preview: { type: Boolean, default: false },
});
const page = usePage();
@ -76,6 +79,12 @@ function removeFile(field, index) {
}
function submit() {
if (props.preview) {
toast.info('Vorschau – es wird nichts gesendet.');
return;
}
const visibleKeys = new Set(visibleFields.value.map((f) => f.key));
data.transform((values) => ({

View file

@ -0,0 +1,172 @@
<script setup>
import { computed, inject } from 'vue';
import { Asterisk, Calendar, ChevronDown, Copy, GitBranch, GripVertical, Paperclip, Plus, Trash2, X } from '@lucide/vue';
import { fieldTypes, layoutTypes, operators, optionTypes } from '../../lib/fields';
/**
* Ein Feld im Baukasten – dargestellt wie im fertigen Formular.
* Bezeichnung, Hinweis und Auswahlmöglichkeiten werden direkt hier bearbeitet.
*/
const props = defineProps({
field: { type: Object, required: true },
index: { type: Number, required: true },
});
const builder = inject('forms:builder');
const selected = computed(() => builder.selectedId.value === props.field._id);
const hasError = computed(() => builder.errorIndex.value === props.index);
const isLayout = computed(() => layoutTypes.includes(props.field.type));
const d = computed(() => props.field.data);
const conditionText = computed(() => {
if (!d.value.condition_field) return null;
const other = builder.fields.find((f) => f.data.key === d.value.condition_field);
const label = other?.data.label ?? d.value.condition_field;
const op = operators[d.value.condition_operator ?? 'equals'];
return ['filled', 'empty'].includes(d.value.condition_operator) ? `${label} ${op}` : `${label} ${op} „${d.value.condition_value ?? ''}“`;
});
function addOption() {
d.value.options = [...(d.value.options ?? []), `Option ${(d.value.options?.length ?? 0) + 1}`];
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${d.value.options.length - 1}"]`)?.select());
}
function removeOption(i) {
d.value.options = d.value.options.filter((_, index) => index !== i);
}
function optionKeydown(event, i) {
if (event.key === 'Enter') {
event.preventDefault();
d.value.options.splice(i + 1, 0, '');
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${i + 1}"]`)?.focus());
} else if (event.key === 'Backspace' && d.value.options[i] === '' && d.value.options.length > 1) {
event.preventDefault();
removeOption(i);
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${Math.max(0, i - 1)}"]`)?.focus());
}
}
// Unauffällige Eingabefelder, die wie normaler Text aussehen
const inline = 'w-full min-w-0 rounded-sm bg-transparent outline-none placeholder:text-muted-foreground/60 focus:bg-brand-soft/40';
// Bezeichnung nur so breit wie ihr Text – das Pflicht-Sternchen steht direkt dahinter.
const labelInput = 'field-sizing-content min-w-6 max-w-full rounded-sm bg-transparent outline-none placeholder:text-muted-foreground/60 focus:bg-brand-soft/40';
const fake = 'flex h-9 w-full items-center rounded-md border border-input bg-card px-3 text-sm text-muted-foreground shadow-xs';
</script>
<template>
<div
class="group relative rounded-md p-3 outline-offset-2 transition-[outline-color]"
:class="[
field.data.width === 'half' && !isLayout ? '' : '@xl:col-span-2',
selected ? 'bg-brand-soft/30 outline-2 outline-brand-500' : hasError ? 'outline-2 outline-destructive' : 'outline-1 outline-transparent hover:outline-brand-300',
]"
:data-field-id="field._id"
@click.stop="builder.select(field._id)"
>
<!-- Werkzeugleiste -->
<div class="absolute -top-3.5 right-2 z-10 items-center gap-0.5 rounded-md border bg-card px-1 py-0.5 text-xs shadow-sm" :class="selected ? 'flex' : 'hidden group-hover:flex'" @click.stop>
<span class="fb-handle flex cursor-grab items-center gap-1 px-1 py-0.5 font-medium text-muted-foreground active:cursor-grabbing" title="Ziehen zum Verschieben">
<GripVertical class="size-3.5" />
<component :is="fieldTypes[field.type].icon" class="size-3.5" />
{{ builder.types[field.type] }}
</span>
<template v-if="!isLayout">
<span class="mx-0.5 h-4 w-px bg-border" />
<button
type="button"
class="flex h-6 items-center gap-1 rounded px-1.5"
:class="d.required ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
:aria-pressed="!!d.required"
title="Pflichtfeld"
@click="d.required = !d.required"
>
<Asterisk class="size-3.5" /> Pflicht
</button>
<button type="button" class="h-6 rounded px-1.5 text-muted-foreground hover:bg-accent" :title="d.width === 'half' ? 'Volle Breite' : 'Halbe Breite'" @click="d.width = d.width === 'half' ? 'full' : 'half'">
{{ d.width === 'half' ? '½' : '1/1' }}
</button>
</template>
<span class="mx-0.5 h-4 w-px bg-border" />
<button type="button" class="grid size-6 place-items-center rounded hover:bg-accent" title="Duplizieren" @click="builder.duplicate(field._id)"><Copy class="size-3.5" /></button>
<button type="button" class="grid size-6 place-items-center rounded text-destructive hover:bg-destructive/10" title="Entfernen" @click="builder.remove(field._id)"><Trash2 class="size-3.5" /></button>
</div>
<p v-if="conditionText" class="mb-1.5 inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-[11px] text-amber-800 dark:bg-amber-900/50 dark:text-amber-200">
<GitBranch class="size-3" /> Nur wenn {{ conditionText }}
</p>
<!-- Gestaltung -->
<input v-if="field.type === 'heading'" v-model="d.text" :class="[inline, 'text-lg font-semibold']" placeholder="Zwischenüberschrift" aria-label="Zwischenüberschrift" />
<textarea
v-else-if="field.type === 'paragraph'"
v-model="d.text"
:class="[inline, 'field-sizing-content resize-none text-sm leading-relaxed text-muted-foreground']"
rows="1"
placeholder="Hinweistext"
aria-label="Hinweistext"
/>
<!-- Kontrollkästchen: Bezeichnung neben dem Kasten -->
<div v-else-if="field.type === 'checkbox'" class="flex items-start gap-2.5">
<span class="mt-0.5 size-4 shrink-0 rounded-[4px] border border-input bg-card" />
<input v-model="d.label" :class="[labelInput, 'text-sm']" placeholder="Text neben dem Kästchen" aria-label="Bezeichnung" />
<span v-if="d.required" class="text-destructive">*</span>
</div>
<!-- Eingabefelder -->
<div v-else class="grid gap-1.5">
<div class="flex items-center gap-0.5 text-[13px] font-medium">
<input v-model="d.label" :class="labelInput" placeholder="Bezeichnung" aria-label="Bezeichnung" />
<span v-if="d.required" class="text-destructive">*</span>
</div>
<div v-if="field.type === 'textarea'" class="rounded-md border border-input bg-card shadow-xs" :style="{ height: `${(d.rows ?? 4) * 1.5 + 1}rem` }">
<input v-model="d.placeholder" class="w-full bg-transparent px-3 py-2 text-sm outline-none placeholder:text-muted-foreground/50" placeholder="Platzhalter (optional)" aria-label="Platzhalter" />
</div>
<div v-else-if="field.type === 'select'" class="grid gap-1.5">
<div :class="[fake, 'justify-between']">Bitte wählen … <ChevronDown class="size-4" /></div>
<div v-if="selected" class="grid gap-1 rounded-md border border-dashed p-2">
<p class="text-xs text-muted-foreground">Auswahlmöglichkeiten</p>
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-2">
<span class="w-5 text-right text-xs text-muted-foreground">{{ i + 1 }}.</span>
<input v-model="d.options[i]" :data-option="`${field._id}-${i}`" :class="[inline, 'text-sm']" placeholder="Auswahlmöglichkeit" @keydown="optionKeydown($event, i)" />
<button type="button" class="grid size-6 place-items-center rounded text-muted-foreground hover:bg-accent" title="Entfernen" @click.stop="removeOption(i)"><X class="size-3.5" /></button>
</div>
<button type="button" class="inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click.stop="addOption"><Plus class="size-3.5" /> Auswahlmöglichkeit</button>
</div>
</div>
<div v-else-if="optionTypes.includes(field.type)" class="grid gap-1.5">
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-2.5">
<span class="size-4 shrink-0 border border-input bg-card" :class="field.type === 'radio' ? 'rounded-full' : 'rounded-[4px]'" />
<input v-model="d.options[i]" :data-option="`${field._id}-${i}`" :class="[inline, 'text-sm']" placeholder="Auswahlmöglichkeit" @keydown="optionKeydown($event, i)" @focus="builder.select(field._id)" />
<button v-if="selected" type="button" class="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent" title="Entfernen" @click.stop="removeOption(i)"><X class="size-3.5" /></button>
</div>
<button v-if="selected" type="button" class="ml-6.5 inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click.stop="addOption"><Plus class="size-3.5" /> Auswahlmöglichkeit</button>
</div>
<div v-else-if="field.type === 'file'" class="flex h-10 items-center justify-center gap-2 rounded-md border border-dashed text-sm text-muted-foreground">
<Paperclip class="size-4" /> {{ d.multiple ? 'Dateien auswählen' : 'Datei auswählen' }}
</div>
<div v-else-if="field.type === 'date'" :class="[fake, 'justify-between']">TT.MM.JJJJ <Calendar class="size-4" /></div>
<div v-else class="rounded-md border border-input bg-card shadow-xs">
<input v-model="d.placeholder" class="h-9 w-full bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground/50" :placeholder="field.type === 'text' ? 'Platzhalter (optional)' : ''" :disabled="field.type !== 'text'" aria-label="Platzhalter" />
</div>
<input
v-if="selected || d.help"
v-model="d.help"
:class="[inline, 'text-[13px] text-muted-foreground']"
placeholder="Hinweis unter dem Feld hinzufügen …"
aria-label="Hinweis"
/>
</div>
</div>
</template>

View file

@ -0,0 +1,193 @@
<script setup>
import { computed, inject } from 'vue';
import { ArrowDown, ArrowUp, Plus, X } from '@lucide/vue';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import NativeSelect from '@/components/NativeSelect.vue';
import { fieldTypes, layoutTypes, operators, optionTypes } from '../../lib/fields';
const props = defineProps({
field: { type: Object, required: true },
});
const builder = inject('forms:builder');
const d = computed(() => props.field.data);
const isLayout = computed(() => layoutTypes.includes(props.field.type));
// Bedingung: nur andere Eingabefelder, die davor stehen
const conditionFields = computed(() => {
const index = builder.fields.findIndex((f) => f._id === props.field._id);
return builder.fields.slice(0, index)
.filter((f) => !layoutTypes.includes(f.type))
.map((f) => ({ value: f.data.key, label: f.data.label || f.data.key }));
});
const conditionTarget = computed(() => builder.fields.find((f) => f.data.key === d.value.condition_field));
const valueOptions = computed(() => {
const target = conditionTarget.value;
if (!target) return null;
if (target.type === 'checkbox') return [{ value: '1', label: 'angehakt' }];
if (optionTypes.includes(target.type)) return (target.data.options ?? []).filter(Boolean).map((o) => ({ value: o, label: o }));
return null;
});
function setCondition(key) {
if (!key) {
delete d.value.condition_field;
delete d.value.condition_operator;
delete d.value.condition_value;
return;
}
d.value.condition_field = key;
d.value.condition_operator ??= 'equals';
}
function moveOption(i, dir) {
const options = [...d.value.options];
const j = i + dir;
if (j < 0 || j >= options.length) return;
[options[i], options[j]] = [options[j], options[i]];
d.value.options = options;
}
const number = (key) => ({
get: () => d.value[key] ?? '',
set: (value) => (value === '' || value === null ? delete d.value[key] : (d.value[key] = Number(value))),
});
const min = computed(number('min'));
const max = computed(number('max'));
const rows = computed(number('rows'));
const maxSize = computed(number('max_size'));
</script>
<template>
<div class="grid gap-5">
<header class="flex items-center gap-3">
<span class="grid size-9 shrink-0 place-items-center rounded-md bg-brand-soft text-brand-text"><component :is="fieldTypes[field.type].icon" class="size-4.5" /></span>
<div class="min-w-0">
<h2 class="font-semibold">{{ builder.types[field.type] }}</h2>
<p class="text-xs text-muted-foreground">Bezeichnung und Auswahlmöglichkeiten bearbeiten Sie direkt im Formular.</p>
</div>
</header>
<template v-if="isLayout">
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Text</span>
<Textarea v-if="field.type === 'paragraph'" v-model="d.text" rows="4" maxlength="3000" />
<Input v-else v-model="d.text" maxlength="200" />
</label>
</template>
<template v-else>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Bezeichnung</span>
<Input v-model="d.label" maxlength="200" />
</label>
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
Pflichtfeld
<Switch :model-value="!!d.required" @update:model-value="(v) => (d.required = v)" />
</label>
<div class="grid gap-1.5">
<span class="text-[13px] font-medium">Breite</span>
<div class="grid grid-cols-2 rounded-md border p-0.5 text-[13px]" role="group">
<button
v-for="option in [{ value: 'full', label: 'Volle Breite' }, { value: 'half', label: 'Halbe Breite' }]"
:key="option.value"
type="button"
class="rounded py-1.5"
:class="(d.width ?? 'full') === option.value ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
:aria-pressed="(d.width ?? 'full') === option.value"
@click="d.width = option.value"
>
{{ option.label }}
</button>
</div>
</div>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Hinweis unter dem Feld</span>
<Input v-model="d.help" maxlength="300" />
</label>
<label v-if="['text', 'email', 'phone'].includes(field.type)" class="grid gap-1.5">
<span class="text-[13px] font-medium">Vorbelegen mit</span>
<NativeSelect :model-value="d.prefill ?? null" :options="builder.prefillOptions" placeholder="– nicht vorbelegen –" @update:model-value="(v) => (v ? (d.prefill = v) : delete d.prefill)" />
<span class="text-xs text-muted-foreground">Aus dem Profil der ausfüllenden Person; änderbar.</span>
</label>
<div v-if="['text', 'textarea', 'number', 'checkboxes'].includes(field.type)" class="grid grid-cols-2 gap-3">
<label v-if="['number', 'checkboxes'].includes(field.type)" class="grid gap-1.5">
<span class="text-[13px] font-medium">{{ field.type === 'checkboxes' ? 'Mindestens wählen' : 'Mindestens' }}</span>
<Input v-model="min" type="number" />
</label>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">{{ { text: 'Höchstlänge', textarea: 'Höchstlänge', number: 'Höchstens', checkboxes: 'Höchstens wählen' }[field.type] }}</span>
<Input v-model="max" type="number" min="1" />
</label>
<label v-if="field.type === 'textarea'" class="grid gap-1.5">
<span class="text-[13px] font-medium">Zeilen</span>
<Input v-model="rows" type="number" min="2" max="20" />
</label>
</div>
<template v-if="field.type === 'file'">
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Erlaubte Dateien</span>
<NativeSelect v-model="d.accept" :options="[{ value: 'documents', label: 'Dokumente (PDF, Office …)' }, { value: 'images', label: 'Bilder' }, { value: 'any', label: 'Dokumente und Bilder' }]" />
</label>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Höchstgröße in MB</span>
<Input v-model="maxSize" type="number" min="1" max="50" />
</label>
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
Mehrere Dateien (bis 10)
<Switch :model-value="!!d.multiple" @update:model-value="(v) => (d.multiple = v)" />
</label>
</template>
<div v-if="optionTypes.includes(field.type)" class="grid gap-1.5">
<span class="text-[13px] font-medium">Auswahlmöglichkeiten</span>
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-1">
<Input v-model="d.options[i]" class="h-8" maxlength="200" />
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Nach oben" @click="moveOption(i, -1)"><ArrowUp class="size-3.5" /></button>
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Nach unten" @click="moveOption(i, 1)"><ArrowDown class="size-3.5" /></button>
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Entfernen" @click="d.options = d.options.filter((_, j) => j !== i)"><X class="size-3.5" /></button>
</div>
<button type="button" class="inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click="d.options = [...(d.options ?? []), '']"><Plus class="size-3.5" /> Hinzufügen</button>
</div>
</template>
<details class="rounded-md border" :open="!!d.condition_field">
<summary class="cursor-pointer px-3 py-2 text-[13px] font-medium">Nur anzeigen, wenn …</summary>
<div class="grid gap-3 border-t px-3 py-3">
<p v-if="!conditionFields.length" class="text-xs text-muted-foreground">Bedingungen beziehen sich auf Felder weiter oben im Formular.</p>
<template v-else>
<NativeSelect :model-value="d.condition_field ?? null" :options="conditionFields" placeholder="– immer anzeigen –" aria-label="Feld" @update:model-value="setCondition" />
<template v-if="d.condition_field">
<NativeSelect v-model="d.condition_operator" :options="Object.entries(operators).map(([value, label]) => ({ value, label }))" aria-label="Bedingung" />
<template v-if="!['filled', 'empty'].includes(d.condition_operator)">
<NativeSelect v-if="valueOptions" v-model="d.condition_value" :options="valueOptions" placeholder="Wert wählen …" aria-label="Wert" />
<Input v-else v-model="d.condition_value" placeholder="Wert" aria-label="Wert" />
</template>
</template>
</template>
</div>
</details>
<label v-if="!isLayout" class="grid gap-1.5">
<span class="text-[13px] font-medium">Technischer Schlüssel</span>
<Input :model-value="d.key" disabled class="font-mono text-xs" />
<span class="text-xs text-muted-foreground">Für Export und Bedingungen. Wird aus der Bezeichnung gebildet und bleibt danach gleich.</span>
</label>
</div>
</template>

View file

@ -0,0 +1,33 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { Download, PencilLine, Plus, TableProperties } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import Panel from '@/components/Panel.vue';
defineProps({
forms: { type: Array, required: true },
createUrl: { type: String, default: null },
});
</script>
<template>
<Panel title="Formulare">
<template #actions>
<Button v-if="createUrl" size="sm" variant="outline" as-child><a :href="createUrl"><Plus /> Neues Formular</a></Button>
</template>
<ul v-if="forms.length" class="-mx-5 divide-y border-t">
<li v-for="form in forms" :key="form.id" class="flex items-center gap-3 px-5 py-2.5">
<div class="min-w-0 flex-1">
<Link :href="form.url" class="block truncate text-sm font-medium hover:underline">{{ form.title }}</Link>
<p class="text-xs text-muted-foreground">
{{ form.open ? 'offen' : 'geschlossen' }} · {{ form.submissions }} Einsendungen<template v-if="form.unread">, <span class="font-medium text-brand-text">{{ form.unread }} neu</span></template>
</p>
</div>
<Button v-if="form.builder_url" size="icon" variant="ghost" as-child title="Felder bearbeiten"><Link :href="form.builder_url"><PencilLine /></Link></Button>
<Button v-if="form.results_url" size="icon" variant="ghost" as-child title="Ergebnisse"><a :href="form.results_url"><TableProperties /></a></Button>
<Button v-if="form.csv_url" size="icon" variant="ghost" as-child title="Ergebnisse als CSV herunterladen"><a :href="form.csv_url"><Download /></a></Button>
</li>
</ul>
<p v-else class="text-sm text-muted-foreground">Noch keine Formulare.</p>
</Panel>
</template>

View file

@ -0,0 +1,110 @@
import {
AtSign,
Calendar,
CheckSquare,
ChevronsUpDown,
CircleDot,
Hash,
Heading,
Info,
ListChecks,
Paperclip,
Phone,
Text,
TextCursorInput,
} from '@lucide/vue';
/**
* Feldtypen des Formularbaukastens – passend zu Inhaus\Plugins\Forms\FormFields.
*/
export const fieldTypes = {
text: { icon: TextCursorInput, group: 'Eingabe', defaults: { label: 'Textzeile', width: 'full' } },
textarea: { icon: Text, group: 'Eingabe', defaults: { label: 'Mehrzeiliger Text', rows: 4, width: 'full' } },
email: { icon: AtSign, group: 'Eingabe', defaults: { label: 'E-Mail-Adresse', width: 'half' } },
phone: { icon: Phone, group: 'Eingabe', defaults: { label: 'Telefonnummer', width: 'half' } },
number: { icon: Hash, group: 'Eingabe', defaults: { label: 'Zahl', width: 'half' } },
date: { icon: Calendar, group: 'Eingabe', defaults: { label: 'Datum', width: 'half' } },
select: { icon: ChevronsUpDown, group: 'Auswahl', defaults: { label: 'Auswahlliste', options: ['Option 1', 'Option 2'], width: 'full' } },
radio: { icon: CircleDot, group: 'Auswahl', defaults: { label: 'Einfachauswahl', options: ['Ja', 'Nein'], width: 'full' } },
checkboxes: { icon: ListChecks, group: 'Auswahl', defaults: { label: 'Mehrfachauswahl', options: ['Option 1', 'Option 2', 'Option 3'], width: 'full' } },
checkbox: { icon: CheckSquare, group: 'Auswahl', defaults: { label: 'Ich stimme zu.', width: 'full' } },
file: { icon: Paperclip, group: 'Sonstiges', defaults: { label: 'Datei', accept: 'any', max_size: 10, width: 'full' } },
heading: { icon: Heading, group: 'Gestaltung', defaults: { text: 'Zwischenüberschrift' } },
paragraph: { icon: Info, group: 'Gestaltung', defaults: { text: 'Hinweistext' } },
};
export const layoutTypes = ['heading', 'paragraph'];
export const optionTypes = ['select', 'radio', 'checkboxes'];
/** Wie Str::slug($label, '_', 'de') auf dem Server. */
export function slugify(text) {
return String(text ?? '')
.toLowerCase()
.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
.normalize('NFKD').replace(/[̀-ͯ]/g, '')
.replace(/@/g, '_at_')
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 60);
}
export function uid() {
return Math.random().toString(36).slice(2, 10);
}
/** Schlüssel für neue Felder aus der Bezeichnung ableiten, eindeutig im Formular. */
export function assignKeys(fields) {
const used = new Set(fields.filter((f) => !f._new && f.data.key).map((f) => f.data.key));
for (const field of fields) {
if (!field._new) continue;
const base = slugify(field.data.label || field.data.text || field.type) || field.type;
let key = base;
for (let i = 2; used.has(key); i++) key = `${base}_${i}`;
field.data.key = key;
used.add(key);
}
}
export function createField(type) {
return { _id: uid(), _new: true, type, data: structuredClone(fieldTypes[type].defaults) };
}
/** Darstellung für die Vorschau – wie FormFields::forFrontend(). */
export function toFrontend(fields) {
const accept = {
documents: '.pdf,.doc,.docx,.xls,.xlsx,.odt,.ods,.ppt,.pptx,.txt,.csv,.rtf',
images: '.jpg,.jpeg,.png,.webp,.gif,.heic',
any: '',
};
return fields.map(({ type, data }) => ({
type,
key: data.key,
label: data.label,
text: data.text,
help: data.help,
placeholder: data.placeholder,
required: !!data.required,
options: (data.options ?? []).filter((o) => o !== ''),
width: data.width ?? 'full',
min: data.min,
max: data.max,
rows: data.rows,
multiple: !!data.multiple,
accept: accept[data.accept ?? 'any'] || undefined,
max_size: data.max_size,
condition: data.condition_field ? { field: data.condition_field, operator: data.condition_operator ?? 'equals', value: String(data.condition_value ?? '') } : null,
}));
}
export const operators = {
equals: 'ist gleich',
not_equals: 'ist nicht',
contains: 'enthält',
filled: 'ist ausgefüllt',
empty: 'ist leer',
};

View file

@ -0,0 +1,325 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, provide, reactive, ref, watch } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { VueDraggable } from 'vue-draggable-plus';
import { ArrowLeft, CircleCheck, Eye, LoaderCircle, PencilLine, Plus, Save, Settings2, TableProperties } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Toaster } from '@/components/ui/sonner';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { http } from '@/lib/http';
import BuilderField from '../components/builder/BuilderField.vue';
import FieldSettings from '../components/builder/FieldSettings.vue';
import FormRenderer from '../components/FormRenderer.vue';
import { assignKeys, createField, fieldTypes, toFrontend, uid } from '../lib/fields';
const props = defineProps({
form: { type: Object, required: true },
types: { type: Object, required: true },
prefillOptions: { type: Array, required: true },
settingsUrl: { type: String, required: true },
resultsUrl: { type: String, default: null },
});
const state = reactive({
title: props.form.title,
description: props.form.description ?? '',
fields: props.form.fields.map((field) => ({ _id: uid(), type: field.type, data: { ...field.data } })),
});
const selectedId = ref(null);
const errorIndex = ref(null);
const mode = ref('edit');
const saving = ref(false);
const saved = ref(JSON.stringify(state));
const dirty = computed(() => JSON.stringify(state) !== saved.value);
const selected = computed(() => state.fields.find((f) => f._id === selectedId.value) ?? null);
// Schlüssel neuer Felder folgen der Bezeichnung, bis gespeichert wurde.
watch(() => state.fields.map((f) => [f._new, f.data.label, f.data.text]), () => assignKeys(state.fields), { deep: true, immediate: true });
function select(id) {
selectedId.value = id;
}
function add(type, index = null) {
const field = createField(type);
const selectedIndex = state.fields.findIndex((f) => f._id === selectedId.value);
const at = index ?? (selectedIndex >= 0 ? selectedIndex + 1 : state.fields.length);
state.fields.splice(at, 0, field);
select(field._id);
requestAnimationFrame(() => {
const el = document.querySelector(`[data-field-id="${field._id}"]`);
el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
el?.querySelector('input, textarea')?.select();
});
}
function remove(id) {
const field = state.fields.find((f) => f._id === id);
const dependents = state.fields.filter((f) => f.data.condition_field && f.data.condition_field === field?.data.key);
if (dependents.length && !window.confirm(`${dependents.length} Feld(er) hängen von diesem Feld ab. Die Bedingung wird dort entfernt. Trotzdem löschen?`)) return;
dependents.forEach((f) => {
delete f.data.condition_field;
delete f.data.condition_operator;
delete f.data.condition_value;
});
state.fields = state.fields.filter((f) => f._id !== id);
if (selectedId.value === id) select(null);
}
function duplicate(id) {
const index = state.fields.findIndex((f) => f._id === id);
const copy = { _id: uid(), _new: true, type: state.fields[index].type, data: structuredClone({ ...state.fields[index].data, key: undefined }) };
state.fields.splice(index + 1, 0, copy);
select(copy._id);
}
// „fields“ wird beim Löschen und Verschieben neu zugewiesen – daher als Getter.
provide('forms:builder', {
get fields() {
return state.fields;
},
types: props.types,
prefillOptions: props.prefillOptions,
selectedId,
errorIndex,
select,
remove,
duplicate,
});
async function save() {
if (saving.value) return;
saving.value = true;
errorIndex.value = null;
try {
const payload = {
title: state.title,
description: state.description,
fields: state.fields.map(({ type, data }) => ({ type, data })),
};
const result = await http.put(`/redaktion/formulare/${props.form.id}`, payload);
// Gespeicherte Schlüssel übernehmen; die Felder gelten nun als bestehend.
result.fields.forEach((field, i) => {
if (state.fields[i]) {
state.fields[i].data.key = field.data.key;
delete state.fields[i]._new;
}
});
saved.value = JSON.stringify(state);
toast.success('Formular gespeichert');
} catch (error) {
const [key, message] = Object.entries(error.fieldErrors ?? {})[0] ?? [];
const match = key?.match(/^fields\.(\d+)/);
if (match) {
errorIndex.value = Number(match[1]);
select(state.fields[errorIndex.value]?._id);
document.querySelector(`[data-field-id="${selectedId.value}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
toast.error(message ?? error.message);
} finally {
saving.value = false;
}
}
function onKeydown(event) {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
event.preventDefault();
save();
} else if (event.key === 'Escape') {
select(null);
}
}
function beforeUnload(event) {
if (dirty.value) {
event.preventDefault();
event.returnValue = '';
}
}
let removeRouterGuard;
onMounted(() => {
window.addEventListener('keydown', onKeydown);
window.addEventListener('beforeunload', beforeUnload);
removeRouterGuard = router.on('before', (event) => {
if (dirty.value && event.detail.visit.method === 'get' && !window.confirm('Es gibt ungespeicherte Änderungen. Seite trotzdem verlassen?')) {
return false;
}
});
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown);
window.removeEventListener('beforeunload', beforeUnload);
removeRouterGuard?.();
});
// Vorschau: echtes Formular mit Bedingungen, ohne Absenden
const previewForm = computed(() => ({
id: -1,
title: state.title,
description: state.description,
url: '#',
fields: toFrontend(state.fields),
prefill: {},
submit_label: 'Absenden',
confirmation: '',
open: true,
}));
const palette = computed(() => {
const groups = {};
for (const [type, meta] of Object.entries(fieldTypes)) {
(groups[meta.group] ??= []).push({ type, label: props.types[type], icon: meta.icon });
}
return Object.entries(groups);
});
</script>
<template>
<Head :title="`Formular: ${state.title}`" />
<div class="flex h-dvh flex-col bg-background">
<header class="z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-2 sm:px-3">
<Link href="/redaktion" class="grid size-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" title="Zurück zur Redaktion">
<ArrowLeft class="size-5" />
</Link>
<div class="min-w-0 flex-1">
<p class="truncate text-sm font-semibold">{{ state.title || 'Ohne Titel' }}</p>
<p class="flex items-center gap-1 truncate text-xs text-muted-foreground" aria-live="polite">
<template v-if="saving"><LoaderCircle class="size-3 animate-spin" /> Speichert …</template>
<template v-else-if="dirty">Ungespeicherte Änderungen</template>
<template v-else><CircleCheck class="size-3" /> Gespeichert · {{ form.submissions }} Einsendungen</template>
</p>
</div>
<div class="flex rounded-md border p-0.5 text-sm" role="group" aria-label="Ansicht">
<button type="button" class="flex items-center gap-1.5 rounded px-2.5 py-1" :class="mode === 'edit' ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'" @click="mode = 'edit'">
<PencilLine class="size-4" /> <span class="hidden sm:inline">Bearbeiten</span>
</button>
<button type="button" class="flex items-center gap-1.5 rounded px-2.5 py-1" :class="mode === 'preview' ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'" @click="mode = 'preview'; select(null)">
<Eye class="size-4" /> <span class="hidden sm:inline">Vorschau</span>
</button>
</div>
<Button variant="ghost" size="icon" as-child title="Einstellungen, Benachrichtigung und Zugriff"><a :href="settingsUrl"><Settings2 /></a></Button>
<Button v-if="resultsUrl" variant="ghost" size="icon" as-child title="Ergebnisse"><a :href="resultsUrl"><TableProperties /></a></Button>
<Button :disabled="saving || !dirty" @click="save"><Save /> <span class="hidden sm:inline">Speichern</span></Button>
</header>
<div class="flex min-h-0 flex-1">
<main class="min-w-0 flex-1 overflow-y-auto" @click="select(null)">
<div class="mx-auto max-w-3xl px-4 py-8">
<p v-if="form.submissions && mode === 'edit'" class="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[13px] text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100">
Es gibt bereits {{ form.submissions }} Einsendungen. Umbenennen ist unproblematisch – gelöschte Felder fehlen nur in neuen Einsendungen.
</p>
<template v-if="mode === 'edit'">
<input v-model="state.title" class="w-full rounded-sm bg-transparent text-3xl font-semibold tracking-tight outline-none focus:bg-brand-soft/40" placeholder="Titel des Formulars" aria-label="Titel" maxlength="200" @click.stop />
<textarea
v-model="state.description"
class="field-sizing-content mt-3 w-full resize-none rounded-sm bg-transparent leading-relaxed text-muted-foreground outline-none placeholder:text-muted-foreground/50 focus:bg-brand-soft/40"
placeholder="Einleitung (optional) – z. B. wofür das Formular gedacht ist und wer es bearbeitet"
aria-label="Einleitung"
rows="1"
maxlength="2000"
@click.stop
/>
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
<VueDraggable
v-model="state.fields"
:group="{ name: 'form-fields' }"
handle=".fb-handle"
:animation="150"
ghost-class="pb-ghost"
class="grid min-h-24 gap-x-5 gap-y-3 @xl:grid-cols-2"
@add="(event) => select(state.fields[event.newIndex]?._id)"
>
<BuilderField v-for="(field, index) in state.fields" :key="field._id" :field="field" :index="index" />
</VueDraggable>
<p v-if="!state.fields.length" class="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground">
Noch keine Felder. Felder aus der rechten Spalte hierher ziehen oder anklicken.
</p>
<Popover>
<PopoverTrigger class="mt-4 flex h-9 w-full items-center justify-center gap-1.5 rounded-md border border-dashed text-sm font-medium text-muted-foreground hover:border-brand-300 hover:bg-brand-soft hover:text-brand-soft-foreground" @click.stop>
<Plus class="size-4" /> Feld hinzufügen
</PopoverTrigger>
<PopoverContent class="w-[22rem] p-3" @click.stop>
<div class="grid grid-cols-2 gap-2">
<button v-for="(label, type) in types" :key="type" type="button" class="flex items-center gap-2 rounded-md border px-2.5 py-2 text-left text-[13px] font-medium hover:border-brand-300 hover:bg-brand-soft/60" @click="add(type, state.fields.length)">
<component :is="fieldTypes[type].icon" class="size-4 shrink-0 text-brand-text" /> <span class="truncate">{{ label }}</span>
</button>
</div>
</PopoverContent>
</Popover>
<div class="mt-5 flex items-center gap-4 border-t pt-5">
<span class="inline-flex h-9 items-center rounded-md bg-brand px-4 text-sm font-medium text-brand-foreground opacity-80">Absenden</span>
<span class="text-xs text-muted-foreground">Beschriftung und Bestätigungstext unter „Einstellungen“</span>
</div>
</div>
</template>
<template v-else>
<h1 class="text-3xl font-semibold tracking-tight">{{ state.title }}</h1>
<p v-if="state.description" class="mt-3 leading-relaxed whitespace-pre-line text-muted-foreground">{{ state.description }}</p>
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
<FormRenderer :key="JSON.stringify(previewForm.fields)" :form="previewForm" preview />
</div>
<p class="mt-3 text-center text-xs text-muted-foreground">Vorschau: Bedingungen und Pflichtfelder funktionieren wie im Portal, gesendet wird nichts.</p>
</template>
</div>
</main>
<aside v-if="mode === 'edit'" class="hidden w-[340px] shrink-0 flex-col border-l bg-card lg:flex">
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<FieldSettings v-if="selected" :key="selected._id" :field="selected" />
<template v-else>
<p class="mb-4 text-xs text-muted-foreground">Klicken fügt das Feld unter dem ausgewählten ein. Felder lassen sich auch an jede Stelle ziehen.</p>
<section v-for="[group, items] in palette" :key="group" class="mb-4">
<h3 class="mb-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">{{ group }}</h3>
<VueDraggable
:model-value="items"
:group="{ name: 'form-fields', pull: 'clone', put: false }"
:clone="(item) => createField(item.type)"
:sort="false"
class="grid grid-cols-2 gap-2"
>
<button
v-for="item in items"
:key="item.type"
type="button"
class="flex cursor-grab items-center gap-2 rounded-md border bg-card px-2.5 py-2 text-left text-[13px] font-medium hover:border-brand-300 hover:bg-brand-soft/60 active:cursor-grabbing"
@click="add(item.type)"
>
<component :is="item.icon" class="size-4 shrink-0 text-brand-text" />
<span class="truncate">{{ item.label }}</span>
</button>
</VueDraggable>
</section>
</template>
</div>
</aside>
</div>
</div>
<Toaster position="bottom-left" />
</template>

View file

@ -1,6 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Forms\Http\Controllers\FormBuilderController;
use Inhaus\Plugins\Forms\Http\Controllers\FormController;
use Inhaus\Plugins\Forms\Http\Controllers\FormResultsController;
@ -9,6 +10,9 @@ Route::middleware('auth')->group(function () {
Route::get('/formulare/{form:slug}', [FormController::class, 'show'])->name('forms.show');
Route::post('/formulare/{form:slug}', [FormController::class, 'submit'])->middleware('throttle:20,1')->name('forms.submit');
Route::get('/redaktion/formulare/{form}', [FormBuilderController::class, 'edit'])->name('forms.builder');
Route::put('/redaktion/formulare/{form}', [FormBuilderController::class, 'update'])->name('forms.builder.update');
Route::get('/formulare/dateien/{file}', [FormResultsController::class, 'file'])->name('forms.file');
Route::get('/admin/formulare/{form}/export', [FormResultsController::class, 'export'])->name('forms.export');
});

View file

@ -0,0 +1,51 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use Inhaus\Plugins\Forms\Models\Form;
/**
* „Redaktion → Formulare“: Formulare, deren Felder oder Ergebnisse die Person bearbeiten bzw. sehen darf.
*/
final class EditorialForms
{
public static function visible(User $user): bool
{
return $user->can('forms.manage')
|| $user->permissions()->ids('forms.edit', 'form') !== []
|| $user->permissions()->ids('forms.results', 'form') !== [];
}
/**
* @return array<string, mixed>
*/
public static function props(User $user): array
{
$all = $user->can('forms.manage');
$edit = $all ? true : $user->permissions()->ids('forms.edit', 'form');
$results = $all ? true : $user->permissions()->ids('forms.results', 'form');
$ids = $edit === true || $results === true ? true : array_values(array_unique([...$edit, ...$results]));
$forms = Form::query()
->when($ids !== true, fn ($q) => $q->whereIn('id', $ids))
->withCount(['submissions', 'submissions as unread_count' => fn ($q) => $q->whereNull('read_at')])
->orderBy('title')
->get(['id', 'title', 'slug', 'is_open', 'closes_at']);
return [
'forms' => $forms->map(fn (Form $form) => [
'id' => $form->id,
'title' => $form->title,
'url' => $form->url(),
'open' => $form->acceptsSubmissions(),
'submissions' => $form->submissions_count,
'unread' => $form->unread_count,
'builder_url' => $edit === true || in_array($form->id, (array) $edit, true) ? route('forms.builder', $form) : null,
'results_url' => $results === true || in_array($form->id, (array) $results, true) ? url('/admin/formulare/'.$form->id.'/ergebnisse') : null,
'csv_url' => $results === true || in_array($form->id, (array) $results, true) ? route('forms.export', $form) : null,
])->all(),
'createUrl' => $all ? url('/admin/formulare/neu') : null,
];
}
}

View file

@ -8,26 +8,24 @@ use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\HtmlString;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\CreateForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\EditForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\FormResults;
@ -62,18 +60,13 @@ class FormResource extends Resource
Tab::make('Felder')->icon(Heroicon::OutlinedQueueList)->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(200),
Textarea::make('description')->label('Einleitung')->rows(2)->maxLength(2000),
Builder::make('fields')
->label('Felder')
->blocks(static::fieldBlocks())
->addActionLabel('Feld hinzufügen')
->blockPickerColumns(3)
->blockNumbers(false)
->collapsible()
->collapsed(fn (string $operation) => $operation === 'edit')
->cloneable()
->reorderableWithButtons()
->minItems(1)
->default([]),
Text::make(fn (?Form $record) => new HtmlString($record
? '<strong>'.count(FormFields::inputs($record)).' Felder.</strong> Die Felder bearbeiten Sie im visuellen Baukasten – so, wie das Formular später aussieht.'
: 'Nach dem Anlegen öffnet sich der visuelle Baukasten für die Felder.')),
Actions::make([
Action::make('builder')->label('Felder im Baukasten bearbeiten')->icon(Heroicon::OutlinedPencilSquare)
->url(fn (?Form $record) => $record ? route('forms.builder', $record) : null),
])->visibleOn('edit'),
]),
Tab::make('Einstellungen')->icon(Heroicon::OutlinedCog6Tooth)->columns(2)->schema([
Toggle::make('is_open')->label('Nimmt Einsendungen an')->default(true),
@ -112,88 +105,6 @@ class FormResource extends Resource
]);
}
/**
* @return list<Block>
*/
public static function fieldBlocks(): array
{
$common = fn (array $extra = [], bool $prefill = false) => [
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(200)->live(onBlur: true)->columnSpan(2),
Toggle::make('required')->label('Pflichtfeld')->inline(false),
...$extra,
TextInput::make('help')->label('Hinweis unter dem Feld')->maxLength(300)->columnSpan(2),
Select::make('width')->label('Breite')->options(['full' => 'Volle Breite', 'half' => 'Halbe Breite'])->default('full')->native(false),
...($prefill ? [Select::make('prefill')->label('Vorbelegen mit')->options(fn () => FormFields::prefillOptions())->placeholder('–')->native(false)] : []),
static::conditionFieldset(),
TextInput::make('key')->label('Technischer Schlüssel')->helperText('Für Export und Bedingungen. Leer = aus der Bezeichnung.')->maxLength(60)->alphaDash(),
];
$options = TagsInput::make('options')->label('Auswahlmöglichkeiten')->placeholder('Eintrag eingeben und Enter')->required()->reorderable()->columnSpanFull();
return [
Block::make('text')->label(static::blockLabel('text'))->icon(Heroicon::OutlinedPencil)->columns(3)
->schema($common([TextInput::make('placeholder')->label('Platzhalter')->maxLength(100), TextInput::make('max')->label('Höchstlänge')->numeric()->minValue(1)->maxValue(255)], prefill: true)),
Block::make('textarea')->label(static::blockLabel('textarea'))->icon(Heroicon::OutlinedBars3BottomLeft)->columns(3)
->schema($common([TextInput::make('rows')->label('Zeilen')->numeric()->minValue(2)->maxValue(20)->default(4), TextInput::make('max')->label('Höchstlänge')->numeric()->minValue(1)->maxValue(10000)])),
Block::make('email')->label(static::blockLabel('email'))->icon(Heroicon::OutlinedAtSymbol)->columns(3)->schema($common(prefill: true)),
Block::make('phone')->label(static::blockLabel('phone'))->icon(Heroicon::OutlinedPhone)->columns(3)->schema($common(prefill: true)),
Block::make('number')->label(static::blockLabel('number'))->icon(Heroicon::OutlinedHashtag)->columns(3)
->schema($common([TextInput::make('min')->label('Mindestens')->numeric(), TextInput::make('max')->label('Höchstens')->numeric()])),
Block::make('date')->label(static::blockLabel('date'))->icon(Heroicon::OutlinedCalendarDays)->columns(3)->schema($common()),
Block::make('select')->label(static::blockLabel('select'))->icon(Heroicon::OutlinedChevronUpDown)->columns(3)->schema($common([$options])),
Block::make('radio')->label(static::blockLabel('radio'))->icon(Heroicon::OutlinedStop)->columns(3)->schema($common([$options])),
Block::make('checkboxes')->label(static::blockLabel('checkboxes'))->icon(Heroicon::OutlinedCheckCircle)->columns(3)
->schema($common([$options, TextInput::make('min')->label('Mindestens … auswählen')->numeric()->minValue(0), TextInput::make('max')->label('Höchstens … auswählen')->numeric()->minValue(1)])),
Block::make('checkbox')->label(static::blockLabel('checkbox'))->icon(Heroicon::OutlinedCheck)->columns(3)
->schema($common()),
Block::make('file')->label(static::blockLabel('file'))->icon(Heroicon::OutlinedPaperClip)->columns(3)
->schema($common([
Select::make('accept')->label('Erlaubte Dateien')->options(['documents' => 'Dokumente (PDF, Office …)', 'images' => 'Bilder', 'any' => 'Dokumente und Bilder'])->default('any')->native(false),
TextInput::make('max_size')->label('Höchstgröße')->numeric()->minValue(1)->maxValue(50)->default(10)->suffix('MB'),
Toggle::make('multiple')->label('Mehrere Dateien (bis 10)')->inline(false),
])),
Block::make('heading')->label(static::blockLabel('heading'))->icon(Heroicon::OutlinedH2)
->schema([TextInput::make('text')->label('Text')->required()->maxLength(200), static::conditionFieldset()]),
Block::make('paragraph')->label(static::blockLabel('paragraph'))->icon(Heroicon::OutlinedInformationCircle)
->schema([Textarea::make('text')->label('Text')->required()->rows(3)->maxLength(3000), static::conditionFieldset()]),
];
}
/**
* Titel eines Feldes im Baukasten: Typ und Bezeichnung (auch zugeklappt lesbar).
*/
private static function blockLabel(string $type): \Closure
{
return function (?array $state) use ($type) {
$text = $state['label'] ?? $state['text'] ?? null;
$suffix = ($state['required'] ?? false) ? ' *' : '';
$conditional = filled($state['condition_field'] ?? null) ? ' (bedingt)' : '';
return FormFields::TYPES[$type].($text ? ': '.mb_strimwidth((string) $text, 0, 70, '…') : '').$suffix.$conditional;
};
}
private static function conditionFieldset(): Fieldset
{
return Fieldset::make('Nur anzeigen, wenn …')->columns(3)->columnSpanFull()->schema([
Select::make('condition_field')->label('Feld')->placeholder('– immer anzeigen –')->native(false)
->options(function (Get $get) {
// Alle Eingabefelder des Formulars (Bezeichnung → Schlüssel).
$fields = FormFields::normalize((array) $get('../../../fields'));
return collect($fields)->reject(fn ($f) => in_array($f['type'], FormFields::LAYOUT_TYPES, true))
->mapWithKeys(fn ($f) => [$f['data']['key'] => ($f['data']['label'] ?? $f['data']['key'])])->all();
})
->live(),
Select::make('condition_operator')->label('Bedingung')->native(false)->default('equals')
->options(['equals' => 'ist gleich', 'not_equals' => 'ist nicht', 'contains' => 'enthält (Mehrfachauswahl)', 'filled' => 'ist ausgefüllt', 'empty' => 'ist leer'])
->visible(fn (Get $get) => filled($get('condition_field'))),
TextInput::make('condition_value')->label('Wert')->maxLength(200)
->visible(fn (Get $get) => filled($get('condition_field')) && ! in_array($get('condition_operator'), ['filled', 'empty'], true))
->helperText('Bei Kontrollkästchen: 1 für „angehakt“.'),
]);
}
/**
* Sichtbar sind Formulare, die man bearbeiten oder deren Ergebnisse man sehen darf.
*/
@ -228,6 +139,12 @@ class FormResource extends Resource
TextColumn::make('closes_at')->label('Einsendeschluss')->dateTime('d.m.Y H:i')->placeholder('–'),
])
->recordActions([
Action::make('builder')->label('Felder')->icon(Heroicon::OutlinedPencilSquare)->iconButton()->tooltip('Felder im Baukasten bearbeiten')
->url(fn (Form $record) => route('forms.builder', $record))
->visible(fn (Form $record) => auth()->user()->can('update', $record)),
Action::make('csv')->label('CSV')->icon(Heroicon::OutlinedArrowDownTray)->iconButton()->tooltip('Ergebnisse als CSV herunterladen')
->url(fn (Form $record) => route('forms.export', $record))
->visible(fn (Form $record) => auth()->user()->can('viewResults', $record)),
Action::make('results')->label('Ergebnisse')->icon(Heroicon::OutlinedTableCells)
->url(fn (Form $record) => static::getUrl('results', ['record' => $record]))
->visible(fn (Form $record) => auth()->user()->can('viewResults', $record)),

View file

@ -11,6 +11,14 @@ class CreateForm extends CreateRecord
protected function mutateFormDataBeforeCreate(array $data): array
{
return [...$data, 'created_by' => auth()->id()];
return [...$data, 'fields' => [], 'created_by' => auth()->id()];
}
/**
* Nach dem Anlegen direkt in den visuellen Baukasten.
*/
protected function getRedirectUrl(): string
{
return route('forms.builder', $this->record);
}
}

View file

@ -15,6 +15,8 @@ class EditForm extends EditRecord
protected function getHeaderActions(): array
{
return [
Action::make('builder')->label('Felder bearbeiten')->icon(Heroicon::OutlinedPencilSquare)
->url(fn () => route('forms.builder', $this->record)),
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
->url(fn () => $this->record->url())->openUrlInNewTab(),
Action::make('results')->label('Ergebnisse')->icon(Heroicon::OutlinedTableCells)->color('gray')

View file

@ -83,6 +83,9 @@ class FormResults extends Page implements HasTable
DeleteAction::make()->visible($canDelete)->after(fn (FormSubmission $s) => Audit::log('forms.submission_deleted', ['form' => $form->id, 'submission' => $s->id])),
])
->toolbarActions([
BulkAction::make('csv')->label('Auswahl als CSV')->icon(Heroicon::OutlinedArrowDownTray)
->action(fn (Collection $records) => $this->redirect(route('forms.export', ['form' => $form, 'ids' => $records->modelKeys()])))
->deselectRecordsAfterCompletion(),
BulkAction::make('markRead')->label('Als gelesen markieren')->icon(Heroicon::OutlinedCheck)
->action(fn (Collection $records) => FormSubmission::query()->whereIn('id', $records->modelKeys())->whereNull('read_at')->update(['read_at' => now()]))
->deselectRecordsAfterCompletion(),
@ -101,7 +104,7 @@ class FormResults extends Page implements HasTable
protected function getHeaderActions(): array
{
return [
Action::make('export')->label('Als CSV exportieren')->icon(Heroicon::OutlinedArrowDownTray)
Action::make('export')->label('Alle als CSV herunterladen')->icon(Heroicon::OutlinedArrowDownTray)
->url(fn () => route('forms.export', $this->record)),
Action::make('edit')->label('Formular bearbeiten')->icon(Heroicon::OutlinedPencilSquare)->color('gray')
->url(fn () => FormResource::getUrl('edit', ['record' => $this->record]))

View file

@ -2,13 +2,13 @@
namespace Inhaus\Plugins\Forms;
use App\Editorial\Editorial;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\BlockType;
use App\Pagebuilder\Field;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Forms\Models\Form;
@ -18,7 +18,8 @@ class FormsPlugin extends Plugin
{
public function register(): void
{
$this->app->make(Navigation::class)->add('forms', 'Formulare', '/formulare', active: ['forms.index', 'forms.show'], sort: 60);
// Kein eigener Menüpunkt im Portal: Formulare werden in Seiten und Beiträge eingebunden.
// /formulare/{slug} bleibt als direkte Adresse (z. B. für Links in E-Mails).
$abilities = $this->app->make(Abilities::class);
$abilities->define('forms.manage', 'Formulare: alle Formulare und Ergebnisse verwalten', 'Formulare');
@ -29,6 +30,10 @@ class FormsPlugin extends Plugin
Gate::policy(Form::class, FormPolicy::class);
$this->app->make(Editorial::class)->add('forms', 'Formulare', 'forms::EditorialForms', 30,
fn (User $user) => EditorialForms::visible($user),
fn (User $user) => EditorialForms::props($user));
$this->app->make(Blocks::class)->add(BlockType::make('forms.form', 'Formular', 'clipboard-list', 'dynamic', 'forms::FormBlock')
->description('Ein Formular direkt auf der Seite ausfüllen lassen.')
->fields([

View file

@ -0,0 +1,142 @@
<?php
namespace Inhaus\Plugins\Forms\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Audit;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Visueller Formularbaukasten im Portal: Das Formular erscheint so, wie es
* ausgefüllt wird; Bezeichnungen und Auswahlmöglichkeiten werden direkt darin
* bearbeitet. Einstellungen und Zugriff pflegt man im Admin.
*/
class FormBuilderController extends Controller
{
public function edit(Form $form): Response
{
Gate::authorize('update', $form);
return Inertia::render('forms::Builder', [
'form' => [
'id' => $form->id,
'title' => $form->title,
'description' => $form->description,
'fields' => $form->fields ?? [],
'url' => $form->url(),
'submissions' => $form->submissions()->count(),
],
'types' => FormFields::TYPES,
'prefillOptions' => collect(FormFields::prefillOptions())->map(fn ($label, $value) => ['value' => $value, 'label' => $label])->values(),
'settingsUrl' => url('/admin/formulare/'.$form->id.'/bearbeiten'),
'resultsUrl' => auth()->user()->can('viewResults', $form) ? url('/admin/formulare/'.$form->id.'/ergebnisse') : null,
]);
}
public function update(Request $request, Form $form): JsonResponse
{
Gate::authorize('update', $form);
$data = $request->validate([
'title' => ['required', 'string', 'max:200'],
'description' => ['nullable', 'string', 'max:2000'],
'fields' => ['present', 'array', 'max:150'],
'fields.*.type' => ['required', Rule::in(array_keys(FormFields::TYPES))],
'fields.*.data' => ['required', 'array'],
'fields.*.data.label' => ['nullable', 'string', 'max:200'],
'fields.*.data.text' => ['nullable', 'string', 'max:3000'],
'fields.*.data.help' => ['nullable', 'string', 'max:300'],
'fields.*.data.placeholder' => ['nullable', 'string', 'max:100'],
'fields.*.data.key' => ['nullable', 'string', 'max:60', 'regex:/^[a-z0-9_]*$/'],
'fields.*.data.options' => ['nullable', 'array', 'max:100'],
'fields.*.data.options.*' => ['nullable', 'string', 'max:200'],
], [], ['title' => 'Titel']);
// Nicht $data['fields']: validate() liefert nur die ausdrücklich geprüften Schlüssel.
// Die übrigen Einstellungen filtert cleanData() je Feldtyp.
$fields = array_map(fn (array $field) => ['type' => $field['type'], 'data' => self::cleanData($field['type'], (array) $field['data'])], array_values((array) $request->input('fields')));
foreach ($fields as $index => $field) {
$needsLabel = ! in_array($field['type'], FormFields::LAYOUT_TYPES, true);
if ($needsLabel ? blank($field['data']['label'] ?? null) : blank($field['data']['text'] ?? null)) {
throw ValidationException::withMessages(["fields.{$index}" => 'Feld '.($index + 1).': Bitte eine Bezeichnung eingeben.']);
}
if (in_array($field['type'], ['select', 'radio', 'checkboxes'], true) && ($field['data']['options'] ?? []) === []) {
throw ValidationException::withMessages(["fields.{$index}" => '„'.$field['data']['label'].'“: Bitte mindestens eine Auswahlmöglichkeit angeben.']);
}
}
$form->fill(['title' => $data['title'], 'description' => $data['description'] ?? null, 'fields' => $fields])->save();
Audit::log('forms.fields_updated', ['form' => $form->id, 'fields' => count($fields)]);
return response()->json(['fields' => $form->fresh()->fields]);
}
/**
* Nur bekannte Einstellungen übernehmen.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private static function cleanData(string $type, array $data): array
{
$allowed = ['label', 'key', 'required', 'help', 'width', 'condition_field', 'condition_operator', 'condition_value'];
$allowed = [...$allowed, ...match ($type) {
'text' => ['placeholder', 'max', 'prefill'],
'textarea' => ['rows', 'max'],
'email', 'phone' => ['prefill'],
'number' => ['min', 'max'],
'select', 'radio' => ['options'],
'checkboxes' => ['options', 'min', 'max'],
'file' => ['accept', 'max_size', 'multiple'],
'heading', 'paragraph' => ['text'],
default => [],
}];
$clean = array_intersect_key($data, array_flip($allowed));
if (isset($clean['options'])) {
$clean['options'] = array_values(array_unique(array_filter(array_map(fn ($o) => trim((string) $o), $clean['options']), 'strlen')));
}
foreach (['required', 'multiple'] as $flag) {
if (isset($clean[$flag])) {
$clean[$flag] = (bool) $clean[$flag];
}
}
foreach (['min', 'max', 'rows', 'max_size'] as $number) {
if (isset($clean[$number])) {
$clean[$number] = is_numeric($clean[$number]) ? (int) $clean[$number] : null;
}
}
if (isset($clean['width']) && ! in_array($clean['width'], ['full', 'half'], true)) {
$clean['width'] = 'full';
}
if (isset($clean['accept']) && ! array_key_exists($clean['accept'], FormFields::FILE_TYPES)) {
$clean['accept'] = 'any';
}
if (isset($clean['prefill']) && ! array_key_exists($clean['prefill'], FormFields::prefillOptions())) {
unset($clean['prefill']);
}
if (isset($clean['condition_operator']) && ! in_array($clean['condition_operator'], ['equals', 'not_equals', 'contains', 'filled', 'empty'], true)) {
$clean['condition_operator'] = 'equals';
}
return array_filter($clean, fn ($value) => $value !== null && $value !== '');
}
}

View file

@ -37,14 +37,18 @@ class FormResultsController extends Controller
$columns = FormFields::inputs($form);
$anonymous = $form->isAnonymous();
return response()->streamDownload(function () use ($form, $columns, $anonymous) {
// Optional nur ausgewählte Einsendungen (aus der Ergebnisliste).
$ids = array_values(array_filter(array_map('intval', (array) $request->query('ids', []))));
$submissions = fn () => $form->submissions()->when($ids !== [], fn ($q) => $q->whereIn('id', $ids));
return response()->streamDownload(function () use ($submissions, $columns, $anonymous) {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
$known = $columns;
// Felder, die es nur noch in älteren Einsendungen gibt, hinten anhängen.
$form->submissions()->select(['id', 'data'])->chunkById(500, function ($chunk) use (&$known) {
$submissions()->select(['id', 'data'])->chunkById(500, function ($chunk) use (&$known) {
foreach ($chunk as $submission) {
foreach ($submission->data as $key => $answer) {
$known[$key] ??= $answer['label'];
@ -54,7 +58,7 @@ class FormResultsController extends Controller
fputcsv($out, ['Eingegangen am', ...($anonymous ? [] : ['Name', 'E-Mail']), ...array_values($known)], ';', '"', '');
$form->submissions()->with('user:id,name,email')->orderBy('id')->chunkById(500, function ($chunk) use ($out, $known, $anonymous) {
$submissions()->with('user:id,name,email')->orderBy('id')->chunkById(500, function ($chunk) use ($out, $known, $anonymous) {
foreach ($chunk as $submission) {
fputcsv($out, [
$submission->created_at->timezone(config('app.timezone'))->format('d.m.Y H:i'),