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

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
主站蜘蛛池模板: 台南市| 镇远县| 吉木萨尔县| 黄山市| 集贤县| 临夏县| 临邑县| 长海县| 疏勒县| 罗江县| 信宜市| 彭水| 哈密市| 固镇县| 泊头市| 兰州市| 周口市| 香河县| 健康| 肥城市| 康定县| 沧州市| 赤城县| 崇礼县| 大丰市| 黄梅县| 和田市| 怀安县| 平陆县| 冀州市| 景泰县| 松桃| 西乌| 乐业县| 宝兴县| 天峻县| 凌源市| 隆化县| 克拉玛依市| 塔城市| 乌什县|