Skip to content

11 Form and Flash Styles

Dave Strus edited this page Jul 15, 2015 · 1 revision

The basics of our app are starting to take shape. Let's take another moment to make it look a little better.

To make our form look a little nicer (and to make better use of the space on the page), add the following to the end of the stylesheet:

app/assets/stylesheets/style.scss

main form {
  margin-bottom: 20px;
  fieldset {
    width: 514px;
    padding: 7px 5px;
    font-size: large;
    background-color: #cee3f8;
    margin-bottom: 10px;
    input[type="text"], textarea, select {
      width: 100%;
      font-size: 14px;
      line-height: 14px;
      padding: 6px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
    textarea {
      height: 100px;
    }
  }
}

In our markup, we can also throw a couple of CSS classes on our submit button to take advantage of some Bootstrap styles.

app/views/posts/new.html.erb

  <%= f.submit class: 'btn btn-default' %>

One other thing stands out at the moment: Flash messages. Let's give those some style. Once again, Bootstrap can provide some help, but we'll have to use Bootstrap's CSS classes.

First we'll add an "alert" class to all flash messages. Don't forget to add it when the message is an Array and when it isn't.

app/views/layouts/application.html.erb

          <% flash.each do |name, msg| -%>
            <% if msg.is_a? Array -%>
              <div class="alert <%= name %>">
                <ul>
                  <% msg.each do |message| -%>
                    <li><%= message %></li>
                  <% end -%>
                </ul>
              </div>
            <% else -%>
              <%= content_tag :div, msg, class: "alert #{name}" %>
            <% end -%>
          <% end -%>

That won't have any immediate effect. We also need to use specialized class names that correspond to Bootstrap. Bootstrap defines styles for .alert-danger, but not for .error.

Let's change our flash messages accordingly.

app/controllers/posts_controller.rb

    if @post.save
      redirect_to posts_path, flash: { :'alert-success' => 'Thanks for submitting your post!' }
    else
      flash.now[:'alert-danger'] = @post.errors.full_messages
      render :new
    end

We changed :notice to :'alert-success' (necessitating hashrocket syntax in place of Ruby 1.9 syntax) and :error to :'alert-danger'

Go ahead and trigger some validation errors and submit a new post or two. Your flash messages should now be nice and colorful.

Let's commit our changes. Don't forget to check your git status, and maybe even git diff, to make sure you're committing what you expect. (Are you ready for me to stop saying that yet?)

$ git add .
$ git commit -m "Add styles for forms and flash messages."