Simple Form: Rendering errors without an appropriate attribute

Posted About 1 year ago. Visible to the public.

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

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

Last edit
About 1 year ago
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2023-05-11 11:49)