Created
March 10, 2021 08:22
-
-
Save johncarter-/266cf0aa39f1ad852ee8d6428d13893f to your computer and use it in GitHub Desktop.
Statamic Livewire Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire; | |
use Illuminate\Support\Facades\URL; | |
use Livewire\Component; | |
use Statamic\Events\SubmissionCreated; | |
use Statamic\Facades\Form; | |
use Statamic\Facades\Site; | |
use Statamic\Forms\SendEmails; | |
class ContactForm extends Component | |
{ | |
public $formHandle; | |
public $fields; | |
protected $form; | |
public function mount($formHandle) | |
{ | |
$this->formHandle = $formHandle; | |
$this->getForm(); | |
$this->fields = array_fill_keys($this->form->blueprint()->fields()->all()->keys()->toArray(), ''); | |
} | |
public function hydrate() | |
{ | |
$this->getForm(); | |
} | |
private function getForm() | |
{ | |
$this->form = Form::find($this->formHandle); | |
} | |
protected function rules() | |
{ | |
return $this->form->blueprint()->fields()->all()->mapWithKeys(function ($field) { | |
return ['fields.' . $field->handle() => collect($field->rules())->flatten()]; | |
})->toArray(); | |
} | |
protected function validationAttributes() | |
{ | |
return $this->form->blueprint()->fields()->all()->mapWithKeys(function ($field) { | |
return ['fields.' . $field->handle() => $field->display()]; | |
})->toArray(); | |
} | |
public function submit() | |
{ | |
$site = Site::findByUrl(URL::previous()); | |
$validatedData = $this->validate(); | |
$submission = $this->form->makeSubmission()->data($validatedData['fields']); | |
if ($this->form->store()) { | |
$submission->save(); | |
} | |
SubmissionCreated::dispatch($submission); | |
SendEmails::dispatch($submission, $site); | |
} | |
public function render() | |
{ | |
return view('livewire.contact-form'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment