In this lesson, let's see how easy it is to work with other form fields.
Prepare DB
We need to prepare the DB quickly before adding other fields to the form.
dabatase/migrations/xxxx_add_radio_and_checkbox_select_to_products_table.php:
Schema::table('products', function (Blueprint $table) { $table->string('color'); $table->boolean('in_stock')->default(true);});
app/Models/Product.php:
class Product extends Model{ protected $fillable = [ 'name', 'description', 'category_id', 'color', 'in_stock', ]; const COLOR_LIST = [ 'red' => 'Red', 'green' => 'Green', 'blue' => 'Blue', ]; // ...}
We will use COLOR_LIST
cons to quickly show colors in the form.
Add Fields to Livewire Form
Now let's show fields.
resources/views/livewire/products-create.blade.php:
<form method="POST" wire:submit="save"> // ... <div class="mt-4"> <label for="color">Color</label> @foreach(\App\Models\Product::COLOR_LIST as $key => $value) <div><input type="radio" wire:model="form.color" id="color" value="{{ $key }}" />{{ $value }}</div> @endforeach @error('form.color') <span class="mt-2 text-sm text-red-600">{{ $message }}</span> @enderror </div> <div class="mt-4"> <label for="in_stock">In stock</label> <div><input type="checkbox" wire:model="form.in_stock" id="in_stock" value="1" />In stock</div> @error('form.in_stock') <span class="mt-2 text-sm text-red-600">{{ $message }}</span> @enderror </div> <button class="mt-4 px-4 py-2 bg-gray-800 rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700"> Save Product </button></form>
So now, let's make them work. Because we are using Form Object, the only file we need to add some logic is there.
app/Livewire/Forms/ProductsForm.php:
class ProductsForm extends Form{ public ?Product $product; #[Validate('required|min:3')] public string $name = ''; #[Validate('required|min:3')] public string $description = ''; #[Validate('required|exists:categories,id', as: 'category')] public int $category_id = 0; #[Validate('required|string')] public string $color = ''; #[Validate('boolean')] public bool $in_stock = true; public function setProduct(Product $product): void { $this->product = $product; $this->name = $product->name; $this->description = $product->description; $this->category_id = $product->category_id; $this->color = $product->color; $this->in_stock = $product->in_stock; } // ...}
And that's it. That's how easy it was. It works now in both create and edit pages.
No comments yet…