Class: RubyMVC::Views::FormView

Inherits:
View show all
Defined in:
lib/ruby_mvc/views/form_view.rb

Overview

FormView instances are an abstract representation of a form-based editor for model instances. It is deliberately modelled on HTML forms where possible.

Direct Known Subclasses

ActiveRecordFormView

Instance Attribute Summary

Attributes inherited from View

#actions, #controller

Instance Method Summary collapse

Methods included from Toolkit::SignalHandler::ClassMethods

#signal, #signals, #valid_signal!, #valid_signal?

Methods included from Toolkit::SignalHandler

#signal_connect, #signal_disconnect, #signal_emit

Constructor Details

#initialize(model, &block) ⇒ FormView

Returns a new instance of FormView.



45
46
47
48
49
50
51
# File 'lib/ruby_mvc/views/form_view.rb', line 45

def initialize(model, &block)
  @model = model
  @editors = {}
  @validators = {}
  @disabled = {}
  self.instance_eval(&block) if block
end

Instance Method Details

#disabled(key, val = true) ⇒ Object

This method is used to ensure that the specified model key field appears, but is disabled. This can also be done via the model by ensuring editable is false.



71
72
73
# File 'lib/ruby_mvc/views/form_view.rb', line 71

def disabled(key, val = true)
  @disabled[key.to_sym] = val
end

#editor(key, editor) ⇒ Object



53
54
55
# File 'lib/ruby_mvc/views/form_view.rb', line 53

def editor(key, editor)
  @editors[key.to_sym] = editor
end

#layout(&block) ⇒ Object

This method is used by the concrete hosting widget to iterate through the form field definitions so that it can create the actual UI form.



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/ruby_mvc/views/form_view.rb', line 79

def layout(&block)
  @model.labels.each do |l|
    k = l[:key]
    if (@disabled.has_key?(k) && @disabled[k]) \
        || !@model.is_editable?(k)
      disabled = true
    else
      disabled = false
    end
    block.call(k, l[:label], @model[k], @editors[k] || l[:editor], disabled)
  end
end

#reset(&block) ⇒ Object



102
103
104
105
106
107
# File 'lib/ruby_mvc/views/form_view.rb', line 102

def reset(&block)
  @model.keys.each do |k|
    block.call(k, @model[k])
  end
  signal_emit("form-reset", self, @model)
end

#submit(values) ⇒ Object

This method is called when the form should be saved to the underlying model.



95
96
97
98
99
100
# File 'lib/ruby_mvc/views/form_view.rb', line 95

def submit(values)
  values.each do |k, v|
    @model[k] = v if @model.is_editable? k
  end
  signal_emit("form-submit", self, @model)
end

#validator(key, &block) ⇒ Object

This method sets a validator block for the given key. More than one validator can be initialized for each property key



61
62
63
64
65
# File 'lib/ruby_mvc/views/form_view.rb', line 61

def validator(key, &block)
  return if !block
  vals = (@validators[key.to_sym] ||= [])
  vals << block
end