laravel 5.0 Form 表单使用方法 【转】

laravel 5.0 Form 表单使用方法 【转】

Laravel – Form

5.0开始不再作为内嵌使用,请安装依赖库,具体看这里:

laravel5.0 Class ‘HTML’ not found

建立Form

{{ Form::open(['url' => 'foo']) }}
//...
{{ Form::close() }}

使用 open 及 close 來建立一個表單。參數是以陣列的方式設定,method 預設為 POST,如果要指定其他的方法,可自行增加:

{{ Form::open(['url' => 'foo', 'method' => 'put']) }}

你也可以不使用 url,改用 route:

{{ Form::open(['route' => 'route.name']) }}

route 帶參數:

{{ Form::open(['route' => ['route.name', $user->id] ]) }}

或是指定 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::hidden('id', '5') }}

密碼欄位會以點或星號顯示輸入的文字。

隱藏欄位通常會帶值。

text 可以利用 label 中說明的加入屬性 [‘size’=>30] 來改變輸入框的寬度。textarea 則是 [‘size’=>’50×50’]。

另外還有 email 及檔案:

{{ Form::email('email') }}
{{ Form::file('upload') }}

!重要,當你有使用到 file 欄位時,在 open 中必須加入 [‘files’ => true] 參數, 才能執行上傳的動作,例如:

{{Form::open(['url'=>'post', '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('按鈕') }}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据