laravel 表单和HTML扩展包

安装

通过composer安装扩展包. 在根目录的composer.json文件中添加laravelcollective/html.

"require": {
    "laravelcollective/html": "5.3.*"
}

接着在终端中更新composer:

composer update

然后,在config/app.php文件中添加新的providers:

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

最后,在config/app.php中添加别名数组:

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

打开表单

打开表单

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

默认是post请求,你也可以使用其他请求:

echo Form::open([‘url‘ => ‘foo/bar‘, ‘method‘ => ‘put‘])

注意: HTML表单只支持POSTGETPUTDELETE方法会被自动添加一个假的_method 隐藏字段到你的表单中.

You may also open forms that point to named routes or controller actions:你也可以打开指向到路由和控制器的表单:

echo Form::open([‘route‘ => ‘route.name‘])

echo Form::open([‘action‘ => ‘[email protected]‘])

还可以指定路由参数:

echo Form::open([‘route‘ => [‘route.name‘, $user->id]])

echo Form::open([‘action‘ => [‘[email protected]‘, $user->id]])

如果表单支持文件上传,添加files选项到数组中:

echo Form::open([‘url‘ => ‘foo/bar‘, ‘files‘ => true])

CSRF 保护

添加CSRF Token到表单

Laravel提供一种简单的方式保护你的应用防止跨域请求伪造,首先,你的session中会被置放一个随机的token,如果你使用 Form::open 方法,CSRF token会以隐藏字段的形式被自动添加到比表单中,或者,如果你想为隐藏的CSRF字段生成HTML,你可以使用token方法:

echo Form::token();

把CSRF过滤器指向路由

Route::post(‘profile‘,
    [
        ‘before‘ => ‘csrf‘,
        function()
        {
            //
        }
    ]
);

表单模型绑定

打开表单模型

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

echo Form::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 named email, the user model‘s email attribute 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:

  1. Session Flash Data (Old Input)
  2. Explicitly Passed Value
  3. 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 using Form::model, be sure to close your form with Form::close!

Form Model Accessors

Laravel‘s Eloquent Accessor allow 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/or a form accessor.

To define a form accessor, create a formFooAttribute method on your model where Foo is the "camel" cased name of the column you wish to access. In this example, we‘ll define an accessor for the date_of_birth attribute. The accessor will automatically be called by the HTML Form Builder when attempting to pre-fill a form field when Form::model() is used.

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user‘s first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getDateOfBirthAttribute($value)
    {
        return Carbon::parse($value)->format(‘m/d/Y‘);
    }

    /**
     * Get the user‘s first name for forms.
     *
     * @param  string  $value
     * @return string
     */
    public function formDateOfBirthAttribute($value)
    {
        return Carbon::parse($value)->format(‘Y-m-d‘);
    }
}

Labels

Generating A Label Element

echo Form::label(‘email‘, ‘E-Mail Address‘);

Specifying Extra HTML Attributes

echo Form::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

echo Form::text(‘username‘);

Specifying A Default Value

echo Form::text(‘email‘, ‘[email protected]‘);

Note: The hidden and textarea methods have the same signature as the text method.

Generating A Password Input

echo Form::password(‘password‘, [‘class‘ => ‘awesome‘]);

Generating Other Inputs

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

Checkboxes and Radio Buttons

Generating A Checkbox Or Radio Input

echo Form::checkbox(‘name‘, ‘value‘);

echo Form::radio(‘name‘, ‘value‘);

Generating A Checkbox Or Radio Input That Is Checked

echo Form::checkbox(‘name‘, ‘value‘, true);

echo Form::radio(‘name‘, ‘value‘, true);

Number

Generating A Number Input

echo Form::number(‘name‘, ‘value‘);

Date

Generating A Date Input

echo Form::date(‘name‘, \Carbon\Carbon::now());

File Input

Generating A File Input

echo Form::file(‘image‘);

Note: The form must have been opened with the files option set to true.

Drop-Down Lists

Generating A Drop-Down List

echo Form::select(‘size‘, [‘L‘ => ‘Large‘, ‘S‘ => ‘Small‘]);

Generating A Drop-Down List With Selected Default

echo Form::select(‘size‘, [‘L‘ => ‘Large‘, ‘S‘ => ‘Small‘], ‘S‘);

Generating a Drop-Down List With an Empty Placeholder

This will create an <option> element with no value as the very first option of your drop-down.

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

Generating A Grouped List

echo Form::select(‘animal‘,[
    ‘Cats‘ => [‘leopard‘ => ‘Leopard‘],
    ‘Dogs‘ => [‘spaniel‘ => ‘Spaniel‘],
]);

Generating A Drop-Down List With A Range

echo Form::selectRange(‘number‘, 10, 20);

Generating A List With Month Names

echo Form::selectMonth(‘month‘);

Buttons

Generating A Submit Button

echo Form::submit(‘Click Me!‘);

Note: Need to create a button element? Try the button method. It has the same signature as submit.

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 ‘<input type="awesome">‘;
});

Now you can call your macro using its name:

Calling A Custom Form Macro

echo Form::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 utilize Laravel Blade Templates. Components can be incredibly useful for developers who use Twitter 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‘s boot method.

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

Notice how we reference a view path of components.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
<div class="form-group">
    {{ Form::label($name, null, [‘class‘ => ‘control-label‘]) }}
    {{ Form::text($name, $value, array_merge([‘class‘ => ‘form-control‘], $attributes)) }}
</div>

Custom Components can also be created on the Html facade in the same fashion as on the Form facade.

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:

<div class="form-group">
    <label for="first_name">First Name</label>
    <input type="text" name="first_name" value="" class="form-control">
</div>

Generating URLs

link_to

Generate a HTML link to the given URL.

echo link_to(‘foo/bar‘, $title = null, $attributes = [], $secure = null);

link_to_asset

Generate a HTML link to the given asset.

echo link_to_asset(‘foo/bar.zip‘, $title = null, $attributes = [], $secure = null);

link_to_route

Generate a HTML link to the given named route.

echo link_to_route(‘route.name‘, $title = null, $parameters = [], $attributes = []);

link_to_action

Generate a HTML link to the given controller action.

echo link_to_action(‘[email protected]‘, $title = null, $parameters = [], $attributes = []);

https://laravelcollective.com/docs/5.3/html

时间: 2024-12-18 02:36:09

laravel 表单和HTML扩展包的相关文章

Python之路【第十三篇续】jQuery案例-Form表单&amp;插件及扩展

jQuery案例-Form表单 学完这个form表单的案例,如果有人说这个表单(功能)还不够NB(此文不包含样式,样式是CSS比较简单可以根据需求自己添加),那么找武Sir他帮你搞定. 一步一步来 注意事项(目录结构): 在写前端html代码的时候要注意(任何代码都一样),一定要规划好目录结构方便其他的人来看你的代码! 如果还有其他的html页面可以在加一个html存储的文件夹. 1.首先看下HTML主体 <!DOCTYPE html> <html lang="en"

jQuery Validate 提交表单验证失败扩展方法

由于Validate没有提供表单提交过后,验证不通过触发方法.这里做一下扩展. 引用场景:每次提交表单元素验证不通过触发方法 打开源代码 找到focusInvalid 方法, 这里是提交表单时验证不通过触发方法,在这里做扩展是就好不 过的. focusInvalid: function() { if ( this.settings.focusInvalid ) { try { $(this.findLastActive() || this.errorList.length && this.

Python之路【第十三篇】jQuery案例-Form表单&amp;插件及扩展

学完这个form表单的案例,如果有人说这个表单(功能)还不够NB(此文不包含样式,样式是CSS比较简单可以根据需求自己添加),那么找武Sir他帮你搞定. 一步一步来 注意事项(目录结构): 在写前端html代码的时候要注意(任何代码都一样),一定要规划好目录结构方便其他的人来看你的代码! 如果还有其他的html页面可以在加一个html存储的文件夹. 1.首先看下HTML主体 <!DOCTYPE html> <html lang="en"> <head>

Laravel表单提交

首先,先做一个简单的表单页面 <html> <head> </head> <body> <form action="/submit" method="post"> <input type="text" name="a"></input> <input type="text" name="b">

HTML5的表单新属性(扩展)

新的 form 属性: autocomplete. novalidate  autocomplete控件是指用户在文本框输入前几个字母或是汉字的时候, autocomplete控件就能从存放数据的文本或是数据库里将所有以这些字母开头的数据提示给用户,供用户选择,提供方便. autocomplete 适用于 <form> 标签,以及以下类型的 <input> 标签:text, search, url, telephone, email, password, datepickers,

自定义laravel表单请求验证类(FormRequest共用一个rules())

我们可以利用Form Request来封装表单验证代码,从而精简Controller中的代码逻辑,使其专注于业务.而独立出去的表单验证逻辑可以复用到其它请求中,看过几篇文章,大多都是讲怎么创建Request,表面看起来是将逻辑与业务分离了,但是没有做到复用,一个业务就得新建一个Request类实在太累,索性这里我将项目全部的表单验证放在一个Request类里,实现高度可复用,下面是具体实现. 首先创建Request php artisan make:request CreateUserReque

laravel 表单验证 正则匹配

判断url地址 是否为正确格式 控制器中 $this -> validate($request,[ 'linkname' => 'required|max:6|min:2', 'url' => 'required', 'url' => array('regex:/(http?|ftp?):\/\/(www)\.([^\.\/]+)\.(com|cn)(\/[\w-\.\/\?\%\&\=]*)?/i'), 'order' => 'required|regex:[[0-

laravel 表单接收

POST方式接收 视图层 <form action="/submit" method="post"> {{csrf_field()}}    //必加 <input type="text" name="a"></input> <input type="text" name="b"></input> <input type=

Day17 表单验证、滚动菜单、Django

一.表单验证的两种实现方式 1.DOM绑定 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单验证(DOM绑定)</title> <style> .item{ width: 250px; height: 60px; position: relative; } .item input{ wid