laravelcollective5.3 Forms & HTML

Installation

Begin by installing this package through Composer. Run the following from the terminal:

composerrequire"laravelcollective/html":"^5.3.0"

Next, add your new provider to theprovidersarray ofconfig/app.php:

'providers'=>[// ...Collective\Html\HtmlServiceProvider::class,// ...],

Finally, add two class aliases to thealiasesarray ofconfig/app.php:

'aliases'=>[// ...'Form'=>Collective\Html\FormFacade::class,'Html'=>Collective\Html\HtmlFacade::class,// ...],

Looking to install this package inLumen? First of all, making this package compatible with Lumen will require some core changes to Lumen, which we believe would dampen the effectiveness of having Lumen in the first place. Secondly, it is our belief that if you need this package in your application, then you should be using Laravel anyway.

Opening A Form

Opening A Form

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

By default, aPOSTmethod will be assumed; however, you are free to specify another method:

echoForm::open(['url'=>'foo/bar','method'=>'put'])

Note:Since HTML forms only supportPOSTandGET,PUTandDELETEmethods will be spoofed by automatically adding a_methodhidden field to your form.

You may also open forms that point to named routes or controller actions:

echoForm::open(['route'=>'route.name'])echoForm::open(['action'=>'Controller@method'])

You may pass in route parameters as well:

echoForm::open(['route'=>['route.name',$user->id]])echoForm::open(['action'=>['Controller@method',$user->id]])

If your form is going to accept file uploads, add afilesoption to your array:

echoForm::open(['url'=>'foo/bar','files'=>true])

Form Model Binding

Opening A Model Form

Often, you will want to populate a form based on the contents of a model. To do so, use theForm::modelmethod:

echoForm::model($user,['route'=>['user.update',$user->id]])

Now, when you generate a form element, like a text input, the model's value matching the field's name will automatically be set as the field value. So, for example, for a text input namedemail, the user model'semailattribute would be set as the value. However, there's more! If there is an item in the Session flash data matching the input name, that will take precedence over the model's value. So, the priority looks like this:

Session Flash Data (Old Input)

Explicitly Passed Value

Model Attribute Data

This allows you to quickly build forms that not only bind to model values, but easily re-populate if there is a validation error on the server!

Note:When usingForm::model, be sure to close your form withForm::close!

Form Model Accessors

Laravel’sEloquent Accessorallow you to manipulate a model attribute before returning it. This can be extremely useful for defining global date formats, for example. However, the date format used for display might not match the date format used for form elements. You can solve this by creating two separate accessors: a standard accessor,and/ora form accessor.

To use form accessors, first include theFormAccessibletrait in the model then create aformFooAttributemethod on your model whereFoois the “camel-cased” name of the column you wish to access. In this example, we’ll define an accessor for thedate_of_birthattribute. The accessor will automatically be called by the HTML Form Builder when attempting to pre-fill a form field whenForm::model()is used.


* Get the user’s date of birth.

*

* @param? string? $value

* @return string

*/publicfunctiongetDateOfBirthAttribute($value){returnCarbon::parse($value)->format('m/d/Y');}/**

* Get the user's date of birth for forms.

*

* @param? string? $value

* @return string

*/publicfunctionformDateOfBirthAttribute($value){returnCarbon::parse($value)->format('Y-m-d');}}

CSRF Protection

If you use theForm::openorForm::modelmethod withPOST,PUTorDELETEthe CSRF token used by Laravel for CSRF protection will be added to your forms as a hidden field automatically. Alternatively, if you wish to generate the HTML for the hidden CSRF field, you may use thetokenmethod:

echoForm::token();

For more information on Laravel’s CSRF protection, seethe relevant section in Laravel’s documentation.

Labels

Generating A Label Element

echoForm::label('email','E-Mail Address');

Specifying Extra HTML Attributes

echoForm::label('email','E-Mail Address',['class'=>'awesome']);

Note:After creating a label, any form element you create with a name matching the label name will automatically receive an ID matching the label name as well.

Text, Text Area, Password & Hidden Fields

Generating A Text Input

echoForm::text('username');

Specifying A Default Value

echoForm::text('email','example@gmail.com');

Note:Thehiddenandtextareamethods have the same signature as thetextmethod.

Generating A Password Input

echoForm::password('password',['class'=>'awesome']);

Generating Other Inputs

echoForm::email($name,$value=null,$attributes=[]);echoForm::file($name,$attributes=[]);

Checkboxes and Radio Buttons

Generating A Checkbox Or Radio Input

echoForm::checkbox('name','value');echoForm::radio('name','value');

Generating A Checkbox Or Radio Input That Is Checked

echoForm::checkbox('name','value',true);echoForm::radio('name','value',true);

Number

Generating A Number Input

echoForm::number('name','value');

Date

Generating A Date Input

echoForm::date('name',\Carbon\Carbon::now());

File Input

Generating A File Input

echoForm::file('image');

Note:The form must have been opened with thefilesoption set totrue.

Drop-Down Lists

Generating A Drop-Down List

echoForm::select('size',['L'=>'Large','S'=>'Small']);

Generating A Drop-Down List With Selected Default

echoForm::select('size',['L'=>'Large','S'=>'Small'],'S');

Generating a Drop-Down List With an Empty Placeholder

This will create anelement with no value as the very first option of your drop-down.

echoForm::select('size',['L'=>'Large','S'=>'Small'],null,['placeholder'=>'Pick a size...']);

Generating a List With Multiple Selectable Options

echoForm::select('size',['L'=>'Large','S'=>'Small'],null,['multiple'=>true]);

Generating A Grouped List

echoForm::select('animal',['Cats'=>['leopard'=>'Leopard'],'Dogs'=>['spaniel'=>'Spaniel'],]);

Generating A Drop-Down List With A Range

echoForm::selectRange('number',10,20);

Generating A List With Month Names

echoForm::selectMonth('month');

Buttons

Generating A Submit Button

echoForm::submit('Click Me!');

Note:Need to create a button element? Try thebuttonmethod. It has the same signature assubmit.

Custom Macros

Registering A Form Macro

It's easy to define your own custom Form class helpers called "macros". Here's how it works. First, simply register the macro with a given name and a Closure:

Form::macro('myField',function(){return'';});

Now you can call your macro using its name:

Calling A Custom Form Macro

echoForm::myField();

Custom Components

Registering A Custom Component

Custom Components are similar to Custom Macros, however instead of using a closure to generate the resulting HTML, Components utilizeLaravel Blade Templates. Components can be incredibly useful for developers who useTwitter Bootstrap, or any other front-end framework, which requires additional markup to properly render forms.

Let's build a Form Component for a simple Bootstrap text input. You might consider registering your Components inside a Service Provider'sbootmethod.

Form::component('bsText','components.form.text',['name','value','attributes']);

Notice how we reference a view path ofcomponents.form.text. Also, the array we provided is a sort of method signature for your Component. This defines the names of the variables that will be passed to your view. Your view might look something like this:

// resources/views/components/form/text.blade.php{{Form::label($name,null,['class'=>'control-label'])}}{{Form::text($name,$value,array_merge(['class'=>'form-control'],$attributes))}}

Custom Components can also be created on theHtmlfacade in the same fashion as on theFormfacade.

Providing Default Values

When defining your Custom Component's method signature, you can provide default values simply by giving your array items values, like so:

Form::component('bsText','components.form.text',['name','value'=>null,'attributes'=>[]]);

Calling A Custom Form Component

Using our example from above (specifically, the one with default values provided), you can call your Custom Component like so:

{{Form::bsText('first_name')}}

This would result in something like the following HTML output:

First Name

Generating URLs

link_to

Generate a HTML link to the given URL.

echolink_to('foo/bar',$title=null,$attributes=[],$secure=null);

link_to_asset

Generate a HTML link to the given asset.

echolink_to_asset('foo/bar.zip',$title=null,$attributes=[],$secure=null);

link_to_route

Generate a HTML link to the given named route.

echolink_to_route('route.name',$title=null,$parameters=[],$attributes=[]);

link_to_action

Generate a HTML link to the given controller action.

echolink_to_action('HomeController@getIndex',$title=null,$parameters=[],$attributes=[])

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末幸缕,一起剝皮案震驚了整個濱河市铐望,隨后出現的幾起案子羡玛,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,113評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件矗蕊,死亡現場離奇詭異正什,居然都是意外死亡,警方通過查閱死者的電腦和手機喜喂,發(fā)現死者居然都...
    沈念sama閱讀 88,644評論 2 381
  • 文/潘曉璐 我一進店門瓤摧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人玉吁,你說我怎么就攤上這事照弥。” “怎么了进副?”我有些...
    開封第一講書人閱讀 153,340評論 0 344
  • 文/不壞的土叔 我叫張陵这揣,是天一觀的道長。 經常有香客問我影斑,道長给赞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,449評論 1 279
  • 正文 為了忘掉前任矫户,我火速辦了婚禮片迅,結果婚禮上,老公的妹妹穿的比我還像新娘皆辽。我一直安慰自己柑蛇,他們只是感情好,可當我...
    茶點故事閱讀 64,445評論 5 374
  • 文/花漫 我一把揭開白布驱闷。 她就那樣靜靜地躺著耻台,像睡著了一般。 火紅的嫁衣襯著肌膚如雪空另。 梳的紋絲不亂的頭發(fā)上盆耽,一...
    開封第一講書人閱讀 49,166評論 1 284
  • 那天,我揣著相機與錄音扼菠,去河邊找鬼摄杂。 笑死,一個胖子當著我的面吹牛娇豫,可吹牛的內容都是我干的匙姜。 我是一名探鬼主播,決...
    沈念sama閱讀 38,442評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼冯痢,長吁一口氣:“原來是場噩夢啊……” “哼氮昧!你這毒婦竟也來了?” 一聲冷哼從身側響起浦楣,我...
    開封第一講書人閱讀 37,105評論 0 261
  • 序言:老撾萬榮一對情侶失蹤袖肥,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后振劳,有當地人在樹林里發(fā)現了一具尸體椎组,經...
    沈念sama閱讀 43,601評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,066評論 2 325
  • 正文 我和宋清朗相戀三年历恐,在試婚紗的時候發(fā)現自己被綠了寸癌。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片专筷。...
    茶點故事閱讀 38,161評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖蒸苇,靈堂內的尸體忽然破棺而出磷蛹,到底是詐尸還是另有隱情,我是刑警寧澤溪烤,帶...
    沈念sama閱讀 33,792評論 4 323
  • 正文 年R本政府宣布味咳,位于F島的核電站,受9級特大地震影響檬嘀,放射性物質發(fā)生泄漏槽驶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,351評論 3 307
  • 文/蒙蒙 一鸳兽、第九天 我趴在偏房一處隱蔽的房頂上張望掂铐。 院中可真熱鬧,春花似錦揍异、人聲如沸堡纬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蛋济,卻和暖如春棍鳖,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背碗旅。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評論 1 261
  • 我被黑心中介騙來泰國打工渡处, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人祟辟。 一個月前我還...
    沈念sama閱讀 45,618評論 2 355
  • 正文 我出身青樓医瘫,卻偏偏與公主長得像,于是被迫代替她去往敵國和親旧困。 傳聞我的和親對象是個殘疾皇子醇份,可洞房花燭夜當晚...
    茶點故事閱讀 42,916評論 2 344

推薦閱讀更多精彩內容