簡體   English   中英

使用 Laravel 和 Live Wire 自動填充表單輸入

[英]Auto populate form inputs with Laravel and Live Wire

目標:在焦點事件上,我想自動填充 html 輸入字段 #City #State(全名)#State2(縮寫)
問題
1)如何將輸入傳遞給函數?
2)我需要做什么來填充字段?

在資源\\視圖中: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>

在 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');
    }
}

在 App\\Models\\ ** 狀態**

class State extends Model
{
    use HasFactory;

}

廷克

>>> 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,
       },
     ],
   }

使用 Livewire,您必須使用wire:model將輸入綁定到您的類的屬性。 Livewire 然后將處理將輸入值設置為組件中的值。

<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>

然后,我建議您在 PHP 類中使用生命周期鈎子,而不是使用wire:focusout 因此,從您的 HTML 中刪除wire:focusout="setlocale" ,並將以下內容添加到您的 PHP 類中,

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM