Read more

Simple Form: Rendering errors without an appropriate attribute

Emanuel
May 11, 2023Software engineer at makandra GmbH

Usually you add errors to :base in ActiveRecord Show archive.org snapshot , in case no appropriate attribute could be used to add the error.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Simple Form Show archive.org snapshot doesn't render errors on :base by default, but here a few options how you can render these on demand. For all the options below we use the following example with a Simple Form Bootstrap configuration:

- @user = Backend::User.new
- @user.errors.add(:base, 'First error')
- @user.errors.add(:base, 'Second error')

= simple_form_for(@user) do |form|
  = form.input :email
  = form.submit 'Save', class: ['btn', 'btn-primary']

Option 1: Using the form.error method

The form.error method renders the first error on :base.

= simple_form_for(@user) do |form|
  - if form.error(:base).present?
    .mb-3.alert.alert-danger
      = form.error :base
  = form.input :email
  = form.submit 'Save', class: ['btn', 'btn-primary']
<div class="mb-3 alert alert-danger">
  <span class="invalid-feedback">First error</span>
</div>

Image

Option 2: Using the form.error_notification method

As suggested in an example template Show archive.org snapshot the error_notification allows to render a default error message or the errors itself.

= simple_form_for(@user) do |form|
  = form.error_notification
  = form.error_notification message: form.object.errors[:base].to_sentence if form.object.errors[:base].present?
  = form.input :email
  = form.submit 'Save', class: ['btn', 'btn-primary']
<div class="mb-3 alert alert-danger">
  <span class="invalid-feedback">First error</span>
</div>

Image

Option 3: Using custom code

= simple_form_for(@user) do |form|
  - errors = form.object.errors[:base]
  - if errors.present?
    .alert.alert-danger
      %ul.mb-0
        - errors.each do |error|
          %li= error
  = form.input :email
  = form.submit 'Save', class: ['btn', 'btn-primary']
<div class="alert alert-danger">
  <ul class="mb-0">
    <li>First error</li>
    <li>Second error</li>
  </ul>
</div>

Image

Emanuel
May 11, 2023Software engineer at makandra GmbH
Posted by Emanuel to makandra dev (2023-05-11 13:49)