BootstrapForm, forms for Laravel 5

Overview

BootstrapForm, forms for Laravel 5

phpunit Total Downloads Latest Stable Version Latest Unstable Version License

This is a package for simply creating Bootstrap 3 styled form groups in Laravel 5. It extends the normal form builder to provide you with horizontal form groups completed with labels, error messages and appropriate class usage.

Introduction

Simply use the BootstrapForm facade in the place of the Form facade when you want to generate a Bootstrap 3 form group.

BootForm::text('username');

And you'll get back the following:

">
<div class="form-group">
    <label for="username" class="control-label col-md-2">Usernamelabel>
    <div class="col-md-10">
        <input type="text" name="username" class="form-control" />
    div>
div>

Of course, if there are errors for that field it will even populate them.

The username field is required.
">
<div class="form-group has-error">
    <label for="username" class="control-label col-md-2">Usernamelabel>
    <div class="col-md-10">
        <input type="text" name="username" class="form-control" />
        <span class="help-block">The username field is required.span>
    div>
div>

Installation

First, require the package using Composer.

composer require watson/bootstrap-form

Now, add these service providers to your config/app.php file (don't add the HtmlServiceProvider if you already have it).

Collective\Html\HtmlServiceProvider::class,
Watson\BootstrapForm\BootstrapFormServiceProvider::class,

And finally add these to the aliases array (note: Form and Html must be listed before BootstrapForm):

'Form'     => Collective\Html\FormFacade::class,
'HTML'     => Collective\Html\HtmlFacade::class,
'BootForm' => Watson\BootstrapForm\Facades\BootstrapForm::class,

Feel free to use a different alias for BootstrapForm if you'd prefer something shorter.

Configuration

There are a number of configuration options available for BootstrapForm. Run the following Artisan command to publish the configuration option to your config directory:

php artisan vendor:publish

Horizontal form sizes

When using a horizontal form you can specify here the default sizes of the left and right columns. Note you can specify as many classes as you like for each column for improved mobile responsiveness, for example:

col-md-3 col-sm-6 col-xs-12

Display errors

By default this package will only display the first validation error for each field. If you'd instead like to list out all the validation errors for a field, simply set this configuration option to true.

Usage

Opening a form

BootstrapForm has improved the process of opening forms, both in terms of providing Bootstrap classes as well as managing models for model-based forms.

// Passing an existing, persisted model will trigger a model
// binded form.
$user = User::whereEmail('[email protected]')->first();

// Named routes
BootForm::open(['model' => $user, 'store' => 'users.store', 'update' => 'users.update']);

// Controller actions
BootForm::open(['model' => $user, 'store' => 'UsersController@store', 'update' => 'UsersController@update']);

If a model is passed to the open method, it will be configured to use the update route with the PUT method. Otherwise it will point to the store method as a POST request. This way you can use the same opening tag for a form that handles creating and saving.

// Passing a model that hasn't been saved or a null value as the
// model value will trigger a `store` form.
$user = new User;

BootForm::open()

Routing with parameters

If the route takes parametersyou can pass them by replacing the route or action name string bwith an array. The first entry is the string for route name, followed by the parameters as you'd pass them to the route function.

BootForm::open(['update' => ['posts.comments.create', $post]])

Form variations

There are a few helpers for opening the different kinds of Bootstrap forms. By default, open() will use the the form style that you have set in the configuration file. These helpers take the same input as the open() method.

// Open a vertical Bootstrap form.
BootForm::vertical();

// Open an inline Bootstrap form.
BootForm::inline();

// Open a horizontal Bootstrap form.
BootForm::horizontal();

If you want to change the columns for a form for a deviation from the settings in your configuration file, you can also set them through the $options array.

BootForm::open(['left_column_class' => 'col-md-2', 'left_column_offset_class' => 'col-md-offset-2', 'right_column_class' => 'col-md-10']);

Text inputs

Here are the various methods for text inputs. Note that the method signatures are relatively close to those provided by the Laravel form builder but take a parameter for the form label.

// The label will be inferred as 'Username'.
BootForm::text('username');

// The field name by default is 'email'.
BootForm::email();

BootForm::textarea('profile');

// The field name by default is 'password'.
BootForm::password();

Checkbox and radio button inputs

Checkboxes and radio buttons are a little bit different and generate different markup.

View the method signature for configuration options.

// A checked checkbox.
BootForm::checkbox('interests[]', 'Laravel', 'laravel', true);

Same goes for radio inputs.

BootForm::radio('gender', 'Male', 'male');

Multiple checkboxes and radio buttons

By simply passing an array of value/label pairs you can generate a group of checkboxes or radio buttons easily.

$label = 'this is just a label';

$interests = [
    'laravel' => 'Laravel',
    'rails'   => 'Rails',
    'ie6'     => 'Internet Explorer 6'
];

// Checkbox inputs with Laravel and Rails selected.
BootForm::checkboxes('interests[]', $label, $interests, ['laravel', 'rails']);

$genders = [
    'male'   => 'Male',
    'female' => 'Female'
];

// Gender inputs inline, 'Gender' label inferred.
BootForm::radios('gender', null, $genders, null, true);

// Gender inputs with female selected.
BootForm::radios('gender', 'Gender', $genders, 'female');

Submit button

// Pretty simple.
BootForm::submit('Login');

Closing the form

// Pretty simple.
BootForm::close();

Labels

Hide Labels

You may hide an element's label by setting the the value to false.

// An input with no label.
BootForm::text('username', false);

Labels with HTML

To include HTML code inside a label:

*']); // A label with HTML code using HtmlString object BootForm::text('username', new Illuminate\Support\HtmlString('Username *')); ">
// A label with HTML code using array notation
BootForm::text('username', ['html' => 'Username *']);

// A label with HTML code using HtmlString object
BootForm::text('username', new Illuminate\Support\HtmlString('Username *'));

Help Text

You may pass a help_text option to any field to have Bootstrap Help Text appended to the rendered form group.

Form input group (suffix and prefix)

Add prefix and/or suffix to any input - you can add text, icon and buttons.

) with 'dollar' as icon {!! BootForm::text('tel', 'Phone', null, ['prefix' => BootForm::addonIcon('dollar')] ) !!} // Prefix and suffix as text {!! BootForm::text('tel', 'Phone', null, ['prefix' => BootForm::addonText('1-'), 'suffix' => BootForm::addonIcon('phone')] ) !!} // Prefix and suffix with button {!! BootForm::text('tel', 'Phone', null, ['suffix' => BootForm::addonButton('Boom!', ['class' => 'btn-danger']), 'prefix' => BootForm::addonButton('Call', ['class' => 'btn-success'])] ) !!} ">
// Suffix button with 'Call' as label and success class to button
{!! BootForm::text('tel', 'Phone', null, ['suffix' => BootForm::addonButton('Call', ['class' => 'btn-success'])] ) !!}

// Prefix button with 'Call' as label and success class to button
{!! BootForm::text('tel', 'Phone', null, ['prefix' => BootForm::addonButton('Call', ['class' => 'btn-success'])] ) !!}

// Prefix icon (I put second parameter after ) with 'dollar' as icon
{!! BootForm::text('tel', 'Phone', null, ['prefix' => BootForm::addonIcon('dollar')] ) !!}

// Prefix and suffix as text
{!! BootForm::text('tel', 'Phone', null, ['prefix' => BootForm::addonText('1-'), 'suffix' => BootForm::addonIcon('phone')] ) !!}

// Prefix and suffix with button
{!! BootForm::text('tel', 'Phone', null, ['suffix' => BootForm::addonButton('Boom!', ['class' => 'btn-danger']), 'prefix' => BootForm::addonButton('Call', ['class' => 'btn-success'])] ) !!}
Comments
  • Add support for php 8

    Add support for php 8

    This is a major update and contain breaking changes

    • drops PHP 7.x support and adopt the new PHP 8.0 syntax

    • changed method signature of getFormGroup() to not get the

    ErrorException: Required parameter $wrapperElement follows optional parameter $label
    

    error [see this link for reference]. You need to update calls to getFormGroup() method from this example:

    BootForm::getFormGroup('name','label','<div><button type="submit" class="btn btn-default">Submit</button></div>')
    

    to this

    BootForm::getFormGroup('<div><button type="submit" class="btn btn-default">Submit</button></div>','name','label')
    
    opened by daryledesilva 13
  • Make possible to add HTML code inside a label

    Make possible to add HTML code inside a label

    For now all labels are escaped. This allow us to include HTML code inside it without escaping:

    // A label with HTML code using array notation
    BootForm::text('username', ['html' => 'Username <span class="required">*</span>']);
    
    // A label with HTML code using HtmlString object
    BootForm::text('username', new Illuminate\Support\HtmlString('Username <span class="required">*</span>'));
    

    This fix #72 both using HtmlString object and array.

    opened by jgrossi 9
  • PHP 8 support

    PHP 8 support

    With PHP 8 it shows following error:

     Required parameter $wrapperElement follows optional parameter $name
    
      at vendor/watson/bootstrap-form/src/BootstrapForm.php:830
        826▕      * @param  string  $label
        827▕      * @param  string  $element
        828▕      * @return string
        829▕      */
      ➜ 830▕     public function getFormGroup($name = null, $label = null, $wrapperElement)
        831▕     {
        832▕         if (is_null($label)) {
        833▕             return $this->getFormGroupWithoutLabel($name, $wrapperElement);
        834▕         }
    
    
    opened by vedmant 8
  • laravel 5.4 - Undefined property: Illuminate\Support\MessageBag::$default

    laravel 5.4 - Undefined property: Illuminate\Support\MessageBag::$default

    In Laravel 5.4,

    If you create a input field like this: {!! BootForm::text('address') !!}

    And in your controller, validate:

            $rules = [
                'address'=>'required',
            ];
            $validator = Validator::make($request->input(), $rules);
    
            if ( $validator->fails() ) {
                return redirect()->route('post-company-create')
                    ->with(['errors'=>$validator->errors()]);
            }
    

    You'll receive this error if you submit a blank 'address': Undefined property: Illuminate\Support\MessageBag::$default

    opened by iateadonut 8
  • Revert the change to the signature

    Revert the change to the signature

    This reverts the change to the getFormGroup signature introduced with the PHP 8.0 changes.

    I've decided to change this because after further review I think it looks awkward from an API perspective. The field name and label should come first when getting a form group - a wrapper should be the last consideration.

    Clearly the test coverage is lacking here, so I'll try and follow that up next.

    opened by dwightwatson 7
  • Problem. radio() with value 0 display label

    Problem. radio() with value 0 display label

    hi BootForm::radio('node[check]', 'Check', 0) render <label for="node[check]"><inpu name="node[check]" id="node[check]" type="radio" value="Check">Check</label> maybe change $value = $value ?: $label; to$value = is_null($value) ? $label : $value; in public function radioElement($name, $label = null, $value = null, $checked = null, $inline = false, array $options = []) it will happen when use BootForm::radios() with values ['0'=>'No', '1'=>'Yes'] Thanks you.

    opened by seedo 7
  • Added support for route/action in array form

    Added support for route/action in array form

    This allows to use nested resources by adding support of routes/action in array form as mentioned in issue https://github.com/dwightwatson/bootstrap-form/issues/43

    Example:

    BootForm::open([
        'model' => $application,
        'store' => array('ApplicationController@store', $project),
        'update' => array('ApplicationController@update', $project)
    ])
    
    opened by DODMax 7
  • Check if model should be used, causes MethodNotAllowedHttpException

    Check if model should be used, causes MethodNotAllowedHttpException

    in "Bootstrapform.php" in the open function is a check on $options['model'], if this exists then the (protected) model function wil be used.

    In the model function is another check on model but this will have no effect because it would'nt go in there in the first place if no model is passed. If it doesn't go in there it wont take the $options['store'] and will give the url of the current page as a default. This will result in POSTing to the /create page wich will throw the MethodNotAllowedHttpException error.

    So either the check if model is set schould be in the open method firing either $this->form->open() or the model function, OR the model function should be public, this way it would make sense that the check is done twice.

    opened by gijsbeijer 5
  • .Standard Forms

    .Standard Forms

    Hey man this is awesome! However I can not seem to render a standard form....

    Doing this in my blade template:

    {{ BootstrapForm::openStandard()}} {{BootstrapForm::text('username')}} {{ BootstrapForm::submit('Login') }} {{ Form::close() }}

    Produces the fields like: `

    `

    The expected result would have been `

    `
    opened by jpsmith1981 5
  • redirect()->back() after failed validation not preserving empty values

    redirect()->back() after failed validation not preserving empty values

    I don't know if this is the expected behavior or what, but seems odd to me:

    Let me know if anyone can reproduce this.

    • When updating an already registered record

    • The Model has a field with required validation

    • Submit the form with this field empty

    • Validate at controller and redirect back with old inputs

    • The field now should be empty, with error messages. It have the error messages, but its filled with the registered value from database.

    // myController
    
    $model->save($request->all());
    if ($model->isInvalid()) {
          return redirect()->back()->withInput()->withErrors();
    }
    
    // myView
    
    {!! BootForm::open(['model' => $model, 'update' => 'admin.models.update']); !!}
    {!! BootForm::text('field', 'myField') !!}
    

    To add some information, the old value is filled normally after validation IF it's not empty, like when we are validating string length.

    opened by ghost 4
  • Passing null to label attribute is causing an error in the label

    Passing null to label attribute is causing an error in the label

    If the following is entered in:

    echo BootForm::text('meta_description', null);
    

    It outputs the label as: "Meta_Description"

    Rather than "Meta Description"

    Please feel free to assign this issue to me and I will solve it.

    opened by MichaelHoughton 4
  • Impossible to get a field without label

    Impossible to get a field without label

    As on version 2.3.

    If I set à label to "false" to avoid having a label, I always get label. Think forcing label to string result to à $label value to "" (empty) to $lable, in facto, $this->getLabelTitle($label, $name) never return null !

    opened by fklee 2
  • Fixing the HtmlString labels in latest versions of PHP

    Fixing the HtmlString labels in latest versions of PHP

    With this pull request the package is now compatible with the latest versions of PHP 8.*. The HTML labels were not rendered due to non-compatible type declarations in label-related methods. Enjoy!

    opened by nocodelab 4
  • Suggestion : add Error Class in Config file

    Suggestion : add Error Class in Config file

    Hi, It will be good if you could add an attribute into config file to manager error class. Something like this : config.php

    ...
    'error_class' => 'has_error'; // default
    ...
    

    Then, edit this function :

    protected function getFieldErrorClass($field, $class = config_value)
        {
            return $this->getFieldError($field) ? $class : null;
        }
    
    opened by AEK-BKF 2
  • Method chaining

    Method chaining

    Is there any plan to implement method chain behaviour? I like it because easy to customize element. I used to use adamwathan/bootform. So sad it is abandoned.

    I already take a look at watson/bootstrap-form source code and tinkering to make it method-chaining-able 🤣 . I can make it without breaking original behaviour.

    So, what do you think guys?

    opened by ifaniqbal 2
Owner
Dwight Watson
#gsd
Dwight Watson
rapyd: crud widgets for laravel. datatable, grids, forms, in a simple package

rapyd-laravel This is a pool of presentation and editing widgets (Grids and Forms) for laravel. Nothing to "generate", just some classes to let you de

Felice Ostuni 875 Dec 29, 2022
Keeping Your Laravel Forms Awake.

Caffeine for Laravel Supporting This Package This is an MIT-licensed open source project with its ongoing development made possible by the support of

GeneaLabs, LLC 839 Dec 22, 2022
Fullstack komponents to write Forms, Queries and Menus in Laravel

kompo.io • Documentation • Demos • Twitter kompo/kompo kompo/kompo is a library of Fullstack Komponents to help you write forms, queries and menus in

Bass El Hachem 107 Dec 5, 2022
A convenient helper for using the laravel-seo package with Filament Admin and Forms

Combine the power of Laravel SEO and Filament PHP. This package is a convenient helper for using the laravel-seo package with Filament Admin and Forms

Ralph J. Smit 39 Dec 21, 2022
Provides the missing range field for the Filament forms.

The missing range field for the Filament forms. Installation You can install the package via composer: composer require yepsua/filament-range-field Pu

null 11 Sep 10, 2022
A demo of how to use filament/forms to build a user-facing Form Builder which stores fields in JSON.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Dan Harrin 41 Dec 24, 2022
Filament Plugin to help implement Cloudflare turnstile into your forms.

Filament Turnstile Filament Turnstile, is a plugin to help you implement the Cloudflare turnstile. This plugin uses Laravel Turnstile Behind the scene

Coderflex 5 Jun 12, 2023
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Jan 2, 2023
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Erik C. Forés 31 Dec 18, 2022
Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Sam Rapaport 46 Oct 1, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

null 9 Dec 14, 2022
Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application.

Laravel Segment Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application. Installation You can install the pac

Octohook 13 May 16, 2022
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

Daniël de Wit 43 Dec 21, 2022
Bring Laravel 8's cursor pagination to Laravel 6, 7

Laravel Cursor Paginate for laravel 6,7 Installation You can install the package via composer: composer require vanthao03596/laravel-cursor-paginate U

Pham Thao 9 Nov 10, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Adnane Kadri 49 Jun 22, 2022
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

null 686 Dec 28, 2022
Laravel Jetstream is a beautifully designed application scaffolding for Laravel.

Laravel Jetstream is a beautifully designed application scaffolding for Laravel. Jetstream provides the perfect starting point for your next Laravel application and includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management.

The Laravel Framework 3.5k Jan 8, 2023
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022