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

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
主站蜘蛛池模板: 游戏| 镇平县| 陈巴尔虎旗| 平武县| 布尔津县| 华宁县| 巴林左旗| 泰州市| 金堂县| 宁城县| 商水县| 阜平县| 林州市| 泾源县| 康保县| 潼关县| 于都县| 平昌县| 葵青区| 威宁| 东台市| 周宁县| 赣榆县| 读书| 沾益县| 海原县| 泸西县| 芒康县| 宁乡县| 海丰县| 阿城市| 彩票| 西畴县| 津市市| 阳曲县| 吴旗县| 绍兴市| 桃园县| 泰顺县| 延长县| 浦江县|