I’m struggling to understand how livewire
works.
I have two text fields. One is where the user enters information like prefixes and the second field with a read-only
attribute where data will be displayed based on the first field value.
But for some reason, I can’t populate the second field. All examples on the internet are how to take a value and return it back or generate a dropdown menu.
my blade
template:
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">prefix</label>
<input wire:change="testing"
type="text"
class="form-control"
id="prefix"
name="prefix"
/>
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Code</label>
<input wire:model="part"
type="text"
class="form-control"
id="part"
name="part"
value="{{ $part }}"
/>
</div>
and
Livewire
class
:
class DoSomethingClass extends Component
{
public $prefix;
public $part;
public function testing()
{
$this->part = $this->prefix;
}
public function render()
{
return view('livewire.blade-template');
}
}
2
Answers
You should use
wire:model
to both input fields. Than, if you want to update the 2nd field on the input of the first, you can use the Livewire Lifecycle to update it.Check this link for info on the updatedPrefix() hook: https://laravel-livewire.com/docs/2.x/lifecycle-hooks
(You can choose to use your testing() method too, but than you still need to use the wire:model directive to your second input.)
You can make what you’re doing work just by adding
wire:model="prefix"
to your firstinput
as suggested above.And the component itself can just stay the same. When someone types anything in the first field then tabs or clicks away it will update the second field.
If you want the second field to update as the user types change it to
wire:keydown="testing"
, it will make a call with every keystroke.As mentioned above, if you use the
updatedPrefix()
method you won’t need thewire:change
orwire:keydown
as Livewire will update the field as the user types.