Class: DrgcmsFormFields::TreeSelect

Inherits:
Select show all
Defined in:
app/models/drgcms_form_fields/tree_select.rb

Overview

Implementation of tree_select DRG CMS form field. Field will provides multiple select functionality displayed as a tree. Might be used for selecting multiple categories in a parent-child tree view.#

Form options:

  • name: field name (required)

  • type: tree_select (required)

  • choices: Values for choices separated by comma. Values can also be specified like description:value.

In this case description will be shown to user, but value will be saved to document.

choices: 'OK:0,Ready:1,Error:2'
choices: Ruby,Pyton,PHP
  • eval: Choices will be provided by evaluating expression eval: ModelName.choices4_field; Model class should define method which will provide data for field. Data returned must be of type Array and have 3 elements. 1 - description text 2 - id value 3 - parent id

  • html: html options which apply to select and text_field fields (optional)

Form example:

10:
  name: categories
  type: tree_select
  eval: 'Categories.all_categories'
  multiple: true
  select_parent: false
  html:
    size: 50x10

Instance Attribute Summary

Attributes inherited from DrgcmsField

#css, #js

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Select

#add_edit_code, #add_view_code, #choices_in_eval, #choices_in_helper, #get_choices, #ro_standard

Methods inherited from DrgcmsField

#hash_to_options, #html, #initialize, #options_to_hash, #record_text_for, #ro_standard, #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

Return value. Return nil if input field is empty



156
157
158
159
160
161
162
163
164
165
166
167
# File 'app/models/drgcms_form_fields/tree_select.rb', line 156

def self.get_data(params, name)
  return nil if params['record'][name].blank?

  result = params['record'][name].split(',')
  result.delete_if(&:blank?)
  return nil if result.size == 0

  # convert to BSON objects if is BSON object ID
  result = result.map{ |e| BSON::ObjectId.from_string(e) } if BSON::ObjectId.legal?(result.first)
  # return only first element if multiple values select was not allowed
  params['record']["#{name}_multiple"] == '1' ? result : result.first  
end

Instance Method Details

#make_tree(parent) ⇒ Object

Prepare choices for tree data rendering.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'app/models/drgcms_form_fields/tree_select.rb', line 60

def make_tree(parent)
  return '' unless @choices[parent.to_s]

  @html << '<ul>'
  choices = if @choices[parent.to_s].first[3] != 0
    @choices[parent.to_s].sort_by {|e| e[3].to_i } # sort by order if first is not 0
  else  
    @choices[parent.to_s].sort_alphabetical_by(&:first) # use UTF-8 sort
  end
  choices.each do |choice|
    data = [ %("selected" : #{choice.last ? 'true' : 'false'} ) ]
    # only for parent objects
    if @choices[ choice[1].to_s ]
      # parent is not selectable
      data << '"disabled" : true' unless @parent.dc_dont?(@yaml['parent_disabled'], true)
      # parents are opened on start
      data << '"opened" : true' unless @parent.dc_dont?(@yaml['parent_opened'], true)
    end
    # data-jstree must be singe quoted
    @html << %(<li data-id="#{choice[1]}" data-jstree='{#{data.join(' , ')}}'>#{choice.first}\n)
    # call recursively for children     
    make_tree(choice[1]) if @choices[ choice[1].to_s ]
    @html << "</li>"
  end
  @html << '</ul>'  
end

#renderObject

Render tree_select field html code



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
# File 'app/models/drgcms_form_fields/tree_select.rb', line 90

def render
  set_initial_value('html','value')
  require 'sort_alphabetical'  
  
  record = record_text_for(@yaml['name'])
  clas   = 'tree-select' + (@readonly ? ' dc-readonly' : '')
  @html << "<div id=\"#{@yaml['name']}\" class=\"#{clas}\" #{set_style()} >"
  # Fill @choices hash. The key is parent object id
  @choices = {}
  choices_in_eval(@yaml['eval']).each do |data| 
    @choices[ data[2].to_s ] ||= [] 
    @choices[ data[2].to_s ] << (data << false)
  end
  # put current values hash with. To speed up selection when there is a lot of categories
  current_values = {}
  current = @record[@yaml['name']] || []
  current = [current] unless current.class == Array # non array fields
  current.each { |e| current_values[e.to_s] = true }
  # set third element of @choices when selected
  @choices.keys.each do |key|
    0.upto( @choices[key].size - 1 ) do |i|
      choice = @choices[key][i]
      choice[choice.size - 1] = true if current_values[ choice[1].to_s ]
    end
  end
  make_tree(nil)
  @html << '</div>'
  # add hidden communication field
  @html << @parent.hidden_field(record, @yaml['name'], value: current.join(','))
  # save multiple indicator for data processing on return
  @html << @parent.hidden_field(record, "#{@yaml['name']}_multiple", value: 1) if @yaml['multiple']
  # javascript to update hidden record field when tree looses focus
readonly_code = %(
,
"conditionalselect" : function (node) {
return false; }
)

  @js =<<EOJS
$(function(){
  $("##{@yaml['name']}").jstree( {
    "checkbox" : {"three_state" : false},        
    "core" : { "themes" : { "icons": false },
               "multiple" : #{@yaml['multiple'] ? 'true' : 'false'}  },
    "plugins" : ["checkbox", "conditionalselect"]
    #{@readonly ? readonly_code : ''}
  });
});
  
$(document).ready(function() {
  $('##{@yaml['name']}').on('focusout', function(e) {
    var checked_ids = [];
    var checked = $('##{@yaml['name']}').jstree("get_checked", true);
    $.each(checked, function() {
      checked_ids.push( this.data.id );
    });
    $('#record_#{@yaml['name']}').val( checked_ids.join(",") );
  });
});
EOJS
  self
end