avoid rendering a simple_form component based on the attribute value

104 views
Skip to first unread message

Chris Beck

unread,
Dec 1, 2012, 9:50:34 AM12/1/12
to plataformate...@googlegroups.com
I have a CustomInput < SimpleForm::Inputs::Base that I would like to avoid rendering if the attribute value is blank. IOW, I want to avoid rendering all the wrappers and components. Can I do this within the control to avoid writing if model.attribute.blank? for each control in my template?

Chris Beck

unread,
Dec 10, 2012, 9:33:05 AM12/10/12
to plataformate...@googlegroups.com
My motivation is to have a single template that can respond to both the show and edit controller methods.  When the action is show, I use a custom input that formats a static control conforming to the bootstrap horizontal_form wrappers

Chris Beck

unread,
Dec 10, 2012, 10:26:33 AM12/10/12
to plataformate...@googlegroups.com

Carlos Antonio da Silva

unread,
Dec 10, 2012, 6:39:40 PM12/10/12
to plataformate...@googlegroups.com
Hm yeah, that's a nice way to deal with it. I have another idea, how about using a form option to handle that instead?


    class MyFormBuilder < SimpleForm::FormBuilder
      def initialize(*)
        super
        @_skip_blank_attributes = options[:skip_blanks]
      end

      def input(attribute_name, *args, &block)
        unless @_skip_blank_attributes && @object.send(attribute_name).blank?
          super
        end
      end
    end


So that you could use like this, with your form helper:

    my_form_for @foo, skip_blanks: params[:action] == 'show'

This way you don't need to couple the form builder with the helper, and I think it's more flexible to add new conditions (you could use the helper instead of the params check here if necessary).

Completely untested, of course :)
Wdyt?
--
At.
Carlos Antonio

Chris Beck

unread,
Dec 11, 2012, 5:22:58 PM12/11/12
to plataformate...@googlegroups.com
Indeed.  That is a better separation of concerns.  And decision to render static controls is a form level operation.  I'll give that a whirl.  Thanks, Carlos.

Carlos Antonio da Silva

unread,
Dec 11, 2012, 5:27:34 PM12/11/12
to plataformate...@googlegroups.com
Cool. If that works for you, perhaps it'd be good to open up a new page in our wiki with the example, like the one we have for attributes filtering (https://github.com/plataformatec/simple_form/wiki/Attributes-filter), that started as an integration with strong parameters. What do you think? Feel free to do that if you find it useful, the wiki is open for everyone to contribute.
--
At.
Carlos Antonio

Chris Beck

unread,
Dec 11, 2012, 11:46:27 PM12/11/12
to plataformate...@googlegroups.com
OK.  I'm happy to help out.  Thanks for all u do in this group, Carlos.

Carlos Antonio da Silva

unread,
Dec 14, 2012, 4:39:25 PM12/14/12
to plataformate...@googlegroups.com
Glad to help :).
--
At.
Carlos Antonio
Reply all
Reply to author
Forward
0 new messages