Class: Kiss::Form
Defined Under Namespace
Classes: BooleanField, CheckboxField, Column, Field, FileField, HiddenField, MultiChoiceField, MultiSelectField, MultiValueField, PasswordField, RadioField, RangeField, Section, SelectField, SubmitField, TextAreaField, TextField
Constant Summary collapse
- COMPONENT_TYPES =
Component type symbols used to create form definition DSL
{ :text => TextField, :hidden => HiddenField, :textarea => TextAreaField, :password => PasswordField, :boolean => BooleanField, :range => RangeField, :file => FileField, :select => SelectField, :radio => RadioField, :checkbox => CheckboxField, :multiselect => MultiSelectField, :submit => SubmitField }
Instance Method Summary collapse
-
#accepted? ⇒ Boolean
(also: #accepted)
Returns true if user submitted form with non-cancel submit button (non-nil submit param, not equal to cancel submit button value).
- #add_component(type, name, *args, &block) ⇒ Object
-
#add_error(*args) ⇒ Object
Add error message to be rendered with form.
-
#add_field(attrs = {}, &block) ⇒ Object
(also: #create_field)
Creates and adds a field to the form, according to specified attributes.
-
#closing_html ⇒ Object
(also: #html_close)
Renders end of form (form close tag).
- #column_break ⇒ Object
- #context ⇒ Object
- #debug(*args) ⇒ Object
-
#errors_html ⇒ Object
Renders error HTML block for top of form, and returns as string.
- #field(name) ⇒ Object
- #form_name_hidden_tag_html ⇒ Object
-
#has_errors? ⇒ Boolean
Returns true if form has errors.
-
#html ⇒ Object
Renders complete form HTML.
-
#initialize(*args, &block) ⇒ Form
constructor
Creates a new form object with specified attributes.
- #method_missing(method, *args, &block) ⇒ Object
- #object(obj = nil, options = {}, &block) ⇒ Object
- #object_field(obj, name) ⇒ Object
-
#opening_html ⇒ Object
(also: #html_open)
Renders beginning of form (form open tag and form/field/error styles).
-
#process(*objs) ⇒ Object
Checks whether form was submitted and accepted by user and, if so, whether form validates.
- #process_or_render ⇒ Object
-
#render(options = {}) ⇒ Object
Renders current action using form’s HTML as action render content.
- #require_values(*names) ⇒ Object
- #required_legend_html ⇒ Object
- #reset ⇒ Object
-
#save(*args) ⇒ Object
Saves form input data associated with specified objects, or all form objects if objects are not specified here.
- #section_break ⇒ Object
-
#sections_html ⇒ Object
(also: #components_html, #fields_html)
Renders HTML for form sections.
- #set_object_data(obj = @_object) ⇒ Object
- #set_objects_data(*args) ⇒ Object
- #style_html ⇒ Object
-
#submit(*args, &block) ⇒ Object
(also: #add_submit)
Creates and adds set of submit buttons to the form, per specified attributes.
-
#submit_html ⇒ Object
Renders form submit buttons.
-
#submitted? ⇒ Boolean
Returns true if user submitted form in this request.
-
#table_closing_html ⇒ Object
(also: #table_html_close)
Renders close of form table.
- #table_html ⇒ Object
-
#table_opening_html ⇒ Object
(also: #table_html_open)
Renders open of form table.
- #unique(*val) ⇒ Object
-
#validate ⇒ Object
Validates form values against fields’ format and required attributes, and returns values unless form has errors.
- #validate_uniqueness_of(column_set) ⇒ Object
-
#values ⇒ Object
Gets hash of form values.
- #with(*args, &block) ⇒ Object
Constructor Details
#initialize(*args, &block) ⇒ Form
Creates a new form object with specified attributes.
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/kiss/form.rb', line 162 def initialize(*args, &block) @_attrs = args.to_attrs _instance_variables_set_from_attrs(@_attrs) @_method ||= 'post' @_sections = [Section.new(self)] @_current_section = @_sections.first @_current_column = @_current_section.columns.first @_components = [] @_fields = Hashay.new @_object_fields = {} @_default_values ||= {} @_params = {} @_with = nil @_field_name_prefix = '' @_objects_add_order = [] @_objects_save_order = [] @_new_object_index = -1 @_object_fields = {} @_unique = [] @_prepend_html = '' @_append_html = '' (@_attrs[:fields] || []).each do |field| # create field here add_field(field) end @_errors = [] @_field_errors = {} import_instance_variables(@_delegate) if @_delegate instance_eval(&block) if block_given? raise "form name required" unless @_name raise "form delegate required" unless @_delegate end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
149 150 151 |
# File 'lib/kiss/form.rb', line 149 def method_missing(method, *args, &block) delegate.send method, *args, &block end |
Instance Method Details
#accepted? ⇒ Boolean Also known as: accepted
Returns true if user submitted form with non-cancel submit button (non-nil submit param, not equal to cancel submit button value).
532 533 534 535 |
# File 'lib/kiss/form.rb', line 532 def accepted? raise 'form missing submit field' unless @_submit return params[@_submit.name] != @_submit.cancel end |
#add_component(type, name, *args, &block) ⇒ Object
137 138 139 140 141 142 143 |
# File 'lib/kiss/form.rb', line 137 def add_component(type, name, *args, &block) attrs = args.to_attrs add_field({ :type => type, :name => name }.merge(attrs), &block) end |
#add_error(*args) ⇒ Object
Add error message to be rendered with form. If multiple args given, first arg is field name, and second arg (error message) will render next to specified field.
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/kiss/form.rb', line 312 def add_error(*args) case args.size when 0 raise 'at least one argument required' when 1 arg = args.first if arg.is_a?(Hash) field = arg.field || arg.field_name = arg. else @_errors << arg return end when 2 field, = args else raise 'too many arguments' end field = @_fields[field] if field.is_a?(String) field.add_error() end |
#add_field(attrs = {}, &block) ⇒ Object Also known as: create_field
Creates and adds a field to the form, according to specified attributes.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/kiss/form.rb', line 226 def add_field(attrs = {}, &block) attrs = @_with.merge(attrs) if @_with name = attrs[:name].to_s key = (attrs[:key] || name).to_sym name = @_field_name_prefix + name unless @_field_name_prefix.empty? type = attrs[:type] ? attrs[:type].to_sym : :text raise "invalid field type '#{type}'" unless COMPONENT_TYPES.has_key?(type) field = COMPONENT_TYPES[type].new(self, attrs.merge( :name => name, :key => key ), &block) field.object = @_object if @_object && !field.object obj = field.object # must hash @_object_fields by Ruby object id; if by object, weird lookup errors result, # even when lookup object has same Ruby object id as the hash key object! ruby_obj_id = obj.object_id unless @_object_fields[ruby_obj_id] @_object_fields[ruby_obj_id] = {} @_objects_add_order << object end if @_object_fields[ruby_obj_id][field.name] raise "duplicate form field name '#{attrs[:name]}'#{" on #{obj.class.name} object" if obj}" end @_object_fields[ruby_obj_id][field.name] = field @_fields[name] = field @_components << field @_current_column.components << field @_enctype = 'multipart/form-data' if field.is_a?(FileField) field end |
#closing_html ⇒ Object Also known as: html_close
Renders end of form (form close tag).
780 781 782 |
# File 'lib/kiss/form.rb', line 780 def closing_html '</div></form>' + @_append_html end |
#column_break ⇒ Object
214 215 216 217 |
# File 'lib/kiss/form.rb', line 214 def column_break @_current_column = Column.new(self) @_current_section.columns << @_current_column end |
#context ⇒ Object
204 205 206 207 208 209 210 211 212 |
# File 'lib/kiss/form.rb', line 204 def context @_context ||= begin @_timezone ||= (fields['timezone'] && (params['timezone'] || (object && object[:timezone]))) || nil { :timezone => @_timezone, :year => @_year } end end |
#debug(*args) ⇒ Object
145 146 147 |
# File 'lib/kiss/form.rb', line 145 def debug(*args) @_delegate.request.debug(args.first, Kernel.caller[0]) end |
#errors_html ⇒ Object
Renders error HTML block for top of form, and returns as string.
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
# File 'lib/kiss/form.rb', line 544 def errors_html return nil unless has_errors? @_errors << "Please correct the #{@_errors.empty? ? '' : 'other '}errors highlighted below." if @_has_field_errors if @_errors.size == 1 content = @_errors[0] else content = "<ul>" + @_errors.map {|e| "<li>#{e}</li>"}.join + "</ul>" end @_errors.pop if @_has_field_errors plural = @_errors.size > 1 || @_has_field_errors ? 's' : nil %Q(<table class="kiss_form_errors"><tr><td>#{content}</td></tr></table>) end |
#field(name) ⇒ Object
291 292 293 |
# File 'lib/kiss/form.rb', line 291 def field(name) @_fields[name] end |
#form_name_hidden_tag_html ⇒ Object
561 562 563 |
# File 'lib/kiss/form.rb', line 561 def form_name_hidden_tag_html %Q(<input type=hidden name="form" value="#{@_name}">) end |
#has_errors? ⇒ Boolean
Returns true if form has errors.
521 522 523 |
# File 'lib/kiss/form.rb', line 521 def has_errors? (@_errors.size > 0 || @_has_field_errors) end |
#html ⇒ Object
Renders complete form HTML.
786 787 788 |
# File 'lib/kiss/form.rb', line 786 def html [opening_html, table_html, closing_html].join end |
#object(obj = nil, options = {}, &block) ⇒ Object
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 |
# File 'lib/kiss/form.rb', line 485 def object(obj = nil, = {}, &block) if block_given? raise 'missing object arg' unless obj if obj.is_a?(Symbol) parent = @_object raise 'missing parent object for object symbol reference' unless parent obj = parent.send(obj) #|| #parent.set_associated_object(parent.class.association_reflection(object).associated_class.new) end raise 'object parameter must reference a model object' unless obj.is_a?(Kiss::Model) # if new, save early to give object a primary key, needed to save assoc children @_objects_save_order << obj if obj.new? prefix = [:prefix] old_obj = @_object old_prefix = @_field_name_prefix @_object = obj @_field_name_prefix = (@_field_name_prefix + prefix.to_s + '.') if prefix instance_eval(&block) @_object = old_obj @_field_name_prefix = old_prefix # save again to pick up any assoc ids from children @_objects_save_order << obj obj elsif obj @_object = obj else @_object end end |
#object_field(obj, name) ⇒ Object
295 296 297 |
# File 'lib/kiss/form.rb', line 295 def object_field(obj, name) @_object_fields[obj.object_id][name.to_s] end |
#opening_html ⇒ Object Also known as: html_open
Renders beginning of form (form open tag and form/field/error styles).
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 |
# File 'lib/kiss/form.rb', line 752 def opening_html @_error_class ||= 'kiss_form_error_message' @_field_error_class ||= @_error_class # form tag form_attrs = ['id', 'method', 'enctype', 'class', 'style'].map do |attr| next if (value = send attr).blank? "#{attr}=\"#{send attr}\"" end if @_html @_html.each_pair do |k, v| form_attrs.push("#{k}=\"#{v}\"") end end form_tag = %Q(<form action="#{@_action}" #{form_attrs.join(' ')}>#{form_name_hidden_tag_html}) # combine [ style_html, @_prepend_html, form_tag, '<div class="kiss_form">', errors_html ].join end |
#process(*objs) ⇒ Object
Checks whether form was submitted and accepted by user and, if so, whether form validates. If form validates, saves form values to form’s Sequel::Model object and returns true. Otherwise, returns false.
408 409 410 411 412 413 414 415 416 417 418 419 |
# File 'lib/kiss/form.rb', line 408 def process(*objs) return false unless submitted if accepted validate return false if has_errors? save(*objs) end return true end |
#process_or_render ⇒ Object
421 422 423 |
# File 'lib/kiss/form.rb', line 421 def process_or_render self.render unless self.process end |
#render(options = {}) ⇒ Object
Renders current action using form’s HTML as action render content.
539 540 541 |
# File 'lib/kiss/form.rb', line 539 def render( = {}) @_delegate.render .merge(:content => html) end |
#require_values(*names) ⇒ Object
469 470 471 |
# File 'lib/kiss/form.rb', line 469 def require_values(*names) names.each {|name| fields[name.to_s].require_value } end |
#required_legend_html ⇒ Object
574 575 576 577 |
# File 'lib/kiss/form.rb', line 574 def required_legend_html (@_has_required_fields && @_mark_required) ? %Q( <tr><td class="kiss_form_help">Required fields marked by <span class="kiss_form_required">*</span></td></tr> ) : '' end |
#reset ⇒ Object
286 287 288 289 |
# File 'lib/kiss/form.rb', line 286 def reset @_params = {} @_fields.each {|field| field.reset } end |
#save(*args) ⇒ Object
Saves form input data associated with specified objects, or all form objects if objects are not specified here.
460 461 462 463 464 465 466 467 |
# File 'lib/kiss/form.rb', line 460 def save(*args) db.transaction do extract_objects_from_args(args).each do |obj| set_object_data(obj) obj.save end end end |
#section_break ⇒ Object
219 220 221 222 223 |
# File 'lib/kiss/form.rb', line 219 def section_break @_current_section = Section.new(self) @_current_column = @_current_section.columns.first @_sections << @_current_section end |
#sections_html ⇒ Object Also known as: components_html, fields_html
Renders HTML for form sections.
566 567 568 569 570 |
# File 'lib/kiss/form.rb', line 566 def sections_html sections.map do |section| section.html end.join end |
#set_object_data(obj = @_object) ⇒ Object
438 439 440 441 442 443 444 445 446 447 448 449 |
# File 'lib/kiss/form.rb', line 438 def set_object_data(obj = @_object) @_object_fields[obj.object_id].values.each do |field| # skip fields whose name starts with underscore next if field.name =~ /\A\_/ # skip fields with save == false next unless field.save # skip file fields next if field.is_a?(FileField) field.set_value_to_object(obj) end end |
#set_objects_data(*args) ⇒ Object
451 452 453 454 455 456 |
# File 'lib/kiss/form.rb', line 451 def set_objects_data(*args) extract_objects_from_args(args).each do |obj| next unless obj set_object_data(obj) end end |
#style_html ⇒ Object
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
# File 'lib/kiss/form.rb', line 616 def style_html styles = [] styles << <<-EOT table.kiss_form { border: 0; border-collapse: collapse; margin-right: -12px; } table.kiss_form > tbody > tr > td { padding: 0; } table.kiss_form_section { border: 0; border-collapse: collapse; } table.kiss_form_section > tbody > tr > td { padding: 0 12px 0 0; } td.kiss_form_column { vertical-align: top; } table.kiss_form_column { margin-bottom: 6px; } table.kiss_form_column > tbody > tr > td { padding: 2px 6px 2px 0; vertical-align: middle; } .kiss_form_errors { margin-bottom: 4px; } .kiss_form_errors td { background-color: #ff8; padding: 2px 4px; line-height: 135%; color: #900; border: 1px solid #db4; } .kiss_form_errors td ul { padding-left: 16px; margin: 0; } .kiss_form .kiss_form_help { padding-bottom: 4px; font-size: 90%; color: #555; } .kiss_form_required { color: #a21; font-size: 150%; line-height: 50%; position: relative; top: 4px; } .kiss_form_column td.kiss_form_label { text-align: right; white-space: nowrap; } .kiss_form_column td.kiss_form_label.error { color: #b10; } .kiss_form_column tr.kiss_form_prompt td { padding: 8px 3px 0px 4px; } .kiss_form_column input[type="text"], .kiss_form_column input[type=password], .kiss_form_column textarea { width: 250px; margin-left: 0; margin-right: 0; } .kiss_form_column table.kiss_form_field_columns { border-spacing: 0; border-collapse: collapse; width: 100%; } .kiss_form_column table.kiss_form_field_columns td { padding: 0 16px 2px 0; vertical-align: top; } .kiss_form_column .kiss_form_checkbox .kiss_form_label { vertical-align: top; padding-top: 3px; } .kiss_form_column .kiss_form_radio .kiss_form_label { vertical-align: top; padding-top: 4px; } .kiss_form_column .kiss_form_textarea .kiss_form_label { vertical-align: top; padding-top: 3px; } .kiss_form tr.kiss_form_submit td { padding: 0 6px 0 0; text-align: center; } EOT if @_error_class == 'kiss_form_error_message' styles << <<-EOT .kiss_form_error_message { padding: 1px 4px; border: 1px solid #db4; background-color: #ff8; color: #900; font-size: 90%; line-height: 135%; display: block; float: left; width: 246px; margin-bottom: 2px; } .kiss_form_error_message div { color: #c00; font-weight: bold; } .kiss_form_error_message ul { padding-left: 16px; margin: 0; } tr.kiss_form_error_row td { padding-top: 0; } tr.kiss_form_error_row .kiss_form_error_message { position: relative; top: -2px; margin-bottom: 0; } EOT end styles.empty? ? '' : ["<style>", styles, "</style>"].flatten.join end |
#submit(*args, &block) ⇒ Object Also known as: add_submit
Creates and adds set of submit buttons to the form, per specified attributes.
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/kiss/form.rb', line 266 def submit(*args, &block) if args.size > 0 raise 'submit already defined' if @_submit attrs = { :type => :submit, :name => 'submit', :save => false, :cancel => 'Cancel' } attrs.merge!(args.pop) if args.last.is_a?(Hash) attrs[:options] = args if args.size > 0 attrs = @_with.merge(attrs) if @_with @_submit = COMPONENT_TYPES[:submit].new(self, attrs, &block) else @_submit end end |
#submit_html ⇒ Object
Renders form submit buttons.
580 581 582 583 584 585 586 587 588 589 590 591 592 |
# File 'lib/kiss/form.rb', line 580 def submit_html if @_submit prompt = @_submit.prompt ? (@_submit.prompt + '<br/>') : '' [ '<tr class="kiss_form_submit"><td>', prompt, @_submit.element_html, '<br/></td></tr>' ].join else '' end end |
#submitted? ⇒ Boolean
Returns true if user submitted form in this request.
526 527 528 |
# File 'lib/kiss/form.rb', line 526 def submitted? @_submitted end |
#table_closing_html ⇒ Object Also known as: table_html_close
Renders close of form table.
601 602 603 |
# File 'lib/kiss/form.rb', line 601 def table_closing_html '</tbody></table>' end |
#table_html ⇒ Object
606 607 608 609 610 611 612 613 614 |
# File 'lib/kiss/form.rb', line 606 def table_html [ table_opening_html, required_legend_html, sections_html, submit_html, table_closing_html ].flatten.join end |
#table_opening_html ⇒ Object Also known as: table_html_open
Renders open of form table.
595 596 597 |
# File 'lib/kiss/form.rb', line 595 def table_opening_html %Q(<table class="kiss_form" border=0 cellspacing=0><tbody>) end |
#unique(*val) ⇒ Object
153 154 155 156 157 158 159 |
# File 'lib/kiss/form.rb', line 153 def unique(*val) if val.empty? @_unique else @_unique << val end end |
#validate ⇒ Object
Validates form values against fields’ format and required attributes, and returns values unless form has errors.
337 338 339 340 341 342 343 344 |
# File 'lib/kiss/form.rb', line 337 def validate return nil unless submitted @_fields.each {|field| field.validate } @_unique.each {|field_set| validate_uniqueness_of(field_set) } has_errors? ? nil : values end |
#validate_uniqueness_of(column_set) ⇒ Object
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/kiss/form.rb', line 346 def validate_uniqueness_of(column_set) conditions = column_set.last.is_a?(Hash) ? column_set.pop : {} nouns = [] true_adjectives = [] false_adjectives = [] column_set.each do |column_name| key = column_name.to_sym column_name = column_name.to_s field = fields[column_name] label, value = field ? [field.label.downcase, field.value] : [column_name.sub(/_id\Z/, '').downcase, object[column_name.to_sym]] conditions[key] = value if column_name =~ /\Ais_/ || column_name =~ /_at\Z/ if value.zero? || value.nil? false_adjectives else true_adjectives end else nouns end << label end dataset = @_object.model.filter(conditions) dataset = dataset.exclude(@_object.pk_hash) unless @_object.new? return nil if dataset.empty? true_adjective_string = true_adjectives.empty? ? '' : (true_adjectives.join(', ') + ' ') humanized_object_class_name = @_object.model.name.singularize.gsub('_', ' ') false_adjective_string = false_adjectives.empty? ? '' : ", not #{false_adjectives.conjoin('or')}," with_clause = nouns.empty? ? '' : " with the same #{nouns.conjoin}" = [ 'There is already another ', true_adjective_string, humanized_object_class_name, false_adjective_string, with_clause, '.' ].join # Add error to a single field if appropriate. if column_set.length == 1 field_name = column_set[0].to_str if field_name && fields[field_name] return add_error(field_name, ) end end # Else add to top of form. return add_error() end |
#values ⇒ Object
Gets hash of form values.
300 301 302 303 304 305 306 307 |
# File 'lib/kiss/form.rb', line 300 def values @_values ||= begin hash = {} @_fields.each {|field| field.set_value_to_hash(hash) } hash['submit'] = @_submit.value = params[@_submit.name] hash end end |
#with(*args, &block) ⇒ Object
473 474 475 476 477 478 479 480 481 482 483 |
# File 'lib/kiss/form.rb', line 473 def with(*args, &block) if block_given? attrs = args.to_attrs old_with = @_with @_with = (@_with || {}).merge(attrs) instance_eval(&block) @_with = old_with end end |