Class: DrgcmsFormFields::MultitextAutocomplete

Inherits:
DrgcmsField
  • Object
show all
Defined in:
app/models/drgcms_form_fields/multitext_autocomplete.rb

Overview

Implementation of multitext_autocomplete DRG Form field.

multitext_autocomplete field is complex data entry field which uses autocomplete function when selecting multiple values for MongoDB Array field. Array typically holds id’s of selected documents and control typically displays value of the field name defined by search options.

Form options:

  • name: field name (required)

  • type: multitext_autocomplete (required)

  • table Model (table) name which must contain searched field name.

  • search: Search may consist of three parameters from which are separated either by dot (.) or comma(,)

    • search_field_name; when table option is defined search must define field name which will be used for search query

    • collection_name.search_field_name; Same as above except that table options must be ommited.

    • collection_name.search_field_name.method_name; When searching is more complex custom search

    method may be defined in CollectionName model which will provide result set for search.

  • with_new Will add an icon for shortcut to add new document to collection

Form example:

90:
  name: kats
  type: multitext_autocomplete
  search: dc_category.name
  with_new: model_name
  size: 30

Instance Attribute Summary

Attributes inherited from DrgcmsField

#css, #js

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from DrgcmsField

#hash_to_options, #html, #initialize, #options_to_hash, #record_text_for, #set_css_code, #set_default_value, #set_initial_value, #set_style, #t

Constructor Details

This class inherits a constructor from DrgcmsFormFields::DrgcmsField

Class Method Details

.get_data(params, name) ⇒ Object

Class method for retrieving data from multitext_autocomplete form field. Values are sabed in parameters as name_id => id



206
207
208
209
210
211
212
213
# File 'app/models/drgcms_form_fields/multitext_autocomplete.rb', line 206

def self.get_data(params, name)
  r = []
  params['record'].each do |k, v| # inject does not work on params
    # if it starts with - then it was removed
    r << BSON::ObjectId.from_string(v) if k.starts_with?("#{name}_") && v[0] != '-'
  end
  r.uniq
end

Instance Method Details

#renderObject

Render multitext_autocomplete field html code



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
199
200
# File 'app/models/drgcms_form_fields/multitext_autocomplete.rb', line 70

def render
  # get field name
  if @yaml['search'].class == Hash
    table      = @yaml['search']['table']
    field_name = @yaml['search']['field']
    method     = @yaml['search']['method']
    search     = method.nil? ? field_name : "#{field_name}.#{method}"
  elsif @yaml['search'].to_s.match(/\.|\,/)
    table, field_name, method = @yaml['search'].split(/\.|\,/).map(&:strip)
    search = method.nil? ? field_name : "#{field_name}.#{method}"
  else # search and table name are separated
    search = field_name = @yaml['search']
  end
  # get table name
  if @yaml['table']
    table = if @yaml['table'].class == String
              @yaml['table']
            # eval(how_to_get_my_table_name)
            elsif @yaml['table']['eval']
              eval @yaml['table']['eval']
            else
              Rails.logger.error "Field #{@yaml['name']}: Invalid table parameter!"
              nil
            end
  end

  if table.blank? || search.blank?
    @html << 'Table or search field not defined!'
    return self
  end

  # does collection exists
  collection = table.classify.constantize rescue nil
  if collection.nil?
    @html << "Invalid table name: #{table}"
    return self
  end

  # does field exists
  unless @record.respond_to?(@yaml['name'])
    @html << "Invalid field name: #{@yaml['name']}"
    return self
  end

  # search data entry
  @yaml['html'] ||= {}
  @yaml['html']['value'] = ''   # must be. Otherwise it will look into record and return error
  @yaml['html']['placeholder'] = t('drgcms.search_placeholder')
  _name = '_' + @yaml['name']
  @html << '<div class="ui-autocomplete-border">'
  @html << @parent.link_to(@parent.mi_icon('plus-square-o green'), '#', onclick: 'return false;') # dummy add. But it is usefull.

  # text_field for autocomplete
  record = record_text_for(@yaml['name'])
  @html << '<span class="dc-text-autocomplete">' << @parent.text_field(record, _name, @yaml['html']) << '<span></span></span>'

  # link for adding new documents to searched collection
  if @yaml['with_new'] && !@readonly
    @html << ' ' +
             @parent.mi_icon('plus-square-o', class: 'in-edit-add', title: t('drgcms.new'),
             style: "vertical-align: top;", 'data-table' => @yaml['with_new'] )
  end

  # div to list active selections
  @html << "<div id =\"#{record}#{@yaml['name']}\">"
  # fill with current values
  current_values = @record.send(@yaml['name'])
  unless current_values.nil?
    current_values.each do |element|
  # this is quick and dirty trick. We have model dc_big_table which can be used for retrive
  # more complicated options
# TODO retrieve choices from big_table
      rec = if table == 'dc_big_table'
              collection.find(@yaml['name'], @parent.session)
            else
              collection.find(element)
            end

      @html << if rec
        link  = @parent.link_to(@parent.mi_icon('remove_circle red'), '#',
                onclick: %($('##{rec.id}').hide(); let v = $('##{record}_#{@yaml['name']}_#{rec.id}'); v.val("-" + v.val());return false;))
        link  = @parent.mi_icon('check green') if @readonly
        field = @parent.hidden_field(record, "#{@yaml['name']}_#{rec.id}", value: element)
        %(<div id="#{rec.id}" style="padding:4px;">#{link} #{rec.send(field_name)}<br>#{field}</div>)
      else
        '** error **'  # Related data is missing. It happends.
      end
    end
  end
  @html << "</div></div>"

  # Create text for div to be added when new category is selected
  link    = @parent.link_to(@parent.mi_icon('remove_circle red'), '#',
            onclick: %($('#rec_id').hide(); let v = $('##{record}_#{@yaml['name']}_rec_id'); v.val("-" + v.val());return false;"))
  field   = @parent.hidden_field(record, "#{@yaml['name']}_rec_id", value: 'rec_id')
  one_div = %(<div id="rec_id" style="padding:4px;">#{link} rec_search<br>#{field}</div>)

  # JS stuff
  @js << <<EOJS
$(document).ready(function() {
  $("##{record}_#{_name}").autocomplete( {
    source: function(request, response) {
      $.ajax({
        url: "#{ @parent.url_for( controller: 'dc_common', action: 'autocomplete' )}",
        type: "POST",
        dataType: "json",
        data: { input: request.term, table: "#{table}", search: "#{search}" #{(',id: "'+@yaml['id'] + '"') if @yaml['id']} },
        success: function(data) {
          response( $.map( data, function(key) {
            return key;
          }));
        }
      });
    },
    change: function (event, ui) { 
      let div = '#{one_div}';
      if (ui.item != null) { 
        div = div.replace(/rec_id/g, ui.item.id)
        div = div.replace('rec_search', ui.item.value)
        $("##{record}#{@yaml['name']}").append(div);
        $("##{record}_#{_name}").val('');
      }
      $("##{record}_#{_name}").focus();
    },
    minLength: 2
  });
});
EOJS

  self
end

#ro_standard(table, search) ⇒ Object

Returns value for readonly field



57
58
59
60
61
62
63
64
65
# File 'app/models/drgcms_form_fields/multitext_autocomplete.rb', line 57

def ro_standard(table, search)
  current_values = @record.send(@yaml['name'])
  return self if current_values.blank?

  table  = table.classify.constantize
  search = search.split(/\.|\,/).first if search.match(/\.|\,/)
  html   = current_values.inject('') { |r, element| r << table.find(element)[search] + '<br>' }
  super(html)
end