laraeast/laravel-bootstrap-forms

提供了一种简单的方法,在您的 Laravel 项目中使用 Bootstrap 组件。

v5.4.0 2023-03-25 23:38 UTC

README

Build Status Total Downloads Latest Stable Version License

# 安装

首先通过 Composer 安装此包。编辑您的项目 composer.json 文件,以添加 laraeast/laravel-bootstrap-forms 作为依赖项。

composer require laraeast/laravel-bootstrap-forms

您应将标志图标发布到公共路径,以在多语言表单标签页中显示。

php artisan vendor:publish --tag=locales:flags

# 打开表单

{{ BsForm::open(['url' => 'foo/bar']) }}
//
{{ BsForm::close() }}

默认情况下,将假设使用 POST 方法;但是,您可以自由指定其他方法

{{ BsForm::open(['url' => 'foo/bar', 'method' => 'post']) }}

注意:由于 HTML 表单仅支持 POSTGET,因此 PUTDELETE 方法将通过自动添加一个隐藏字段 _method 到您的表单中来进行欺骗。

您还可以指定方法来打开表单

{{ BsForm::get('foo/bar') }}
{{ BsForm::post('foo/bar') }}
{{ BsForm::put('foo/bar') }}
{{ BsForm::patch('foo/bar') }}
{{ BsForm::delete('foo/bar') }}
{{ BsForm::model($model, 'foo/bar') }}
{{ BsForm::putModel($model, 'foo/bar') }}
{{ BsForm::patchModel($model, 'foo/bar') }}

您还可以打开指向命名路由或控制器操作的表单

{{ BsForm::open(['route' => 'route.name']) }}
{{ BsForm::open(['action' => 'Controller@method']) }}

您还可以传递路由参数

{{ BsForm::open(['route' => ['route.name', $user->id]]) }}
{{ BsForm::open(['action' => ['Controller@method', $user->id]]) }}

# 文本、文本区域、日期、数字和密码字段

生成文本输入

{{ BsForm::text('username') }}

指定默认值

{{ BsForm::text('email', 'example@gmail.com') }}
{{ BsForm::text('email')->value('example@gmail.com') }}

注意:日期、数字和文本区域方法与文本方法的签名相同。

生成密码输入

{{ BsForm::password('password', ['class' => 'awesome']) }}
{{ BsForm::password('password')->attr('class', 'awesome') }}

生成其他输入

{{ BsForm::email($name)->value($value)->label($label) }}
{{ BsForm::file($name)->label('Upload File') }}

# 复选框和单选按钮

生成复选框或单选按钮输入

{{ BsForm::checkbox('name', 'value')->checked(false) }}
{{ BsForm::checkbox('name')->value('value')->checked(false) }}
{{ BsForm::checkbox('name')->value(1)->withDefault()->checked(false) }} {{-- If unchecked will send "0" with request --}}
{{ BsForm::checkbox('name')->value(1)->withoutDefault()->checked(false) }}
{{ BsForm::checkbox('name')->value(1)->default('no')->checked(false) }} {{-- If unchecked will send "no" with request --}}

{{ BsForm::radio('name', 'value')->checked(false)->label('label') }}
{{ BsForm::radio('name')->value('value')->checked(false)->label('label') }}

默认情况下,将使用未选中的复选框发送默认值 "0",如果要在全局范围内禁用它,请设置配置密钥 "laravel-bootstrap-forms.checkboxes.hasDefaultValue": true

# 下拉列表

{{ BsForm::select('size', ['L' => 'Large', 'S' => 'Small']) }}
{{ BsForm::select('size')->options(['L' => 'Large', 'S' => 'Small']) }}

生成带有选中默认值的下拉列表

{{ BsForm::select('size')->options(['L' => 'Large', 'S' => 'Small'])->value('S') }}

生成带有空占位符的下拉列表

{{ BsForm::select('size')->options(['L' => 'Large', 'S' => 'Small'])->placeholder('Select Size') }}

生成分组列表

{{ BsForm::select('animal',[
         'Cats' => ['leopard' => 'Leopard'],
         'Dogs' => ['spaniel' => 'Spaniel'],
   ]) }}

# 生成提交按钮

{{ BsForm::submit('Click Me!') }}

生成具有 Bootstrap 按钮样式的提交按钮

{{ BsForm::submit('Click Me!')->success() }}
{{ BsForm::submit('Click Me!')->primary() }}
{{ BsForm::submit('Click Me!')->info() }}
{{ BsForm::submit('Click Me!')->warning() }}
{{ BsForm::submit('Click Me!')->danger() }}

# 支持的方法

->label($label) : 生成指定字段的标签。

{{ BsForm::text('username')->label('Username') }}

->name($name) : 生成指定字段的标签。

{{ BsForm::text('username')->label('Username') }}

->placeholder($placeholder) : 设置指定字段的占位符属性。

{{ BsForm::text('username')->placeholder('Please Enter Your Name') }}

->min($min) : 设置指定数字字段的 min 属性。

{{ BsForm::number('age')->min(10) }}

->max($max) : 设置指定数字字段的 max 属性。

{{ BsForm::number('age')->min(10)->max(30) }}

->step($step) : 设置指定数字字段的 step 属性。

{{ BsForm::number('age')->min(10)->max(30)->step(1) }}

->multiple($bool = true) : 设置指定选择和文件字段的 multiple 属性。

{{ BsForm::file('photos[]')->multiple() }}

->note($note) : 设置指定字段的 help-block

{{ BsForm::text('username')->note('Example: Ahmed Fathy') }}

->name($name) : 设置指定字段的名称。

{{ BsForm::text()->name('username')->note('Example: Ahmed Fathy') }}

->value($value) : 设置指定字段的值作为默认值将设置 old('name')

{{ BsForm::text()->name('username')->value('Ahmed Fathy') }}

->inlineValidation($bool = true) : 在指定字段中显示验证错误。

{{ BsForm::text('username')->style('vertical')->inlineValidation(false) }}

->style($style = 'default') : 设置指定字段的样式。支持 ['default', 'vertical']

{{ BsForm::text('username')->style('vertical') }}
{{ BsForm::text('email')->style('default') }}

->close() : 关闭表单标签。

{{ BsForm::close() }}

# 使用具有本地化字段的资源

您还可以使用资源选项添加本地化标签、说明和占位符

@php(BsForm::resource('users'))

您必须将 users.php 文件添加到 resources/lang/en/ 路径中,并设置默认属性、注释以及占位符。

<?php
return [
    'attributes' => [
        'username' => 'User Name',
        'email' => 'E-mail Address',
        'phone' => 'Phone Number',
    ],
    'notes' => [
        'username' => 'Example: Ahmed Fathy',
        'email' => 'Example: aliraqi-dev@gmail.com',
        'phone' => 'Example: +02xxxxxxxxxxx',
    ],
    'placeholders' => [
        'username' => 'Please enter your name.',
        'email' => 'Please enter your e-mail address.',
        'phone' => 'Please enter your phone number.',
    ],
    ...
];

## 使用自定义错误消息包

您可以使用自定义错误包来显示验证错误,而不会产生任何冲突。

// Default error bag
BsForm::errorBag('default');

// Other error bag
BsForm::errorBag('create');

## 示例注册表单

@php(BsForm::resource('users'))

{{ BsForm::post(route('register')) }}
	{{ BsForm::text()->name('name') }}
	{{ BsForm::email('email') }}
	{{ BsForm::text('phone') }}
	{{ BsForm::submit()->danger() }}
{{ BsForm::close() }}

## 使用多语言表单标签

{{ BsForm::post(route('categories.store')) }}
	@bsMultilangualFormTabs
        {{ BsForm::text('name') }}
	@endBsMultilangualFormTabs

	{{ BsForm::submit()->danger() }}
{{ BsForm::close() }}

注意:在 @bsMultilangualFormTabs@endBsMultilangualFormTabs 内部的输入名称应加上 :{lang} 后缀。

例如,如果您的支持语言是 aren,则输入名称将命名为 name:arname:en

您应使用 Astrotomic/laravel-translatable 并配置其 rule_factory 的键格式为 \Astrotomic\Translatable\Validation\RuleFactory::FORMAT_KEY 来填充多语言数据,如下例所示。

Category::create([
    'name:ar' => 'سيارات',
    'name:en' => 'Cars',
]);

// with laravel-bootstrap-forms
Category::create($request->all());

## 管理区域设置

您可以在 locales.php 配置文件中添加您支持的区域设置。您可以使用以下命令获取它

php artisan vendor:publish --tag=locales:config
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Application Locales
    |--------------------------------------------------------------------------
    |
    | Contains an array with the applications available locales.
    |
    */
    'languages' => [
        'en' => [
                'code' => 'en',
                'name' => 'English',
                'dir' => 'ltr',
                'flag' => '/images/flags/us.png'
            ],
            'ar' => [
                'code' => 'ar',
                'name' => 'العربية',
                'dir' => 'rtl',
                'flag' => '/images/flags/sa.png'
            ],
        ],
];

## 使用 Bootstrap 3

如果您想使用 Bootstrap 3,应使用以下命令发布配置文件,并全局设置 Bootstrap 版本。

php artisan vendor:publish --tag=laravel-bootstrap-forms.config
<?php

return [
    /**
     * The path of form components views.
     *
     * - 'BsForm::bootstrap4'  - Bootstrap 4
     * - 'BsForm::bootstrap3'  - Bootstrap 3
     */
    'views' => 'BsForm::bootstrap3',
    ...
];

更改 Bootstrap 版本后,您应使用 view:clear artisan 命令清除缓存的视图文件。

php artisan view:clear

## 向组件添加自定义样式

运行 vendor:publish artisan 命令以覆盖组件视图。

php artisan vendor:publish --provider="Laraeast\LaravelBootstrapForms\Providers\BootstrapFormsServiceProvider" --tag laravel-bootstrap-forms.views

将在 resources/views/vendor/BsForm 路径下覆盖组件。

- views
	- vendor
		- BsForm
			- bootstrap4
				- text
					- default.blade.php
					- vertical.blade.php
					- custom.blade.php
				- email
					- default.blade.php
					- vertical.blade.php
					- custom.blade.php

您可以将 default.blade.php 文件复制为 custom.blade.php 并使用自定义样式。

{{ BsForm::text('name')->style('custom') }}

您也可以在表单打开之前使用 BsForm::style() 方法全局设置样式

@php(BsForm::style('custom'))

或者

@php(BsForm::resource('users')->style('custom'))

要重置自定义样式为默认值,应调用 clearStyle() 方法

@php(BsForm::clearStyle())

例如

@php(BsForm::resource('users')->style('web'))
{{ BsForm::model($user, route('users.update', $user)) }}
	{{-- All fields here uses web style  --}}
	{{ BsForm::text('name') }} 
	{{ BsForm::text('email') }} 
@php(BsForm::clearStyle())
	{{-- All fields after clearing uses default style  --}}
	{{ BsForm::text('phone') }} 
	{{ BsForm::textarea('address') }} 
	{{ BsForm::submit()->style('inline') }} 
{{ BsForm::close() }}

## 添加自定义组件

您可以将新的组件类扩展为 BaseComponent,并在 AppServiceProvider 类的 boot() 方法中注册它

<?php

namespace App\Components;

use Laraeast\LaravelBootstrapForms\Components\BaseComponent;

class ImageComponent extends BaseComponent
{
    /**
     * The component view path.
     *
     * @var string
     */
    protected $viewPath = 'components.image';

    /**
     * The image file path.
     *
     * @var string
     */
    protected $file;

    /**
     * Initialized the input arguments.
     *
     * @param mixed ...$arguments
     * @return $this
     */
    public function init(...$arguments)
    {
        $this->name = $name = $arguments[0] ?? null;

        $this->value = ($arguments[1] ?? null) ?: 'http://via.placeholder.com/100x100';

        //$this->setDefaultLabel();

        //$this->setDefaultNote();

        //$this->setDefaultPlaceholder();

        return $this;
    }

    /**
     * Set the file path.
     *
     * @param $file
     * @return $this
     */
    public function file($file)
    {
        $this->file = $file;

        return $this;
    }

    /**
     * The variables with registerd in view component.
     *
     * @return array
     */
    protected function viewComposer()
    {
        return [
            'file' => $this->file,
        ];
    }
}

然后,在您的 AppServiceProvider 类的 boot() 方法中注册组件类

<?php

namespace App\Providers;

use App\Components\ImageComponent;
use Illuminate\Support\ServiceProvider;
use Laraeast\LaravelBootstrapForms\Facades\BsForm;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        BsForm::registerComponent('image', ImageComponent::class);
        ...
    }
    ...

然后发布 BsForm 视图,并在 views/vendor/BsForm/bootstrap4/components/image/default.blade.php 路径中创建新的组件文件。

views/vendor/BsForm/bootstrap4/components/image/default.blade.php 文件的示例内容

<div class="form-group{{ $errors->has($name) ? ' has-error' : '' }}">
    @if($label)
        {{ Form::label($name, $label, ['class' => 'content-label']) }}
    @endif

    {{ Form::file($name, array_merge(['class' => 'form-control'], $attributes)) }}

    @if($inlineValidation)
        @if($errors->has($name))
            <strong class="help-block">{{ $errors->first($name) }}</strong>
        @else
            <strong class="help-block">{{ $note }}</strong>
        @endif
    @else
        <strong class="help-block">{{ $note }}</strong>
    @endif
        
    @if($file)
        <div class="row">
            <div class="col-xs-6 col-md-3">
                <a href="#" class="thumbnail">
                    <img src="{{ $file }}">
                </a>
            </div>
        </div>
    @endif
</div>

用法

{{ BsForm::image('photo', $url) }}