Bypass required when save as draft
- Published: 28 May 2025 Updated: 28 May 2025
Unrequire fields recursively when saving as draft
Imagine you have a massive form with two buttons: Save as Draft and Submit, where all fields or a lot of them are required to submit.
You may want to let users save the form as draft even if it's incomplete.
Here's what you could do:
1public function saveDraft()
2{
3 foreach ($this->form->getComponents() as $component) {
4 $this->unrequireFields(component: $component);
5 }
6 $state = $this->form->getState();
7 //...
8}
9
10protected function unrequireFields($component, array $except = []): void
11{
12 if ($component instanceof Field) {
13 if (!in_array($component->getName(), $except)) {
14 if ($component->isRequired()) {
15 $component->markAsRequired();
16 }
17 $component->required(false);
18 }
19 return;
20 }
21
22 foreach ($component->getChildComponents() as $child) {
23 $this->unrequireFields($child, $except);
24 }
25}
Here, the unrequireFields method recursively remove the required for all the fields.
It also mark them as required thanks to the markAsRequired method in order to have the red asterisk even if the fields are not really required.
Related Tricks:
I’ll guide you on how to test your Form Builder using Livewire Volt with a class-based component.
Sometimes, when we need to test our application locally, we always have to fill forms manually. Let's take the Filament approach and achieve this with more accurate data.
Let Users to Select All Options with a Simple Hint Action
how to use a resource with multiple models
get translatable attribute in a relationships