Class: Kiss::Form

Inherits:
Object show all
Defined in:
lib/kiss/form.rb,
lib/kiss/form/field.rb

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

Constructor Details

#initialize(*args, &block) ⇒ Form

Creates a new form object with specified attributes.



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/kiss/form.rb', line 132

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



119
120
121
# File 'lib/kiss/form.rb', line 119

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).

Returns:

  • (Boolean)


464
465
466
467
# File 'lib/kiss/form.rb', line 464

def accepted?
  raise 'form missing submit field' unless @_submit
  return params[@_submit.name] != @_submit.cancel
end

#add_component(type, name, *args, &block) ⇒ Object



107
108
109
110
111
112
113
# File 'lib/kiss/form.rb', line 107

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.



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/kiss/form.rb', line 282

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
      message = arg.message
    else
      @_errors << arg
      return
    end
  when 2
    field, message = args
  else
    raise 'too many arguments'
  end
  
  field = @_fields[field] if field.is_a?(String)
  field.add_error(message)
end

#add_field(attrs = {}, &block) ⇒ Object Also known as: create_field

Creates and adds a field to the form, according to specified attributes.



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/kiss/form.rb', line 196

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

#column_breakObject



184
185
186
187
# File 'lib/kiss/form.rb', line 184

def column_break
  @_current_column = Column.new(self)
  @_current_section.columns << @_current_column
end

#component_html(field) ⇒ Object Also known as: field_html

Renders HTML for specified form field.



708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/kiss/form.rb', line 708

def component_html(field)
  field = fields[field.to_s] if (field.is_a?(Symbol) || field.is_a?(String))
  return field.element_html if field.is_a?(HiddenField)
  
  type = field.class.type
  prompt = field.prompt
  label = field.label
  errors = field.errors_html
  required = field.required ? %Q(<span class="kiss_form_required">#{@_mark_required}</span> ) : ''
  
  ([
	  prompt ? %Q(<tr class="kiss_form_prompt"><td class="kiss_form_label">#{required}</td><td>#{prompt.to_s}</td></tr>) : '',
	  
    %Q(<tr class="kiss_form_#{type}"><td class="kiss_form_label#{errors ? ' error' : ''}">),
    !prompt ? (required + (label.blank? ? '' : label.to_s + ':' )) : '',
	  %Q(</td><td class="kiss_form_#{type}">),
		field.element_html, "</td></tr>"
	] + (errors ? [
	  '<tr class="kiss_form_error_row"><td class="kiss_form_required"></td><td>',
	  errors,
	  '</td></tr>'
	] : [])).join
end

#components_htmlObject Also known as: fields_html

Renders HTML for form fields.



667
668
669
670
671
# File 'lib/kiss/form.rb', line 667

def components_html
  @_components.map do |component|
    component_html(component)
  end.join
end

#contextObject



174
175
176
177
178
179
180
181
182
# File 'lib/kiss/form.rb', line 174

def context
  @_context ||= begin
    @_timezone ||= (fields['timezone'] && (params['timezone'] || (object && object[:timezone]))) || nil
    {
      :timezone => @_timezone,
      :year => @_year
    }
  end
end

#debug(*args) ⇒ Object



115
116
117
# File 'lib/kiss/form.rb', line 115

def debug(*args)
  @_delegate.request.debug(args.first, Kernel.caller[0])
end

#errors_htmlObject

Renders error HTML block for top of form, and returns as string.



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/kiss/form.rb', line 471

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



261
262
263
# File 'lib/kiss/form.rb', line 261

def field(name)
  @_fields[name]
end

#form_name_hidden_tag_htmlObject



493
494
495
# File 'lib/kiss/form.rb', line 493

def form_name_hidden_tag_html
  %Q(<input type=hidden name="form" value="#{@_name}">)
end

#has_errors?Boolean

Returns true if form has errors.

Returns:

  • (Boolean)


453
454
455
# File 'lib/kiss/form.rb', line 453

def has_errors?
  (@_errors.size > 0 || @_has_field_errors)
end

#htmlObject

Renders complete form HTML.



695
696
697
698
699
700
701
702
703
704
705
# File 'lib/kiss/form.rb', line 695

def html
  return [
    html_open,
    table_html_open,
    required_legend_html,
    sections_html,
    submit_html,
    table_html_close,
    html_close
  ].flatten.join
end

#html_closeObject

Renders end of form (form close tag).



655
656
657
# File 'lib/kiss/form.rb', line 655

def html_close
  "</div></form>#{@_append_html}"
end

#html_openObject

Renders beginning of form (form open tag and form/field/error styles).



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
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
# File 'lib/kiss/form.rb', line 498

def html_open
  @_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})
  
  # style tag
  styles = []
  styles.push( <<-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.push( <<-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
  style_tag = styles.size == 0 ? '' : "<style>" + styles.join('') + "</style>"
  
  # combine
  return %Q(#{@_prepend_html}#{form_tag}#{style_tag}<div class="kiss_form">#{errors_html})
end

#object(obj = nil, options = {}, &block) ⇒ Object



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/kiss/form.rb', line 417

def object(obj = nil, options = {}, &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 = options[: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



265
266
267
# File 'lib/kiss/form.rb', line 265

def object_field(obj, name)
  @_object_fields[obj.object_id][name.to_s]
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.



340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/kiss/form.rb', line 340

def process(*objs)
  return false unless 
  
  if accepted
    validate
    return false if has_errors?
  
    save(*objs)
  end
 
	return true
end

#process_or_renderObject



353
354
355
# File 'lib/kiss/form.rb', line 353

def process_or_render
  self.render unless self.process
end

#render(options = {}) ⇒ Object

Renders current action using form’s HTML as action render content.



489
490
491
# File 'lib/kiss/form.rb', line 489

def render(options = {})
  @_delegate.render options.merge(:content => html)
end

#require_values(*names) ⇒ Object



401
402
403
# File 'lib/kiss/form.rb', line 401

def require_values(*names)
  names.each {|name| fields[name.to_s].require_value }
end

#required_legend_htmlObject



679
680
681
682
# File 'lib/kiss/form.rb', line 679

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

#resetObject



256
257
258
259
# File 'lib/kiss/form.rb', line 256

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.



392
393
394
395
396
397
398
399
# File 'lib/kiss/form.rb', line 392

def save(*args)
  db.transaction do
    extract_objects_from_args(args).each do |obj|
      set_object_data(obj)
      obj.save
    end
  end
end

#section_breakObject



189
190
191
192
193
# File 'lib/kiss/form.rb', line 189

def section_break
  @_current_section = Section.new(self)
  @_current_column = @_current_section.columns.first
  @_sections << @_current_section
end

#sections_htmlObject

Renders HTML for form sections.



660
661
662
663
664
# File 'lib/kiss/form.rb', line 660

def sections_html
  sections.map do |section|
    section.html
  end.join
end

#set_object_data(obj = @_object) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/kiss/form.rb', line 370

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



383
384
385
386
387
388
# File 'lib/kiss/form.rb', line 383

def set_objects_data(*args)
  extract_objects_from_args(args).each do |obj|
    next unless obj
    set_object_data(obj)
  end
end

#submit(*args, &block) ⇒ Object Also known as: add_submit

Creates and adds set of submit buttons to the form, per specified attributes.



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/kiss/form.rb', line 236

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_htmlObject

Renders form submit buttons.



690
691
692
# File 'lib/kiss/form.rb', line 690

def submit_html
  @_submit ? %Q(<tr class="kiss_form_submit"><td>#{@_submit.element_html}</td></tr>) : ''
end

#submitted?Boolean

Returns true if user submitted form in this request.

Returns:

  • (Boolean)


458
459
460
# File 'lib/kiss/form.rb', line 458

def 
  @_submitted
end

#table_html_closeObject

Renders close of form table.



685
686
687
# File 'lib/kiss/form.rb', line 685

def table_html_close
  '</tbody></table>'
end

#table_html_openObject

Renders open of form table.



675
676
677
# File 'lib/kiss/form.rb', line 675

def table_html_open
  %Q(<table class="kiss_form" border=0 cellspacing=0><tbody>)
end

#unique(*val) ⇒ Object



123
124
125
126
127
128
129
# File 'lib/kiss/form.rb', line 123

def unique(*val)
  if val.empty?
    @_unique
  else
    @_unique << val
  end
end

#validateObject

Validates form values against fields’ format and required attributes, and returns values unless form has errors.



307
308
309
310
311
312
313
314
# File 'lib/kiss/form.rb', line 307

def validate
  return nil unless 
  
	@_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



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/kiss/form.rb', line 316

def validate_uniqueness_of(column_set)
  column_set_labels_values = column_set.map do |column_name|
    (field = fields[column_name.to_s]) ? 
      [field.label, field.value] : 
      [column_name.to_s.sub(/_id\Z/, '').titlecase, object[column_name]]
  end
  conditions = column_set.zip column_set_labels_values.map {|lv| lv[1] }
  
  dataset = @_object.model.filter(conditions)
  unless (@_object.new? ? dataset : dataset.exclude(@_object.pk_hash)).empty?
    labels = column_set_labels_values.map {|lv| lv[0] }
    message = "There is already another #{@_object.model.name.singularize.gsub('_', ' ')} with the same #{labels.conjoin}."
    return (
      (column_set.length == 1) && 
      (field_name = column_set[0].to_str) &&
      fields[field_name]
    ) ? add_error(field_name, message) : add_error(message)
  end
end

#valuesObject

Gets hash of form values.



270
271
272
273
274
275
276
277
# File 'lib/kiss/form.rb', line 270

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



405
406
407
408
409
410
411
412
413
414
415
# File 'lib/kiss/form.rb', line 405

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