Customized the Select Menus In A Hobo Form

Originally written by bretweinraub on 2010-03-09.

Hobo does a nice job of generating a default form for every model you generate.

Especially nice are the “select” boxes that follow ActiveRecord “belongs_to” associations.

In any event generally speaking the best way to look at how to change the form for a model is to look at the autogenerated tag created by Rapid,

in

$RAILS_ROOT/app/views/taglibs/auto/rapid/forms.dryml

There you’ll see this (basically):

<!-- AUTOMATICALLY GENERATED FILE - DO NOT EDIT -->

<def tag="form" for="InviteGroup">
  <form merge param="default">
    <error-messages param/>
    <field-list fields="name, address, group_leader" param/>
    <div param="actions">
      <submit label="#{ht 'invite_groups.actions.save', :default=>['Save']}" param/><or-cancel param="cancel"/>
    </div>
  </form>
</def>

Now lets monkey with this tag a bit. For my model I have a belongs_to association called “group leader” that I want to filter, or put another way I want to restrict the entries that can appear in my dropdown.

Here’s the bit from the model code:

class InviteGroup < ActiveRecord::Base

  hobo_model # Don't put anything above this

  fields do
    name :string
    group_leader_id :integer
    address :text
    timestamps
  end

  has_many :invitees
  belongs_to :group_leader, :class_name => 'Invitee', :foreign_key => "group_leader_id"
  .....

In this case I only want to allow a group leader who is actual an invitee of this group. So if an invite doesn’t point to this group, it can’t be my leader. Put generically:

A foreign key to a parent table may have a restricted set of valid values.

Lets restrict our form, in this case to whatever the ‘invitees’ method of our current object returns.

We can do this by ‘extending’ our form tag, and we’ll do this by altering the behaviour of the tag in

$RAILS_ROOT/app/views/taglibs/application.dryml

<extend tag="form" for="InviteGroup">
  <old-form merge>
    <field-list: fields="name, address, group_leader">
      <group-leader-view:>
        <select-one options="&@this.invitees"/>
      </group-leader-view:>
    </field-list:>
  </old-form>
</extend>

Explained simply: - extend alters the tag auto-generated by rapid - old-form merge; see the agility tutorial more on this construct - group-leader-view ; we can change the markup generated for any field in field list

This works like a charm!

How to learn more? Probably the best thing you can do is work through the DRYML guide; this will help you crack the mystery of these tags and empower to alter the functionality of the Rapid tags, as well as write your own. Good luck!


Edit this page