Skip to content

Instantly share code, notes, and snippets.

@neaf
Created December 25, 2009 16:01
Show Gist options
  • Select an option

  • Save neaf/263660 to your computer and use it in GitHub Desktop.

Select an option

Save neaf/263660 to your computer and use it in GitHub Desktop.
require 'bureaucrat/formsets'
class QuoteItemForm < Bureaucrat::Forms::Form
extend Bureaucrat::Quickfields
string :id, :required => false
hide :id
string :description
integer :unit_price
integer :quantity, :required => false
def save
if valid?
QuoteItem.new(cleaned_data)
end
end
end
QuoteItemFormSet = Bureaucrat::Formsets.make_formset_class(QuoteItemForm, :extra => 5, :can_delete => true)
class QuoteItemFormSet
def clean
if filled_forms.blank?
raise Bureaucrat::Fields::FieldValidationError.new("Quote has to contain at least one item.")
end
end
def filled_forms
forms.reject { |f| f.cleaned_data.blank? }
end
def self.from_quote(quote, options = {})
prefix = options.fetch(:prefix, self.default_prefix)
params = {}
quote.items.each_with_index do |item, index|
[:id, :description, :unit_price, :quantity].each do |f|
params["%s-%d-%s" % [prefix, index, f]] = item.send(f)
end
end
params["%s-%s" % [prefix, Bureaucrat::Formsets::INITIAL_FORM_COUNT]] = quote.items.count
params["%s-%s" % [prefix, Bureaucrat::Formsets::TOTAL_FORM_COUNT]] = quote.items.count + options.fetch(:extra, 0)
self.new(params, options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment