Class: DynamicForm

Inherits:
ActiveRecord::Base
  • Object
show all
Extended by:
FriendlyId
Defined in:
app/models/dynamic_form.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.class_exists?(class_name) ⇒ Boolean

Returns:

  • (Boolean)

25
26
27
28
29
30
31
32
33
34
# File 'app/models/dynamic_form.rb', line 25

def self.class_exists?(class_name)
	result = nil
	begin
	  klass = Module.const_get(class_name)
    result = (klass.is_a?(Class) ? ((klass.superclass == ActiveRecord::Base or klass.superclass == DynamicModel) ? true : nil) : nil)
	rescue NameError
	  result = nil
	end
	result
end

.concat_fields_to_build_definition(array_of_fields) ⇒ Object


97
98
99
# File 'app/models/dynamic_form.rb', line 97

def self.concat_fields_to_build_definition(array_of_fields)
  array_of_fields.to_json
end

.get_form(klass_name, internal_identifier = '') ⇒ Object


36
37
38
39
40
41
# File 'app/models/dynamic_form.rb', line 36

def self.get_form(klass_name, internal_identifier='')
  result = nil  	
 result = DynamicForm.find_by_model_name_and_internal_identifier(klass_name, internal_identifier) unless internal_identifier.blank?
 result = DynamicForm.find_by_model_name_and_default(klass_name, true) if result.nil?
	result
end

Instance Method Details

#add_help_qtip(def_object) ⇒ Object


68
69
70
71
72
73
74
# File 'app/models/dynamic_form.rb', line 68

def add_help_qtip(def_object)
  def_object.each do |item|
    item[:plugins] = NonEscapeJsonString.new('[new helpQtip("'+item[:help_qtip].gsub(/\"/,'\"')+'")]') unless item[:help_qtip].blank?
  end
  
  def_object
end

#add_validation(def_object) ⇒ Object


56
57
58
59
60
61
62
63
64
65
66
# File 'app/models/dynamic_form.rb', line 56

def add_validation(def_object)
  def_object.each do |item|
    if !item[:validation_regex].blank?
      item[:regex] = NonEscapeJsonString.new(item[:validation_regex].match('^\/') ? item[:validation_regex] : '/'+item[:validation_regex]+'/')
    elsif !item[:validator_function].blank?
      item[:validator] = NonEscapeJsonString.new("function(v){ return #{item[:validator_function]}; }")
    end
  end
  
  def_object
end

#default_form_checkObject


18
19
20
21
22
23
# File 'app/models/dynamic_form.rb', line 18

def default_form_check
  # count how many forms this model has, if one, set as default
  if dynamic_form_model.dynamic_forms.count == 1
    DynamicFormModel.get_constant(self.model_name).set_default(self.id)
  end
end

#definition_objectObject

parse JSON definition into a ruby object returns an array of hashes


45
46
47
48
49
50
# File 'app/models/dynamic_form.rb', line 45

def definition_object
  o = JSON.parse(self.definition)
  o.map do |i|
    i = i.symbolize_keys
  end
end

#definition_with_validationObject


52
53
54
# File 'app/models/dynamic_form.rb', line 52

def definition_with_validation
  add_validation(self.definition_object)
end

#deprecated_field?(field_name) ⇒ Boolean

check field against form definition to see if field still exists returns true if field does not exist

Returns:

  • (Boolean)

88
89
90
91
92
93
94
95
# File 'app/models/dynamic_form.rb', line 88

def deprecated_field?(field_name)
  result = true
 definition_object.each do |field|
    result = false if field[:name] == field_name.to_s
  end
  
  result
end

#focus_first_field_jsObject


101
102
103
104
105
106
107
# File 'app/models/dynamic_form.rb', line 101

def focus_first_field_js
  if self.focus_first_field
    return "form.getComponent(0).focus(true, 200);"
  else
    return ''
  end
end

will return an array of field names that are of xtype 'related_combobox'


77
78
79
80
81
82
83
84
# File 'app/models/dynamic_form.rb', line 77

def related_fields
  related_fields = []
  definition_object.each do |f|
    related_fields << f if ['related_combobox','related_searchbox'].include?(f[:xtype])
  end

  related_fields
end

#should_generate_new_friendly_id?Boolean

Returns:

  • (Boolean)

12
13
14
# File 'app/models/dynamic_form.rb', line 12

def should_generate_new_friendly_id?
  new_record?
end

#submit_empty_text_jsObject


109
110
111
112
113
114
115
# File 'app/models/dynamic_form.rb', line 109

def submit_empty_text_js
  if self.submit_empty_text
    return "submitEmptyText: true,"
  else
    return ''
  end
end

#to_extjs_formpanel(options = {}) ⇒ Object


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
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
# File 'app/models/dynamic_form.rb', line 117

def to_extjs_formpanel(options={})   
  form_hash = {
    :xtype => 'dynamic_form_panel',
    :url => options[:url],
    :title => self.description,
    :frame => true,
    :bodyStyle => 'padding: 5px 5px 0;',
    :baseParams => {
      :dynamic_form_id => self.id,
      :dynamic_form_model_id => self.dynamic_form_model_id,
      :model_name => self.model_name
    },
    :defaults => {},
    :items => add_help_qtip(definition_with_validation)
  }
  form_hash[:defaults][:msgTarget] = self.msg_target unless self.msg_target.blank?
  form_hash[:width] = options[:width] if options[:width]
  form_hash[:baseParams][:id] = options[:record_id] if options[:record_id]
  form_hash[:listeners] = {
    :afterrender => NonEscapeJsonString.new("function(form) { #{focus_first_field_js} }")
  }
  form_hash[:buttons] = []
  form_hash[:buttons] << {
    :text => self.submit_button_label,
    :listeners => NonEscapeJsonString.new("{
        click:function(button){
            var form = button.findParentByType('form').getForm();
            //jsonSubmit option only works when there is no filefield so we have to do it ourselves
            //JSON is important to preserve data types (ie. we want integers to save as integers not strings)
            var form_data = {};
            Ext.each(form.getFields().items, function(field) {
              if (Ext.Array.indexOf(['filefield','fileuploadfield'], field.xtype) < 0){
                form_data[field.name] = field.getValue();
              } 
            });
            if (form.isValid()){
              form.submit({
                  #{submit_empty_text_js}
                  reset:false,
                  params:{
                    form_data_json: Ext.encode(form_data)
                  },
                  success:function(form, action){
                      var obj = Ext.decode(action.response.responseText);
                      if(obj.success){
                        if (form.getRecord()){
                          form.owner.fireEvent('afterupdate');
                        }else{
                          form.owner.fireEvent('aftercreate', {
                            record: obj
                          });
                        }
                      }else{
                        Ext.Msg.alert('Error', obj.message);
                      }
                  },
                  failure:function(form, action){
                    Ext.Msg.alert('Error', action.response.responseText);
                  }
              });
            }else{
              Ext.Msg.alert('Error','Please complete form.');
            }
        }
    }")
  }
  form_hash[:buttons] << {
    :text => self.cancel_button_label,
    :listeners => NonEscapeJsonString.new("{
        \"click\":function(button){
          var form = button.findParentByType('dynamic_form_panel');
          if (form.up('tabpanel')){
            form.up('tabpanel').remove(form.up('panel'));
          }else{
            form.up('window').close();
          }
        }
    }")
  }
    
  form_hash   
end

#to_extjs_widget(options = {}) ⇒ Object

convert form definition to ExtJS form definition is essentially the formpanel items

options hash: :url => pass in URL for form to post to :widget_result_id => :width =>


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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'app/models/dynamic_form.rb', line 207

def to_extjs_widget(options={})
  javascript = "Ext.QuickTips.init(); Ext.create('Ext.form.Panel',"
  
  config_hash = {
    :url => "#{options[:url]}",
    :title => "#{self.description}",
    :frame => true,
    :bodyStyle => 'padding: 5px 5px 0;',
    :renderTo => 'dynamic_form_target',
    :baseParams => {
      :dynamic_form_id => self.id,
      :dynamic_form_model_id => self.dynamic_form_model_id,
      :model_name => self.model_name
    },
    :items => add_help_qtip(definition_with_validation),
    :defaults => {},
    :listeners => {
      :afterrender => NonEscapeJsonString.new("function(form) { #{focus_first_field_js} }")
    }
  }
  config_hash[:defaults][:msgTarget] = self.msg_target unless self.msg_target.blank?
  config_hash[:width] = options[:width] if options[:width]
  config_hash[:buttons] = []
  config_hash[:buttons] << {
    :text => self.submit_button_label,
    :listeners => NonEscapeJsonString.new("{
        \"click\":function(button){
            var form = button.findParentByType('form').getForm();
            //jsonSubmit option only works when there is no filefield so we have to do it ourselves
            //JSON is important to preserve data types (ie. we want integers to save as integers not strings)
            var form_data = {};
            Ext.each(form.getFields().items, function(field) {
              if (Ext.Array.indexOf(['filefield','fileuploadfield'], field.xtype) < 0){
                form_data[field.name] = field.getValue();
              } 
            });
            form.submit({
                #{submit_empty_text_js}
                reset:true,
                params:{
                  form_data_json: Ext.encode(form_data)
                },
                success:function(form, action){
                    json_hash = Ext.decode(action.response.responseText);
                    Ext.get('#{options[:widget_result_id]}').dom.innerHTML = json_hash.response;
                    var scriptTags = Ext.get('#{options[:widget_result_id]}').dom.getElementsByTagName('script');
                    Ext.each(scriptTags, function(scriptTag){
                          eval(scriptTag.text);
                    });
                },
                failure:function(form, action){
                  if (action.response){
                    json_hash = Ext.decode(action.response.responseText);
                    Ext.get('#{options[:widget_result_id]}').dom.innerHTML = json_hash.response;
                  }
                }
            });
        }
    }")
  }
  config_hash[:buttons] << {
    :text => 'Reset',
    :listeners => NonEscapeJsonString.new("{
        \"click\":function(button){
            button.findParentByType('form').getForm().reset();
        }
    }")
  }

  javascript += "#{config_hash.to_json});"
  #logger.info javascript
  javascript
end