Form 進階
建立表單
{{ Form::open(['url' => 'foo']) }}
//...
{{ Form::close() }}
使用 open() 及 close() 方法來建立一個表單。open() 方法的參數是以陣列,必須指定要傳送到哪個 url,method 預設為 POST,可省略,如果要指定其他的方法,可自行增加,例如:
{{ Form::open(['url' => 'foo', 'method' => 'put']) }}
你也可以不使用 url,改用 route:
{{ Form::open(['route' => 'route.name']) }}
如果使用 route,記得在 Routes.php 中,必須設定對應的 route name。
route 帶參數:
{{ Form::open(['route' => ['route.name', $user->id] ]) }}
或是使用 action 來指定 Controller:
{{ Form::open(['action' => 'Controller@method']) }}
Controller 帶參數:
{{ Form::open(['action' => ['Controller@method', $user->id] ]) }}
Form Model Binding
表單可以綁定資料模型,可以讓你在需要載入資料到表單欄位時更加方便。在前面的迷你部落格例子中,當我們在編輯文章時,可以改用 Model Binding 的方式來改寫:
原本的
{{Form::open(['url'=>'post/'.$post->id, 'method'=>'put'])}}
改成
{{ Form::model($post, ['action'=>['HomeController@update', $post->id]]) }}
現在這個表單已經和 $post 所儲存的 Post 模型綁定,在之後的欄位,就不需要指定值,只要欄位名稱和 Post 的屬性名稱相同即可。
原本的
{{Form::text('title', $post->title)}}<br>
改為
{{Form::text('title')}}<br>
這裡的 'title' 和 Post 的屬性,也就是資料庫中的欄位同名。因此可以不用 $post->title 指定值。
表單元件
Label
標籤文字,通常放在輸入框的前面,用來說明輸入框內要填入什麼內容。使用方式:
{{ Form::label('title', '標題') }}
如果要加入 HTML 屬性,可以使用第三個參數,陣列型態:
{{ Form::label('title', '標題', ['class'=>'title']) }}
要用到 css 去指定樣式時,可以加入 class 屬性。後面其他的表單元件都可以這麼使用。
Input (Text, TextArea, Password, Hidden, Email, File)
文字輸入框,沒有值的狀態:
{{ Form::text('title') }}
{{ Form::textarea('content') }}
{{ Form::password('password') }}
指定值:
{{ Form::text('title', '這是標題') }}
{{ Form::textarea('content', '這是內容') }}
{{ Form::password('password', '12345678') }}
{{ Form::hidden('id', '5') }}
密碼欄位會以點或星號顯示輸入的文字。
text 可以使用第三個參數加入 HTML 屬性 ['size'=>30] 來改變輸入框的寬度。textarea 則是 ['size'=>'50x50'],中間那個是小寫的 x。
email 及檔案的使用方式:
{{ Form::email('email') }}
{{ Form::file('upload') }}
!重要,當你有使用到 file 欄位時,在 open() 方法中必須加入 ['files' => true] 參數,才能執行上傳的動作,否則上傳欄位是無效的,例如:
{{ Form::open(['url'=>'foo', 'method'=>'post', 'files'=>true]) }}
Checkboxes (複選) 及 Radio (單選)
複選
{{ Form::checkbox('habit', 'reading', true) }}看書<br>
habit 是欄位名稱,reading 是值,true 表示預設為勾選,可以省略不寫,表示不勾選。
單選
{{ Form::radio('city', 'taipei', true) }}Taipei<br>
{{ Form::radio('city', 'taichung') }}Taichung<br>
{{ Form::radio('city', 'kaohsiung') }}Kaohsiung<br>
city 是欄位名稱,同名的視為一組,同一組中只有一個可以被選取。taipei 等第二個參數是值,true 表示選取。
Drop-Down Lists (下拉式清單)
一般清單
{{ Form::select('size', ['L'=>'大','M'=>'中','S'=>'小'], 'M') }}
size 是欄位名稱;第二個參數是陣列,表示清單項目;第三個參數可省略,是前面陣列中的 Key,表示預設選取的項目。
群組清單
{{ Form::select('fruit', [
'A' => ['apple' => 'Apple'],
'B' => ['banana' => 'Banana'],
])}}
fruit 是欄位名稱;陣列是清單項目;A 是群組名稱,之後的陣列是屬於該群組的清單項目。
連續數字清單
{{ Form::selectRange('number', 10, 20) }}
number 是欄位名稱,10 是起始值,20 是結束值,這個清單會自動產生 10~20 的數字項目。
月份清單
{{ Form::selectMonth('month') }}
自動產生月份名的清單項目,不過是英文的。
Buttons (按鈕)
Submit
{{ Form::submit('發表文章') }}
Button
{{ Form::button('按鈕') }}
Last updated
Was this helpful?