Created
October 31, 2023 17:32
-
-
Save paperscissors/72e5beb4a004236a39708222df541efe to your computer and use it in GitHub Desktop.
Laravel Livewire 3 Field Repeater
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
<div> | |
@foreach($rows as $index => $row) | |
<div class="flex items-center space-x-4 mb-3" wire:key="min{{ $index }}"> | |
<input | |
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-10" | |
type="number" wire:model="rows.{{ $index }}.min" placeholder="Min"> | |
<input | |
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-10" | |
type="number" wire:model="rows.{{ $index }}.max" placeholder="Max"> | |
<input | |
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-10" | |
type="text" wire:model="rows.{{ $index }}.price" placeholder="Price"> | |
<button | |
class="bg-red-400 hover:bg-red-700 text-white py-2 px-4 rounded focus:outline-none focus:shadow-outline h-10" | |
wire:click="removeRow({{ $index }})">Remove | |
</button> | |
</div> | |
@endforeach | |
<button wire:click="addRow" | |
class="bg-gray-400 hover:bg-gray-700 text-white py-1 px-2 text-sm rounded focus:outline-none focus:shadow-outline"> | |
Add Row | |
</button> | |
</div> |
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\Livewire; | |
use Livewire\Component; | |
class FieldRepeater extends Component | |
{ | |
public array $rows = []; | |
public string $field; | |
protected $listeners = ['updateRows']; | |
public function mount($field, $initialRows = []) | |
{ | |
$this->field = $field; | |
$this->rows = $initialRows; | |
} | |
public function updated($propertyName) | |
{ | |
ray('updated', $propertyName); | |
$this->dispatch('update-rows', field: $this->field, rows: $this->rows); | |
} | |
public function addRow() | |
{ | |
$this->rows[] = ['min' => '', 'max' => '', 'price' => '']; | |
$this->dispatch('update-rows', field: $this->field, rows: $this->rows); // Emit an event to the parent | |
} | |
public function removeRow($index) | |
{ | |
unset($this->rows[$index]); | |
$this->rows = array_values($this->rows); | |
$this->dispatch('update-rows', field: $this->field, rows: $this->rows); // Emit an event to the parent | |
} | |
public function render() | |
{ | |
return view('livewire.field-repeater'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment