- Laravel Application Development Cookbook
- Terry Matula
- 363字
- 2021-07-23 15:33:33
Creating a simple form
One of the most basic aspects of any web application is the form. Laravel provides easy ways to build HTML for our forms.
Getting ready
To get started, we need a fresh installation of Laravel.
How to do it...
To complete this recipe, follow these steps:
- In the
app/views
folder, create a newuserform.php
file. - In
routes.php
, create a route to load the view:Route::get(userform, function() { return View::make('userform'); });
- In the
userform.php
view, create a form using the following code:<h1>User Info</h1> <?= Form::open() ?> <?= Form::label('username', 'Username') ?> <?= Form::text('username') ?> <br> <?= Form::label('password', 'Password') ?> <?= Form::password('password') ?> <br> <?= Form::label('color', 'Favorite Color') ?> <?= Form::select('color', array('red' => 'red', 'green' =>'green', 'blue' => 'blue')) ?> <br> <?= Form::submit('Send it!') ?> <?= Form::close() ?>
View your form in the web page, by going to http://{your-server}/userform
(where {your-server}
is the name of your server).
How it works...
For this task, we created a simple form using Laravel's built-in Form
class. This allows us to easily create form elements with minimal code, and it's W3C (World Wide Web Consortium) compliant.
First, we open the form. Laravel automatically creates the <form>
html, including the action, the method, and the accept-charset parameters. When there are no options passed in, the default action is the current URL, the default method is POST,
and the charset is taken from the application config file.
Next we create normal text and password input fields, along with their labels. The first parameter in the label is the name of the text field and the second is the actual text to print. In the form builder, the label should appear before the actual form input.
The form select requires a second parameter, an array of the value in the drop-down box. In this example, we're creating an array using the 'key' => 'value'
syntax. If we want to create option groups, we just need to create nested arrays.
Finally, we create our Submit button and close the form.
There's more...
Most of Laravel's form methods can also include parameters for a default value and custom attributes (classes, IDs, and so on). We could also use Form::input()
for many fields, if we didn't want to use the specific methods. For example, we could have Form::input('submit', NULL, 'Send it!')
to create a submit button.
See also
- The Gathering form input to display on another page recipe
- Web安全防護指南:基礎篇
- Building Django 2.0 Web Applications
- Twilio Cookbook
- 5G承載網網絡規劃與組網設計
- Unity Artificial Intelligence Programming
- OMNeT++與網絡仿真
- INSTANT KineticJS Starter
- TD-LTE無線網絡規劃與設計
- 網管第一課:網絡操作系統與配置管理
- 從實踐中學習手機抓包與數據分析
- 異構蜂窩網絡關鍵理論與技術
- 深入理解Nginx:模塊開發與架構解析
- INSTANT LinkedIn Customization How-to
- Implementing NetScaler VPX?
- 新媒體交互藝術