[英]Laravel 5.5 correct way for a CRUD form select
所以我有這個CRUD,在這里我使用相同的表單來創建和編輯條目。 我需要以幾種形式進行選擇,在創建時(尚無該特定字段的數據),我的選擇顯示占位符,但是在編輯時,我的選擇顯示對特定ID字段存儲在數據庫中的任何內容。 所以我有:控制器:
...
public function create()
{
$house = houses::pluck('name', 'id');
//$thisclient = null;
$clients = client::pluck('last_name', 'id');
$reps = user::where('role_id', 5)->orderBy('first_name')->get()->pluck('full_name', 'id');
return view('prospects.create', compact('house', 'clients', 'reps'));
}
...
public function edit($id)
{
$house = houses::pluck('name', 'id');
//$thisclient = user::whereId($id)->first();
$clients = client::pluck('last_name', 'id');
$reps = user::where('role_id', 5)->orderBy('first_name')->get()->pluck('full_name', 'id');
$prospect = Prospect::findOrFail($id);
return view('prospects.edit', compact('prospect', 'house', 'clients', 'reps'));
}
和我的視圖形式:為創建而努力:
{!!Form::select('client_id', $clients, null, ['class' => 'form-control', 'placeholder' => 'Please Select'] ) !!}
編輯工作:
{!! Form::select('client_id', $clients, $prospect->client_id, ['class' => 'form-control'] ) !!}
我在這里遇到了2個麻煩,如果我將null
作為我的選擇字段,它將不會在edit
帶來所選數據,如果我有$prospect->client_id
,則由於沒有數據,它將在create
時返回錯誤。 我試圖通過在控制器上創建變量$ thishouse並將其傳遞給返回view('prospects.create', compact('house', 'thisclient','clients', 'reps'));
來解決此問題view('prospects.create', compact('house', 'thisclient','clients', 'reps'));
並查看Form::select('client_id', $clients, $thisclient, ['class' => 'form-control'] ) !!}
但似乎有點臟,因為有幾種選擇形式...
第二個麻煩是,如果我將一個占位符保留在Edit上,它將顯示該占位符,而不是$prospect->client_id
本身。
實現所有這些並使用相同的表單進行創建和編輯的最佳和最簡單的方法是什么? 謝謝
您可以使用Form :: open和Form :: model來創建和編輯。 例如,您可以在視圖中進行設置:
@if(isset($prospect))
{!! Form::model($prospect, ['action' => ['ProspectController@update', $prospect->id], 'method' => 'patch']) !!}
@else
{!! Form::open(array('action' => 'ProspectController@store', 'method' => 'POST')) !!}
@endif
然后您可以像這樣創建選擇:
{!! Form::select('client_id', $clients, old('client_id'), ['class' => 'form-control'] ) !!}
因此,當您進行編輯時,Laravel將從模型函數的變量中選擇屬性。
並且由於您使用的是Laravel 5.5,所以您也可以使用@isset
指令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.