Giter Club home page Giter Club logo

bootforms's Introduction

Important: This package is not actively maintained. For bug fixes and new features, please fork.

BootForms

This Project Has Been Deprecated. Code Climate Coverage Status

BootForms builds on top of my more general Form package by adding another layer of abstraction to rapidly generate markup for standard Bootstrap 3 forms. Probably not perfect for your super custom branded ready-for-release apps, but a huge time saver when you are still in the prototyping stage!

Installing with Composer

You can install this package via Composer by running this command in your terminal in the root of your project:

composer require adamwathan/bootforms

Laravel

If you are using Laravel 4 or 5, you can get started very quickly by registering the included service provider.

Modify the providers array in config/app.php to include the BootFormsServiceProvider:

'providers' => [
    //...
    'AdamWathan\BootForms\BootFormsServiceProvider'
  ],

Add the BootForm facade to the aliases array in config/app.php:

'aliases' => [
    //...
    'BootForm' => 'AdamWathan\BootForms\Facades\BootForm'
  ],

You can now start using BootForms by calling methods directly on the BootForm facade:

BootForm::text('Email', 'email');

Outside of Laravel

Usage outside of Laravel is a little trickier since there's a bit of a dependency stack you need to build up, but it's not too tricky.

$formBuilder = new AdamWathan\Form\FormBuilder;

$formBuilder->setOldInputProvider($myOldInputProvider);
$formBuilder->setErrorStore($myErrorStore);
$formBuilder->setToken($myCsrfToken);

$basicBootFormsBuilder = new AdamWathan\BootForms\BasicFormBuilder($formBuilder);
$horizontalBootFormsBuilder = new AdamWathan\BootForms\HorizontalFormBuilder($formBuilder);

$bootForm = new AdamWathan\BootForms\BootForm($basicBootFormsBuilder, $horizontalBootFormsBuilder);

Note: You must provide your own implementations of AdamWathan\Form\OldInputInterface and AdamWathan\Form\ErrorStoreInterface when not using the implementations meant for Laravel.

Using BootForms

Basic Usage

BootForms lets you create a label and form control and wrap it all in a form group in one call.

//  <form method="POST">
//    <div class="form-group">
//      <label for="field_name">Field Label</label>
//      <input type="text" class="form-control" id="field_name" name="field_name">
//    </div>
//  </form>
{!! BootForm::open() !!}
{!! BootForm::text('Field Label', 'field_name') !!}
{!! BootForm::close() !!}

Note: Don't forget to open() forms before trying to create fields! BootForms needs to know if you opened a vertical or horizontal form before it can render a field, so you'll get an error if you forget.

Customizing Elements

If you need to customize your form elements in any way (such as adding a default value or placeholder to a text element), simply chain the calls you need to make and they will fall through to the underlying form element.

Attributes can be added either via the attribute method, or by simply using the attribute name as the method name.

// <div class="form-group">
//    <label for="first_name">First Name</label>
//    <input type="text" class="form-control" id="first_name" name="first_name" placeholder="John Doe">
// </div>
BootForm::text('First Name', 'first_name')->placeholder('John Doe');

// <div class="form-group">
//   <label for="color">Color</label>
//   <select class="form-control" id="color" name="color">
//     <option value="red">Red</option>
//     <option value="green" selected>Green</option>
//   </select>
// </div>
BootForm::select('Color', 'color')->options(['red' => 'Red', 'green' => 'Green'])->select('green');

// <form method="GET" action="/users">
BootForm::open()->get()->action('/users');

// <div class="form-group">
//    <label for="first_name">First Name</label>
//    <input type="text" class="form-control" id="first_name" name="first_name" value="John Doe">
// </div>
BootForm::text('First Name', 'first_name')->defaultValue('John Doe');

For more information about what's possible, check out the documentation for my basic Form package.

Reduced Boilerplate

Typical Bootstrap form boilerplate might look something like this:

<form>
  <div class="form-group">
    <label for="first_name">First Name</label>
    <input type="text" class="form-control" name="first_name" id="first_name">
  </div>
  <div class="form-group">
    <label for="last_name">Last Name</label>
    <input type="text" class="form-control" name="last_name" id="last_name">
  </div>
  <div class="form-group">
    <label for="date_of_birth">Date of Birth</label>
    <input type="date" class="form-control" name="date_of_birth" id="date_of_birth">
  </div>
  <div class="form-group">
    <label for="email">Email address</label>
    <input type="email" class="form-control" name="email" id="email">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password" id="password">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

BootForms makes a few decisions for you and allows you to pare it down a bit more:

{!! BootForm::open() !!}
  {!! BootForm::text('First Name', 'first_name') !!}
  {!! BootForm::text('Last Name', 'last_name') !!}
  {!! BootForm::date('Date of Birth', 'date_of_birth') !!}
  {!! BootForm::email('Email', 'email') !!}
  {!! BootForm::password('Password', 'password') !!}
  {!! BootForm::submit('Submit') !!}
{!! BootForm::close() !!}

Automatic Validation State

Another nice thing about BootForms is that it will automatically add error states and error messages to your controls if it sees an error for that control in the error store.

Essentially, this takes code that would normally look like this:

<div class="form-group {!! $errors->has('first_name') ? 'has-error' : '' !!}">
  <label for="first_name">First Name</label>
  <input type="text" class="form-control" id="first_name">
  {!! $errors->first('first_name', '<p class="help-block">:message</p>') !!}
</div>

And reduces it to this:

{!! BootForm::text('First Name', 'first_name') !!}

...with the has-error class being added automatically if there is an error in the session.

Horizontal Forms

To use a horizontal form instead of the standard basic form, simply swap the BootForm::open() call with a call to openHorizontal($columnSizes) instead:

// Width in columns of the left and right side
// for each breakpoint you'd like to specify.
$columnSizes = [
  'sm' => [4, 8],
  'lg' => [2, 10]
];

{!! BootForm::openHorizontal($columnSizes) !!}
  {!! BootForm::text('First Name', 'first_name') !!}
  {!! BootForm::text('Last Name', 'last_name') !!}
  {!! BootForm::text('Date of Birth', 'date_of_birth') !!}
  {!! BootForm::email('Email', 'email') !!}
  {!! BootForm::password('Password', 'password') !!}
  {!! BootForm::submit('Submit') !!}
{!! BootForm::close() !!}

Additional Tips

Hiding Labels

You can hide labels by chaining the hideLabel() helper off of any element definition.

BootForm::text('First Name', 'first_name')->hideLabel()

The label will still be generated in the markup, but hidden using Bootstrap's .sr-only class, so you don't reduce the accessibility of your form.

Help Blocks

You can add a help block underneath a form element using the helpBlock() helper.

BootForm::text('Password', 'password')->helpBlock('A strong password should be long and hard to guess.')

Note: This help block will automatically be overridden by errors if there are validation errors.

Model Binding

BootForms makes it easy to bind an object to a form to provide default values. Read more about it here.

BootForm::open()->action( route('users.update', $user) )->put()
BootForm::bind($user)
BootForm::close()

Related Resources

bootforms's People

Contributors

adamwathan avatar aydinhassan avatar clemblanco avatar cpgo avatar django23 avatar javiermartinz avatar jesseleite avatar manavo avatar moura137 avatar nathanleclaire avatar propaganistas avatar robbiepaul avatar sdebacker avatar sobak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bootforms's Issues

Configurable ControllerClasses in horizontal forms

In HorizontalFormGroup.php the ControllerClass 'col-lg-' is hardCoded.

protected function getControlClass()
{
    return 'col-lg-' . $this->controlWidth;
}

Would be nice if this is configurable as well as the width itself. For example I want to set "col-sm-6 col-md-4 col-lg-2" for my labels and different settings for the control in this 3 classes again.

I really like the approach of https://github.com/dwightwatson/bootstrap-form where this can be done via laravel configs.

Version requirement

"require": {
    "php": ">=5.3.0",
    "adamwathan/form": "dev-master"
},

I assume the requirement should be changed to v0.2 instead of dev-master?

composer update not working

I'm using laravel 4 and have been using your repo.

I started getting the following error when doing a composer update.

Problem 1
- The requested package adam-wathan/boot-forms could not be found in any version, there may be a typo in the package name.

here is what i have in my composer.json

"repositories": [
{
"type": "vcs",
"url": "https://github.com/adamwathan/bootforms"
}
],
"require": {
"adam-wathan/boot-forms": "dev-master"
},

Laravel 4 normalization

Hi,

In laravel the names fields are always in first position and the value fields always in second...

To respect the Laravel's conventions it would be preferable to like this :

{{ BootForm::text('first_name', 'First Name') }}

Instead of this :

{{ BootForm::text('First Name', 'first_name') }}

Thanks

Laravel 5?

this look really good - be nice to have for Laravel 5

Option to add extra HTML after input

Hi,

Is there any option to pass extra HTML after specific input? I've got some text fields which require additional help-block (bootstrap) with some info for user.

It would be great to do something like this:
{{ BootForm::text('Price', 'price')->html('<span class="help-block">My text</span>') }}
Or
{{ BootForm::text('Price', 'price')->helpBlock('My text') }}

Current result is:
<div class="form-group"><label for="price" class="col-lg-3 control-label">Price</label><div class="col-lg-9"><input type="text" class="form-control" id="price" name="price" /></div></div>

Expected result:
<div class="form-group"><label for="price" class="col-lg-3 control-label">Price</label><div class="col-lg-9"><input type="text" class="form-control" id="price" name="price" /><span class="help-block">My text</span></div></div>

Best regards,
Mateusz

Form select element

Is Bootform doesn't support <select> element?
I'm trying as follows, but didn't work

{{ BootForm::select('Arc Types', array('bundle'=>'Rounded', 'linear'=>'Linear')) }}

showing error

Next exception 'ErrorException' with message 'Illegal offset type in isset or empty

Laravel Error

I managed to get the files installed however here is a new error i'm getting

Argument 1 passed to AdamWathan\Form\ErrorStore\IlluminateErrorStore::__construct() must be an instance of Illuminate\Session\Store, instance of Illuminate\Session\SessionManager given, called in /vendor/adamwathan/bootforms/src/AdamWathan/BootForms/BootFormsServiceProvider.php on line 36 and defined

Invalid argument supplied for foreach()

I am getting this error: Invalid argument supplied for foreach()

In file: /home/forge/staging.domain.com/vendor/adamwathan/bootforms/src/AdamWathan/BootForms/HorizontalFormBuilder.php

protected function getLabelClass()
{
    $class = '';
    foreach ($this->columnSizes as $breakpoint => $sizes) { // this line
        $class .= sprintf('col-%s-%s ', $breakpoint, $sizes[0]);
    }

Triggered when I do:

{!! BootForm::text('Your name', 'name'); !!}

Inside my form I opened like this:

{!! BootForm::openHorizontal(3, 9)->post()->action('/auth/register') !!}

I think it happend after updating my composer file.

My composer:

"require": {
    "laravel/framework": "~5.0",
    "adamwathan/bootforms": "0.6.3",
},

I have also tried going back to version 0.5.0 - but same issue occurs.

Bug in select ?

Hello,

I try to make a select with this code:

...
$formatlist=array("0" => "Select a format", "1"=>"A4", "2"=>"A3"); 
...

{{ BootForm::select('Format','format',$formatlist)}}

and the result is:

<select id="format" class="form-control" name="format">
<option value="Select a format">Select a format</option>
<option value="A4">A4</option>
<option value="A3">A3</option>
</select>

instead of

<select id="format" class="form-control" name="format">
<option value="0">Select a format</option>
<option value="1">A4</option>
<option value="2">A3</option>
</select>

Where is the mistake ? can you help me please ?

Best regards,

Dominique

Binding to model

I don't know if this is at all possible, but I don't see an example of binding to a model. How do I do that?

Passing $options to open()

Am I missing how we pass $options through to $this->builder->open(); ?

I would like to set the route via $options

Add support to input array

I create a request

php artisan make:request FormRequest

Create a rules for input array

public function rules()
{
$rules = [];
foreach($this->request->get('input_name') as $key)
{
$rules['input_name.'.$key] = 'required';
}
return $rules;
}

But receive a error:

FatalErrorException in FormGroup.php line 0: Method AdamWathan\Form\Elements\Text::__toString() must not throw an exception

some questions about form-group

Hi there, i have some questions:

1 can i custon two or more div width in the same form ?
first

and second
like this
2 can i add two or more button in one form-group ?

sorry for my poor english ,Thanks!!!

<form class="form-horizontal" role="form">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-5">
      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-8">
      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" class="btn btn-default">button1</button>
      <button type="button"  class="btn btn-default">button2</button>
    </div>
  </div>
</form>

helpBlock documentation

Undocumented feature: if you want to add a help line or message, you can chain
->helpBlock('message')

Default Textarea value

Hi,

Maybe it could be nice to add a default value for the textarea like that :

BootForm::textarea('Name' , 'name' , 'default value')

Good job

Placing submit and cancel button in one group

Perhaps someone can tell me if there is an easier way to get submit and cancel buttons next to each other? The submit button goes in a group, so if there is a way to add the cancel button too in the same group that would solve this.

I am using this now, for lack of better:

  {!! Form::submit('Update', array('class' => 'btn btn-info')) !!}
  {!! link_to_route('clubs.index', 'Cancel', null, array('class' => 'btn')) !!}

New Version

 composer.json                                      |  2 +-
 src/AdamWathan/BootForms/BasicFormBuilder.php      | 10 ++--
 src/AdamWathan/BootForms/Elements/FormGroup.php    | 11 +++--
 src/AdamWathan/BootForms/Elements/GroupWrapper.php | 14 +++++-
 src/AdamWathan/BootForms/HorizontalFormBuilder.php | 12 ++---
 tests/BasicFormBuilderTest.php                     | 53 +++++++++++++++++++---
 tests/FormGroupTest.php                            |  5 +-
 tests/HorizontalFormBuilderTest.php                |  2 +-
 8 files changed, 82 insertions(+), 27 deletions(-)

diff --git a/composer.json b/composer.json
index 2a3bf1b..5b43a48 100644
--- a/composer.json
+++ b/composer.json
@@ -10,7 +10,7 @@
     "license": "MIT",
     "require": {
         "php": ">=5.3.0",
-        "adamwathan/form": "v0.2"
+        "adamwathan/form": "dev-master"
     },
     "require-dev": {
         "phpunit/phpunit": "3.7.*",
diff --git a/src/AdamWathan/BootForms/BasicFormBuilder.php b/src/AdamWathan/BootForms/BasicFormBuilder.php
index 26c27f9..c454872 100644
--- a/src/AdamWathan/BootForms/BasicFormBuilder.php
+++ b/src/AdamWathan/BootForms/BasicFormBuilder.php
@@ -23,7 +23,7 @@ class BasicFormBuilder
        $formGroup = new FormGroup($label, $control);

        if ($this->builder->hasError($name)) {
-           $formGroup->helpBlock(new HelpBlock($this->builder->getError($name)));
+           $formGroup->helpBlock($this->builder->getError($name));
            $formGroup->addClass('has-error');
        }

@@ -41,7 +41,7 @@ class BasicFormBuilder

        return $this->formGroup($label, $name, $control);
    }
-   
+
    public function password($label, $name)
    {
        $control = $this->builder->password($name);
@@ -81,7 +81,7 @@ class BasicFormBuilder
        $checkGroup = new CheckGroup($label);

        if ($this->builder->hasError($name)) {
-           $checkGroup->helpBlock(new HelpBlock($this->builder->getError($name)));
+           $checkGroup->helpBlock($this->builder->getError($name));
            $checkGroup->addClass('has-error');
        }
        return $checkGroup;
@@ -151,7 +151,7 @@ class BasicFormBuilder
        $formGroup = new FormGroup($label, $control);

        if ($this->builder->hasError($name)) {
-           $formGroup->helpBlock(new HelpBlock($this->builder->getError($name)));
+           $formGroup->helpBlock($this->builder->getError($name));
            $formGroup->addClass('has-error');
        }

@@ -162,4 +162,4 @@ class BasicFormBuilder
    {
        return call_user_func_array(array($this->builder, $method), $parameters);
    }
-}
\ No newline at end of file
+}
diff --git a/src/AdamWathan/BootForms/Elements/FormGroup.php b/src/AdamWathan/BootForms/Elements/FormGroup.php
index 7add9df..ee3acbc 100644
--- a/src/AdamWathan/BootForms/Elements/FormGroup.php
+++ b/src/AdamWathan/BootForms/Elements/FormGroup.php
@@ -17,7 +17,7 @@ class FormGroup extends Element
    }

    public function render()
-   {       
+   {
        $html  = '<div';
        $html .= $this->renderAttributes();
        $html .= '>';
@@ -30,9 +30,12 @@ class FormGroup extends Element
        return $html;
    }

-   public function helpBlock(HelpBlock $helpBlock)
+   public function helpBlock($text)
    {
-       $this->helpBlock = $helpBlock;
+       if (isset($this->helpBlock)) {
+           return;
+       }
+       $this->helpBlock = new HelpBlock($text);
        return $this;
    }

@@ -60,4 +63,4 @@ class FormGroup extends Element
        call_user_func_array(array($this->control, $method), $parameters);
        return $this;
    }
-}
\ No newline at end of file
+}
diff --git a/src/AdamWathan/BootForms/Elements/GroupWrapper.php b/src/AdamWathan/BootForms/Elements/GroupWrapper.php
index ff23eb1..26d500a 100644
--- a/src/AdamWathan/BootForms/Elements/GroupWrapper.php
+++ b/src/AdamWathan/BootForms/Elements/GroupWrapper.php
@@ -16,14 +16,26 @@ class GroupWrapper
        return $this->formGroup->render();
    }

+   public function helpBlock($text)
+   {
+       $this->formGroup->helpBlock($text);
+       return $this;
+   }
+
    public function __toString()
    {
        return $this->render();
    }

+   public function labelClass($class)
+   {
+       $this->formGroup->label()->addClass($class);
+       return $this;
+   }
+
    public function __call($method, $parameters)
    {
        call_user_func_array(array($this->formGroup->control(), $method), $parameters);
        return $this;
    }
-}
\ No newline at end of file
+}
diff --git a/src/AdamWathan/BootForms/HorizontalFormBuilder.php b/src/AdamWathan/BootForms/HorizontalFormBuilder.php
index 09ba909..20ac91d 100644
--- a/src/AdamWathan/BootForms/HorizontalFormBuilder.php
+++ b/src/AdamWathan/BootForms/HorizontalFormBuilder.php
@@ -35,7 +35,7 @@ class HorizontalFormBuilder extends BasicFormBuilder
    public function open()
    {
        return $this->builder->open()->addClass('form-horizontal');
-   }   
+   }

    protected function formGroup($label, $name, $control)
    {
@@ -49,7 +49,7 @@ class HorizontalFormBuilder extends BasicFormBuilder
        $formGroup = new HorizontalFormGroup($label, $control, $this->controlWidth);

        if ($this->builder->hasError($name)) {
-           $formGroup->helpBlock(new HelpBlock($this->builder->getError($name)));
+           $formGroup->helpBlock($this->builder->getError($name));
            $formGroup->addClass('has-error');
        }

@@ -82,7 +82,7 @@ class HorizontalFormBuilder extends BasicFormBuilder
        $checkGroup = new CheckGroup($label);

        if ($this->builder->hasError($name)) {
-           $checkGroup->helpBlock(new HelpBlock($this->builder->getError($name)));
+           $checkGroup->helpBlock($this->builder->getError($name));
            $checkGroup->addClass('has-error');
        }

@@ -90,7 +90,7 @@ class HorizontalFormBuilder extends BasicFormBuilder
    }

    public function radio($label, $name, $value = null)
-   {   
+   {
        if (is_null($value)) {
            $value = $label;
        }
@@ -114,7 +114,7 @@ class HorizontalFormBuilder extends BasicFormBuilder
        $formGroup = new HorizontalFormGroup($label, $control, $this->controlWidth);

        if ($this->builder->hasError($name)) {
-           $formGroup->helpBlock(new HelpBlock($this->builder->getError($name)));
+           $formGroup->helpBlock($this->builder->getError($name));
            $formGroup->addClass('has-error');
        }

@@ -125,4 +125,4 @@ class HorizontalFormBuilder extends BasicFormBuilder
    {
        return call_user_func_array(array($this->builder, $method), $parameters);
    }
-}
\ No newline at end of file
+}
diff --git a/tests/BasicFormBuilderTest.php b/tests/BasicFormBuilderTest.php
index 35f954b..d019639 100644
--- a/tests/BasicFormBuilderTest.php
+++ b/tests/BasicFormBuilderTest.php
@@ -46,6 +46,19 @@ class BasicFormBuilderTest extends PHPUnit_Framework_TestCase
        $this->assertEquals($expected, $result);
    }

+   public function testRenderTextGroupWithErrorOverridesCustomHelpBlock()
+   {
+       $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
+       $errorStore->shouldReceive('hasError')->andReturn(true);
+       $errorStore->shouldReceive('getError')->andReturn('Email is required.');
+
+       $this->builder->setErrorStore($errorStore);
+
+       $expected = '<div class="form-group has-error"><label class="control-label" for="email">Email</label><input type="text" name="email" id="email" class="form-control"><p class="help-block">Email is required.</p></div>';
+       $result = $this->form->text('Email', 'email')->helpBlock('some custom text')->render();
+       $this->assertEquals($expected, $result);
+   }
+
    public function testRenderTextGroupWithOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
@@ -133,21 +146,21 @@ class BasicFormBuilderTest extends PHPUnit_Framework_TestCase

    public function testRenderSubmit()
    {
-       $expected = '<input type="submit" value="Submit" class="btn btn-default">';
+       $expected = '<button type="submit" class="btn btn-default">Submit</button>';
        $result = $this->form->submit()->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderSubmitWithAlternateStyling()
    {
-       $expected = '<input type="submit" value="Submit" class="btn btn-success">';
+       $expected = '<button type="submit" class="btn btn-success">Submit</button>';
        $result = $this->form->submit('Submit', 'btn-success')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderSubmitWithValue()
    {
-       $expected = '<input type="submit" value="Sign Up" class="btn btn-success">';
+       $expected = '<button type="submit" class="btn btn-success">Sign Up</button>';
        $result = $this->form->submit('Sign Up', 'btn-success')->render();
        $this->assertEquals($expected, $result);
    }
@@ -413,12 +426,40 @@ class BasicFormBuilderTest extends PHPUnit_Framework_TestCase
        $this->assertEquals($expected, $result);
    }

-    public function testCanAddClassToUnderlyingControl()
-    {
+   public function testCanAddClassToUnderlyingControl()
+   {
        $expected = '<div class="form-group"><label class="control-label" for="color">Favorite Color</label><select name="color" id="color" class="form-control my-class"><option value="1">Red</option><option value="2">Green</option><option value="3">Blue</option></select></div>';

        $options = array('1' => 'Red', '2' => 'Green', '3' => 'Blue');
        $result = $this->form->select('Favorite Color', 'color', $options)->addClass('my-class')->render();
        $this->assertEquals($expected, $result);
-    }
+   }
+
+   public function testRenderTextGroupWithLabelClass()
+   {
+       $expected = '<div class="form-group"><label class="control-label required" for="email">Email</label><input type="text" name="email" id="email" class="form-control"></div>';
+       $result = $this->form->text('Email', 'email')->labelClass('required')->render();
+       $this->assertEquals($expected, $result);
+   }
+
+   public function testBindObject()
+   {
+       $object = $this->getStubObject();
+       $this->form->bind($object);
+       $expected = '<div class="form-group"><label class="control-label" for="first_name">First Name</label><input type="text" name="first_name" value="John" id="first_name" class="form-control"></div>';
+       $result = $this->form->text('First Name', 'first_name')->render();
+       $this->assertEquals($expected, $result);
+   }
+
+   private function getStubObject()
+   {
+       $obj = new stdClass;
+       $obj->email = '[email protected]';
+       $obj->first_name = 'John';
+       $obj->last_name = 'Doe';
+       $obj->date_of_birth = new \DateTime('1985-05-06');
+       $obj->gender = 'male';
+       $obj->terms = 'agree';
+       return $obj;
+   }
 }
diff --git a/tests/FormGroupTest.php b/tests/FormGroupTest.php
index 694152c..4260434 100644
--- a/tests/FormGroupTest.php
+++ b/tests/FormGroupTest.php
@@ -75,11 +75,10 @@ class FormGroupTest extends PHPUnit_Framework_TestCase
         $label = $this->builder->label('Email');
         $text = $this->builder->text('email');
         $formGroup = new FormGroup($label, $text);
-        $helpBlock = new HelpBlock('Email is required.');
-        $formGroup->helpBlock($helpBlock);
+        $formGroup->helpBlock('Email is required.');

         $expected = '<div class="form-group"><label>Email</label><input type="text" name="email"><p class="help-block">Email is required.</p></div>';
         $result = $formGroup->render();
         $this->assertEquals($expected, $result);
     }
-}
\ No newline at end of file
+}
diff --git a/tests/HorizontalFormBuilderTest.php b/tests/HorizontalFormBuilderTest.php
index 3481430..dd3bcc4 100644
--- a/tests/HorizontalFormBuilderTest.php
+++ b/tests/HorizontalFormBuilderTest.php
@@ -169,7 +169,7 @@ class HorizontalFormBuilderTest extends PHPUnit_Framework_TestCase

    public function testRenderSubmit()
    {
-       $expected = '<div class="form-group"><div class="col-lg-offset-2 col-lg-10"><input type="submit" value="Submit" class="btn btn-default"></div></div>';
+       $expected = '<div class="form-group"><div class="col-lg-offset-2 col-lg-10"><button type="submit" class="btn btn-default">Submit</button></div></div>';
        $result = $this->form->submit()->render();
        $this->assertEquals($expected, $result);
    }

OldInput laravel

Hi,

I can't seem to get the oldinput to work in laravel
i have this form

<?php $formTypeEdit=true; ?>
            {!! BootForm::openHorizontal($columnSizes)->put() !!}
            {{--{!! BootForm::bind($user) !!}--}}
            <h1>Edit User</h1>

                <?php if($formTypeEdit){ ?>
                {!! BootForm::hidden('id') !!}
                <?php }?>
                {!! BootForm::email(trans('user.fields.email'), 'email') !!}
                <?php if(!$formTypeEdit){?>
                {!! BootForm::password(trans('user.fields.password'), 'password') !!}
                {!! BootForm::password(trans('user.fields.confirm_password'),'password_confirmation') !!}
                <?php }?>
                {!! BootForm::text(trans('user.fields.firstname'),'firstname') !!}
                {!! BootForm::text(trans('user.fields.lastname'),'lastname') !!}
            {!! BootForm::submit('edit') !!}
            {!!  BootForm::close() !!}

should i add something to it to get it to work or should it work out of the box?

Thanks in advance,

call_user_func_array() error

System info

Elementary OS 32bit (Ubuntu effectively I think!)
PHP 5.5.9

Installation info

Following the instructions listed here : https://github.com/adamwathan/bootforms

composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "laravel/framework": "4.2.*",
        "adamwathan/bootforms": "dev-master"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev"
}

Installed by running composer update

Testing

I use php artisan serve to test, so I am running on localhost:8000

Error

ErrorException (E_UNKNOWN)

call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

in file

/home/ct14/Laravel/site3/vendor/adamwathan/bootforms/src/AdamWathan/BootForms/BootForm.php

Thanks for your time!

Laravel 5 prints HTML escaped instead of non-escaped

First time around with BootForms and i'm trying it with Laravel 5 right now and if i:

{{ BootForm::Open()->post()->action('/data/exalted-types/store') }}
{{ BootForm::Close() }}

It simply outputs

<form method="POST" action="/data/exalted-types/store"> </form>

But this is escaped HTML that can be viewed in the browser, the real code output is:

&lt;form method=&quot;POST&quot; action=&quot;/data/exalted-types/store&quot;&gt;
&lt;/form&gt;

What am i doing wrong?

Not sure this is Laravel 5 specific, this could be due to my inexperience!

Generate CSRF token automatically

Hi,

with L5 latest update the CSRF middleware is added to the application stack which means it's executed every time. For some reason, your Form Builder is not generating the hidden input for the _token. Any idea why or do we need to call a method?

Thanks!

Multiple Select

How can I implement a multiple select box?
'<$select multiple$>

Passing array of options to select

BootForm::select()

Does not properly handle an array as the second argument.
e.g. the default Laravel form builder;
{{ Form::select('provider_id', $providers) }}
works fine, but:
{{ BootForm::select('provider_id', $providers) }}
Throws a fatal error;

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Method AdamWathan\Form\Elements\Label::__toString() must not throw an exception 

The manual at https://github.com/adamwathan/form#selects implies that it should work, assuming the syntax is the same for BootForm.

Uploading multiple files

I need to upload multiple files in my app. To that with Laravel Forms, one would do

Form::files('files[]',array('multiple'=>true)

How can I accomplish this with BootForms?

Optional label

There is any way to create form elements without label?

Something like this will be usefull:

{!! BootForm::text(null, 'email')->placeholder('Email') !!}
<input class="form-control" placeholder="E-mail" name="email" type="email">

Feature: Ability to set default for the checkbox field with parameter

Currently you can set the value of the checkbox to checked on not with one of the following:

->defaultToChecked()
->defaultToUnchecked()

However these methods do not take a parameter. When creating an update from I don't now when writing the view whether the default should be checked or not, as it depends on the record being edited.

What I would like to be able to do is pass an optional boolean parameter to the methods above. If the parameter is ommited it defaults to true. However if you pass false it does the opposite. E.g. ->defaultToChecked(false) would default to not checked. This way I can write some little conditional code in the parameter.

For example:

BootForm::checkbox('Active', 'active')->defaultToChecked($user->active?true:false)

N.B. in the code I see there is a protected method setChecked which basically works as I want it to, but then itis protected and not for the default value.

Feature: Form Token

It would be great if the BootForm::open() inserted the Form::token automatically or passing it a value to insert this information

.form-group customization?

I often layout my forms using Bootstrap's grid system, ie) http://puu.sh/gsISV/575bc100fb.png

What do you think of adding the following two methods?

BootForm::text('Name', 'name')->groupAttribute('class', 'form-group col-md-6')
BootForm::text('Name', 'name')->groupAddClass('col-md-6')

Either of the above would output...

<div class="form-group col-md-6">
  ...
</div>

You can see I am mirroring the attribute() and addClass() methods you already have implemented, but for .form-group elements instead of .form-control elements. I feel this would add more layout flexibility. Thoughts?

PS. Input groups would also be sick for those icons I have in there. I see there's another issue open for that though ;)

PATCH not implemented

I used this to get PATCH to work

{!! BootForm::openHorizontal(['sm' => [4, 8], 'lg' => [1, 11]])->action(route('clubs.update', [$club->id])) !!}
  {{ BootForm::bind($club) }}
  {!! BootForm::hidden('_method')->value('PATCH') !!}

I can see in the code that 'PUT' gets an automatic hidden method, but PATCH doesn't. I am not saying this is a bug, but it's not really elegant to have to put hidden fields myself.

Keep getting exception when using BootForm::Select

I'm using Laravel 5 (if that matter anyhow) to render a list of options to a template using

{!! BootForm::Select('Exalted type', $exaltedTypes->lists('name', 'id')) !!}

The value of my list of option is

array (size=5)
    1 => string 'Solars' (length=6)
    2 => string 'Terrestrials' (length=12)
    3 => string 'Sidereals' (length=9)
    4 => string 'Lunars' (length=6)
    5 => string 'Abyssals' (length=8)

And the error i keep getting is:

FatalErrorException in FormGroup.php line 0: Method AdamWathan\Form\Elements\Label::__toString() must not throw an exception in FormGroup.php line 0
at HandleExceptions->fatalExceptionFromError(array('type' => '1', 'message' => 'Method AdamWathan\Form\Elements\Label::__toString() must not throw an exception', 'file' =>  C:\wamp\www\exalted\vendor\adamwathan\bootforms\src\AdamWathan\BootForms\Elements\FormGroup.php', 'line' => '0')) in HandleExceptions.php line 116
at HandleExceptions->handleShutdown()

Do you have an idea of what might be wrong?

Array rules vs inputs array

Hi Adam,
I found an issue when you are working with input arrays. In these cases, the validation rules in laravel should be added with dots. This makes imposible for the builder finding an error with the input name.

BasicFormBuilder.php, line 25:

    if ($this->builder->hasError($name)) {
        $formGroup->helpBlock($this->builder->getError($name));
        $formGroup->addClass('has-error');
    }

If you have rules like this:
$rules['stock_attributes.1'] = "required";

hasError will look for errors at stock_attributes[1], not stock_attributes.1.

I made a quick fix:
$name = str_replace('[', '.', $name);
$name = str_replace(']', '', $name);

    if ($this->builder->hasError($name)) {

Do you find it OK?

Thanks!

[Feature] Required field

Hi,

Is there any option to mark field as required? I see this like new method on form element, like:
BootForm::text('Name', 'name')->required()
And then field will turn red with additional * or something :)

Question : Default values on a multiple select

Hello,

I just would like to know how to set multiple default values for a select with the "multiple" attribute.

I've tried to do something like this :

$tagOptions = array(
'tag1'=>'Tag 1',
'tag2'=>'Tag 2',
'tag3'=>'Tag 3'
);

BootForm::select('Tags','tags[]', $tagOptions)->attribute("multiple","multiple")->select(array('tag1','tag3'));

But the select method works only to select a single value.

Thank you very much

Add support for Laravel route

Hi @adamwathan,

The package is awesome!
It would be perfect (to me) if I could declare route name (with route parameters) in place for the action.

Is there a reason this is not implemented?
Are you interested by implementing it?

:)

J.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.