官术网_书友最值得收藏!

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:

  1. In the app/views folder, create a new userform.php file.
  2. In routes.php, create a route to load the view:
    Route::get(userform, function()
    {
        return View::make('userform');
    });
  3. 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
主站蜘蛛池模板: 邵阳市| 鄂伦春自治旗| 鄯善县| 安龙县| 柯坪县| 崇文区| 文山县| 蕲春县| 陵川县| 禄丰县| 化德县| 紫金县| 开封市| 塔河县| 台中市| 徐闻县| 阜南县| 普兰县| 泉州市| 牙克石市| 哈巴河县| 瑞昌市| 古浪县| 贵州省| 临城县| 聊城市| 康保县| 济阳县| 榕江县| 北川| 瑞昌市| 登封市| 宜丰县| 石城县| 衡阳市| 永宁县| 维西| 英吉沙县| 普陀区| 阜宁县| 昆山市|