Announcing the ActionButton Plugin

Brian Landau, Former Developer

Article Category: #Code

Posted on

When creating web application there’s often a need for single links that have a destructive or “unsafe” effect. In accordance with HTTP specs, GET’s (e.g. links) should not be used for this. The issues that 37signals had with unsafe links prove the importance of this.

This is also important if your application is RESTful. Rails offers a few good solutions, but none of them are ideal. There’s link_to_remote, but this requires the user to have JavaScript enabled and doesn’t allow for progressive enhancement. Then there’s submit_to_remote, which requires you to wrap it in a form tag yourself and also doesn’t allow for progressive enhancement. Last, you have button_to, which is almost ideal, but it uses a submit button that offers less options for styling than a button tag.

And this is where the idea for a button tag helper came in. (See this blog post for a good description of why the button element rocks). Thus, ActionButton was born.

With it, you can create a form with a single button element. The form can be set to point to any url just as you would with a normal form. The button and the form can have different id and class attributes, making them easy to target via JavaScript. But you don’t need to set these; by default it will create classes and ids that are sensible. Of course, all the normal HTML options are available, too.

The plugin will also install a modified version of the lowpro library. The ujs_remote_form helper provided creates a snippet of lowpro JavaScript that can be used to make a form (or set of forms) submit via an AJAX call.

So how would I use this?

Well, if you have a list of blog posts in an admin section and you want to add delete buttons next to each of them and you want them to look the same in every browser, this is how you would do it.

<%= action_button 'delete_post', "#{image_tag('icons/delete.jpg', :alt => 'delete')} Delete", 
post_url(post), {:method => :delete, :number => post.id} %>

Then when you’re ready for some AJAXy goodness, you can either use the Rails built-in helper of the plugin’s lowpro one:

Built-in:

Add this for each post:

<%= observe_form "delete_post#{post.id}-form", :on => 'submit', 
:confim => 'Are you sure you wish to delete this post?' %>

Lowpro:

Add this for the whole page of posts:

<%= ujs_remote_form 'button.delete_post', :confirm => 'Are you sure you wish to delete this post' %>

So where do I get this plugin of button joy?

It’s up on github right now!

If you have any questions, comments or suggestions, send them my way. It’s great to get feedback, but if you really feel I messed something up, just fork it and make the changes you feel it needs.

Related Articles