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
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:
parent
11123fecc0
commit
435960725d
139 changed files with 1735 additions and 432 deletions
51
plugins-core/forms/src/EditorialForms.php
Normal file
51
plugins-core/forms/src/EditorialForms.php
Normal 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,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -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)),
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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]))
|
||||
|
|
|
|||
|
|
@ -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([
|
||||
|
|
|
|||
|
|
@ -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 !== '');
|
||||
}
|
||||
}
|
||||
|
|
@ -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'),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue