Home > other >  Auto populate form inputs with Laravel and Live Wire
Auto populate form inputs with Laravel and Live Wire

Time:10-16

Goal: on focusout event I want to auto populate html input fields #City #State (full name) #State2 (abbreviation)
Questions
1) how do I get the input passed to the function?
2) What do I need to do to populate the fields?

in resouces\ views: locale.blade.php

<div>
<input type="text" name="City" id="City" value="{{ $city }}">
<input type="text" name="State" id="State" value="{{ $state }}">
<input type="text" name="State2" id="State2" value="{{ $state2 }}">
<input type="text" name="Zip" id="Zip" value="{{ $zip }}"
       wire:focusout="setlocale">
</div>

in App\Http\ LiveWire Locale.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\State;
use Illuminate\Support\Arr;

class Locale extends Component
{
    public $zip = "";
    public $city = "";
    public $state = "";
    public $state2 = "";
    
    public function setlocale()

    {   
        $locale_arr=[];
        $g = $this->zip;
        dd($g);       ################## its only returning "" in my dd(); ###################
        $z = State::get()->where('zip',$g);
        $city = $z->city;
        $state = $z->state_name;
        $state2 = $z->state2_id;
        //TODO somehow render these variables in input fields.
        
    }
    public function render()
    {
        return view('livewire.locale');
    }
}

in App\Models\ ** State**

class State extends Model
{
    use HasFactory;

}

Tinker

>>> use App\Models\State
>>> $a = State::get()->where('zip','10001');
=> Illuminate\Database\Eloquent\Collection {#70820
     all: [
       2569 => App\Models\State {#35131
         id: 2570,
         zip: "10001",
         lat: 40.7506,
         lng: -73.9972,
         city: "New York",
         state_id: "NY",
         state_name: "New York",
         county_name: null,
         timezone: null,
       },
     ],
   }

CodePudding user response:

With Livewire, you have to bind the inputs to the properties of your class using wire:model. Livewire will then handle setting the value of your inputs to what you have in the component.

<div>
   <input type="text" name="City" id="City" wire:model="city" />
   <input type="text" name="State" id="State" wire:model="state" />
   <input type="text" name="State2" id="State2" wire:model="state2" />
   <input type="text" name="Zip" id="Zip" wire:model="zip" wire:focusout="setlocale" />
</div>

Then, instead of using wire:focusout, I recommend that you use a lifecycle-hook in the PHP class instead. So remove wire:focusout="setlocale" from your HTML, and add the following to your PHP class,

public function updated($field, $value) 
{
    if ($field === 'zip') {
        $this->setlocale();
    }

}

public function setlocale()
{   
    $zip = State::where('zip', $this->zip)->first();
    $this->city = $zip->city;
    $this->state = $zip->state_name;
    $this->state2 = $zip->state2_id;
}
  • Related