Giter VIP home page Giter VIP logo

twitter_bootstrap_form_for's Introduction

Twitter Bootstrap Form For

WARNING! This is for Rails 4 and Bootstrap 3 (current in RC).

twitter_bootstrap_form_for is a Rails FormBuilder DSL that, like Formtastic, makes it easier to create semantically awesome, readily-stylable, and wonderfully accessible HTML forms in your Rails applications. It abides by the markup expectations of Twitter Bootstrap, make your forms look great right out of the box.

However, it also tries not to do too much. Rather than try to guess at input types and provide an exhaustive set of options for each tag helper (as Formtastic does), it only lightly wraps the existing Rails form tag helpers.

Dependencies

  • Rails 4
  • Bootstrap-sass, pull from branch 3 off github

gem 'bootstrap-sass', :git => 'git://github.com/thomas-mcdonald/bootstrap-sass.git', :branch => '3'

Syntax

= twitter_bootstrap_form_for @user, layout: 'vertical (default) OR horizontal OR inline', default_div_class: 'col-lg-10 (default)', role: 'form (default)' do |user|

  / wraps a section in a fieldset with the provided legend text
  = user.inputs 'Sign up', :class => 'sign_up' do

    / generates a standard email field; also showing overriding the div_class around the input element on a horizontal form
    = user.email_field :email, :placeholder => '[email protected]', div_class: 'col-md-6'

    / generates a password field with a descriptive aside
    = user.password_field :password do
      %span.help-block
        Must be no larger than 6 characters<br/>
        Must contain only the letters 'x' or 'p'

    / a field with a custom label
    = user.password_field :password_confirmation, 'Confirm Password'

    / input fields with custom add-ons
    = user.text_field :twitter_id, 'Twitter', :class => 'medium', :add_on => :prepend do
      %span.add-on @

    / select fields now have the second parameter as a label
    = user.date_select :born_on, 'Born on', {}, :class => 'small'

    / inline inputs are not automatically labeled
    = user.inline 'Interests' do |inline|
      #{inline.text_field :interest_1, :class => 'small'},
      #{inline.text_field :interest_2, :class => 'small'}, and
      #{inline.text_field :interest_3, :class => 'small'}

    / group of radio buttons
    = user.toggles 'Email Preferences' do
      = user.radio_button :email, 'HTML Email', :html, :checked => true
      = user.radio_button :email, 'Plain Text', :plain

    / group of checkboxes
    = user.toggles 'Agreements' do
      = user.check_box :agree,   'I agree to the abusive Terms and Conditions'
      = user.check_box :spam,    'I agree to receive all sorts of spam'
      = user.check_box :spammer, 'I agree to let the site spam others through my Twitter account'

  / wraps buttons in a distinctive style
  = user.actions do
    = user.submit 'Sign up'
    = button_tag  'Cancel', :type => 'reset', :class => 'btn'

That code produces the following output, with no custom stylesheets.

That's it. All of the Rails field helpers you know and love work just like their normal FormBuilder counterparts, but with minor extensions to expose the functionality anticipated by Twitter Bootstrap.

Form Helper Changes

The changes this FormBuilder effects to the existing Rails form helpers is simple:

  • the second parameter becomes the label (pass false to disable, nil for default)
  • the last options hash accepts an :add_on key
  • if a block is passed, the HTML it outputs is placed immediately after the input

Known Bugs

  • inline fields don't receive error markup (issue #28)

twitter_bootstrap_form_for's People

Contributors

boz avatar derekprior avatar hron84 avatar lukesaunders avatar stouset avatar zzip 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

twitter_bootstrap_form_for's Issues

Submit button not becomes primary button

The f.submit method generates wrong markup, submit button should marked with 'btn-primary' class not btn and primary - latest bootstrap does not supports second solution.

Custom form helpers results in multiple labels

I have a custom form field that I created that just passes off a value and class to a text field and when using it in a twitter_bootstrap_form_for it results in a label being wrapped around the element twice.

The code for my form field is the following:

def date_field(field_name, index, options={})
  options.merge!(:value => object.send(field_name).to_s, :class => "datePicker")

  text_field field_name, options
end

and the code for my form is the following:

= twitter_bootstrap_form_for([@event, @day]) do |f|
  = f.inputs 'Day' do
    = f.text_field :name
    =f.date_field :date
  = f.actions do
    = f.submit "Save"
    = button_tag 'Cancel', :type => 'reset', :class => 'btn'

And the output HTML looks like this:

<div id="day_date_input" class=" clearfix">
  <label for="day_date">Date</label>
  <div class="input">
    <div id="day_date_input" class=" clearfix">
      <label for="day_date">Date</label>
      <div class="input">
        <input type="text" value="12/22/2011" size="30" name="day[date]" id="day_date" class="datePicker hasDatepicker"></div>
      </div>
    </div>
  </div>
</div>

Am I doing something wrong or is this an issue with using custom form helpers with this gem?

Support for i18n?

It seems that the standard form builder methods support i18n just fine. The inputs and inline_inputs methods do not, however. Would it be worth adding some i18n to those methods inside the gem, or should the user be forced to call t() in the view? I'm still becoming familiar with the i18n API myself, so I'm not sure how this is usually handled.

If tackling it in the gem is desired, I think the simplest way might be to just call translate when those methods try to throw down a label. That works fine if you pass, say, a symbol as the label. That'd be a clear indication that you'd want translation done. What about the case where the user passes a string as the label (i.e. 'fieldsets.user_information')? How would we know if they want that translated or if they want to render that string directly?

Is there a standard practice for this? simple_form leverages the existing standard location for label translations (helpers.label.model.field) but they do not introduce new elements.

twitter_bootstrap_fields_for not working

When trying to do twitter_bootstrap_fields_for, and then call new_form.inputs, this error is shown "undefined method `inputs' for #<ActionView::Helpers::FormBuilder"

Errors with add-ons

I thought I'd seen this issue arise before here on github, but I can't find it right now, so I'm posting again.

When a validation error occurs, a red error message is displayed next to form elements, as it should be. But when the input has an add-on, then the add-on appears in the wrong place. For instance, a prepended dollar sign appears after the error message.

I uploaded a pic for reference:

http://www.smidwap.com/addon_problem.jpg

Wrong class on input wrappers

Normal input rendered with this markup:

<div class="clearfix" id="post_video_input">
  <div class="input">
    <input id="post_video" name="post[video]" size="30" type="text" />
  </div>
</div>

Latest Twitter bootstrap requires following markup (I kept current classes too):

<div class="control-group clearfix" id="post_video_input">
  <div class="controls input">
    <input id="post_video" name="post[video]" size="30" type="text" />
  </div>
</div>

Plus, on validation errors .control-group should marked with error class to make input as red.

For details, check latest docs

Consider making a twitter_bootstrap_form version

The current version of twitter_bootstrap_form_for works with objects.
Consider making a version of the method (maybe named twitter_bootstrap_form) that just generates the form.

As an example, I have the following form, and I'd like to use twitter_bootstrap_form for it

<%= form_tag({:controller => :reminders,  :action => :create}, {:remote => remote?, :class => "generic_form", :id => "new_reminder"}) do %>
  <%= render 'shared/error_messages', :object => @reminder %>
  <fieldset>
    <%= hidden_field :idea, :id %>
    <legend>Remind me to</legend>
    <ol>
      <li>
        <span class="title"><%= @idea.content %></span>
      </li>  
      <li>
        <%= label_tag :reminder_reminder_date, "on" %>
        <%= text_field :reminder, :reminder_date, :placeholder => "Reminder date" %>
        <%= errors_for_field(@reminder, :reminder_date) %>
      </li>
      <li>
        <%= label_tag :reminder_privacy_id, "as" %>
        <%= collection_select(:reminder, :privacy_id, Privacy.all, :id, :name) %>
      </li>
  </ol>
  </fieldset>
  <% unless hide_buttons? %>
  <fieldset>
    <%= submit_tag submit_button_name %>
  </fieldset>
  <% end %>
<% end %>

_tag helpers

I have noticed that a lot of the _tag helpers do not create the labels. For example f.text_field :text will create all the html markup for a twitter bootstrap label but text_field_tag :text will not.

From a POLS perspective I think the _tag helpers should behave as close as possible to their non_tag counterparts.

Incorrect Error Markup

In the twitter bootstrap documentation, a field with errors is presented with the following markup:

<div class="clearfix error">
  <label for="errorInput">Input with error</label>
    <div class="input">
      <input class="xlarge error" id="errorInput" name="errorInput" size="30" type="text">
      <span class="help-inline">Small snippet of help text</span>
  </div>
</div>

I created the following form where login is a required field

= twitter_bootstrap_form_for ['admin', @location] do |f|
  = f.text_field :name

The HTML that is generated on error is:

<div class=" clearfix error" id="location_name_input">
  <div class="field_with_errors">
    <label for="location_name">Name</label>
  </div>
  <div class="input">
    <div class="field_with_errors">
      <input id="location_name" name="location[name]" size="30" type="text" />
    </div>
    <span class="help-inline">can't be blank</span>
  </div>
</div>

There seem to be two extra divs (one each wrapping the label and the actual input tag). I think these are rails artifacts. The problem is, the "can't be blank" text gets rendered below the input rather than next to it because the div.field_with_errors is a block element. I can work around this with

.field_with_errors {
  display: inline;
}

but is there any way those extra divs can be eliminated entirely?

Rails 4.0 Support

Since twitter_bootstrap_form_for relies on actionpack ~> 3 it fails to work with Rails 4.0. Any chance we can get the dependency upgraded in the gemspec?

Resolving dependencies............................................................
Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    twitter_bootstrap_form_for (>= 2.0.1.0.rc1) ruby depends on
      actionpack (~> 3) ruby

    rails (>= 4.0.0) ruby depends on
      actionpack (4.0.0)

select doesn't accept :class or :disabled attributes

Maybe I'm missing something...but when I pass class or disabled attributes to the select option, they don't get passed through to the form.

<%= f.select(:foo,"Foo",foo_items_for_select,:disabled => true)%>

I checked and the attributes do get passed to text_fields

Any ideas on how to include this?

date_select??

Hi!

When i try to use a f.date_select i get an "can't convert Symbol into String". What gives?

  • Kai

make it work for objects other than ActiveModel

For example if I use the session object

<%= twitter_bootstrap_form_for(session, :url => sessions_path) do |f| %>

I get this error:

undefined method `model_name' for Rack::Session::Abstract::SessionHash:Class

Release 2.0.1.0.rc2

The gemspec in version 2.0.1.0.rc1 is pessimistically locked to

s.add_dependency 'railties',   '~> 3'

which precludes using railties (read: Rails) versions greater than 3. I can see that the bootstrap-2.0 branch has fixed this issue in 2667469. Can that change be released as a new gem version?

Inline errors for toggles

As far as I can tell, master is missing inline errors for toggles.

I wrote a quick fix so that I can use this library on a project, but it's not pull-worthy: coshx@36ca5db

If I understood the reason for the toggle abstraction, I'd try to come up with a real fix.

Placeholder on errors.

If a text field has an error associated with it then I think the current placeholder behaviour leads to confusion.

The field text loses its grey colouring and becomes red, this means that the colour hinting is lost and can lead to user confusion (Especially in cases where we are validating_presence_of).

I would either:

Keep grey colouring on placeholder text no matter what
or
Remove placeholder text in case of errors on the field.

What do you guys think?

Select tags broken

Select tags with the following definition:

twitter_bootstrap_form_for @model do |f|
  f.select :field_name, [['one',1],['Two',2]]

do not render properly. It appears that the options array is being put into the label field.

<div class="clearfix" id="model_field_name_input"><label for="model_field_name">one1two2</label><div class="input"><select id="model_field_name" name="model[field_name]"></select></div></div>

<select> does not accept html options

Correct me if I'm wrong, but in standard Rails forms, you can specify HTML options such as a class for a <select> element with the following syntax:

f.select :field, choices, {}, { :class => 'my_css_class' }

With twitter_bootstrap_form_for, I was expecting the syntax to be:

f.select :field, label, choices, {}, { :class => 'my_css_class' }

However that solution does not seem to work. Is that a known issue?

link_to styled as button renders inline in form actions block, button_to does not.

If I have a bit of a form that looks like this

<%= f.actions do -%>
    <%= f.submit 'Save' %>
    <%= button_to 'Delete', dashboard_memobj_path(@memobj), :class => 'btn danger', :method => :delete %>
<% end %>

the 'Save' button will be rendered atop the 'Delete' button. However, if I have

<%= f.actions do -%>
    <%= f.submit 'Save' %>
    <%= link_to 'Delete', dashboard_memobj_path(@memobj), :class => 'btn danger', :method => :delete %>
<% end %>

The 'Save' button and 'Delete' link--styled as a button--render inline.

Displaying errors assigned to :base?

Am I doing something wrong, or does this library not handle errors added to :base? The only errors that show up for me are those attached to individual attributes.

Bootstrap-2.0 inputs have wrappers?

I'm trying to use this gem and I'm having a few minor issues with the markup that is being produced.
I'm using the following code :

                        <%= home.label 'Address' do |controls| %> 
                <%= controls.text_field :home_name, :class => 'span3', :placeholder => "Building name/number" %>
                <%= controls.text_field :home_name, :class => 'span3', :placeholder => "Road" %>
                <%= controls.text_field :home_name, :class => 'span3', :placeholder => "Town" %>
                <%= controls.text_field :home_name, :class => 'span3', :placeholder => "County" %>
                <%= controls.text_field :home_name, :class => 'span2', :placeholder => "Postcode" %>
            <% end %>

Which is producing nearly the right format, however each of the input tags are being wrapped in a span with a class of input. So for example

<div class="control-group" id="field_control_group">
    <label class="control-label" for="field">Label</label>
    <div class="controls">
        <span class="input">
            <input class="span3" id="field" name="fields[field]" size="30" type="text" />
        </span>
    </div>
</div>

As a result, the bootstrap styling breaks and doesn't work the way it's meant to work.
Is there any easy way to get rid of this or disable this?

Thanks

Nested forms support

I think twitter_bootstrap_form_for should support nested forms too. BTW: Great piece of work!

field_with_error divs added around error fields

Rails insists on inserting a div around any label or input with errors on the attribute. There's a mechanism to override this, but it's application-wide. We may need to swap the existing value in and out before and after we start rendering forms.

Checkbox arrays

Is there a way to properly do a checkbox array?

I've got something like this:

-MeasureUnit.where(:active => true, :id => nil).each do |mu|

  = f.check_box "measure_unit_ids[]", mu.name, {:checked => @conf.measure_unit.include?(mu)}, mu.id

But all the label and input elements created get the same name attribute, so clicking any of the labels un/checks the first element.

How could I do this?

Allow configuration of label html

I want to be able to add a class to the label sometimes, and I can't figure out a way to do it.

In order to do this in my own project I've added an option 'label_html'. This is just like the simple_form option in that it allows you to set ids/classes on the label.

e.g.

  = f.text_field :address_line1, 'Address line 1', label_html: { class: "required" }

Let's you put a 'required' class on the label

Pull request: #66

Add support for inline inputs

The example page for Twitter Bootstrap includes examples for multiple input fields inlined. We should explicitly support this.

text_field :add_on option doesn't respect value

It is generating the input-prepend/input-append class correctly, but it looks like the bootstrap markup requires the add-on span to come before the input for prepend. Because the span is added in the block of text_field it always gets added after. I have only tried this on the bootstrap-2.0 branch.

bootstrap-2.0 no method inputs

Great work there!

Did the syntax changed somehow? I tried upgrading to the bootstrap-2.0 branch but am getting undefined method 'inputs' for #<TwitterBootstrapFormFor::FormBuilder:0x00000004687460> on previously working code.

Thanks in advance.

PS: I am using rails 3.2.1

Remove dependency on Haml

It's probably too onerous to require other people use Haml. We should see if it's faster to use ERB partials or simply render the HTML ourselves in code.

:add_on => :prepend not working

I tried this:

  = f.text_field :price, 'Twitter', :class => 'medium', :add_on => :prepend do
    %span.add-on @

but this

@

it is rendered after the text_field not before, so the @ appears after the field

License

What is the license for this gem? MIT?

How to support form_tag too?

Right now, I think this works only form @form resource. i.e. only with = twitter_bootstrap_form_for @user do |user|

Does it or how do I make it work with form_tag syntax as well. like `=twitter_bootstrap_form_tag :user do |user| ??

bootstrap-2.0 branch - "button" based form helpers broken for rails 3.0.x

I'm not sure if this is a documentation issue or a code issue but on rails 3.0.9 I get the following error when doing a submit button. I'm assuming that was added in either rails 3.1.x or 3.2.x

ActionView::Template::Error (super: no superclass method `button'):
49: <% end %>
50:
51: <%= f.actions do %>
52: <%= f.submit(@issue.new_record? ? 'Create' : 'Save') %>
53:
54:
55: <% end %>

Move to central organisation?

Hi!

I am the maintainer of three gems similar to this one that make it easier to use Twitter Bootstrap in Ruby projects (https://github.com/krautcomputing/rails-bootstrap-navbar, https://github.com/krautcomputing/bootstrap-navbar, https://github.com/krautcomputing/middleman-bootstrap-navbar).

I was thinking about moving all those gems to a separate organisation (like "bootstrap-ruby") and wanted to get some feedback from other maintainers of similar gems (and the community at large) if that makes sense and if we could use this to make it easier for people to find gems to work with Bootstrap in Ruby (Rails, Sinatra, etc.)
I think it would also invite other people to contribute to those projects if they were united in a central organisation.

What do you think?
Would you be willing to move this repo to such an organisation as well?

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.