Class: Backend::FormBuilder

Inherits:
SimpleForm::FormBuilder
  • Object
show all
Defined in:
app/helpers/backend/form_builder.rb

Instance Method Summary collapse

Instance Method Details

#abilities_list(attribute_name = :abilities_list, options = {}) ⇒ Object


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
280
281
282
283
284
285
286
287
288
289
290
291
# File 'app/helpers/backend/form_builder.rb', line 239

def abilities_list(attribute_name = :abilities_list, options = {})
  prefix = @lookup_model_names.first +
           @lookup_model_names[1..-1].collect { |x| "[#{x}]" }.join +
           "[#{attribute_name}][]"
  input(attribute_name, options) do
    data_lists = {}
    @template.(:span, class: 'control-group abilities-list') do
      abilities_for_select = Nomen::Ability.list.sort_by(&:human_name).map do |a|
        attrs = { value: a.name }
        if a.parameters
          a.parameters.each do |parameter|
            if parameter == :variety
              data_lists[parameter] ||= Nomen::Variety.selection
            elsif parameter == :issue_nature
              data_lists[parameter] ||= Nomen::IssueNature.selection
            else
              raise "Unknown parameter type for an ability: #{parameter.inspect}"
            end
          end
          attrs[:data] = { ability_parameters: a.parameters.join(', ') }
        end
        @template.(:option, a.human_name, attrs)
      end.join.html_safe
      widget = @template.(:span, class: 'abilities') do
        if list = @object.send(attribute_name)
          list.collect do |a|
            ar = a.to_s.split(/[\(\,\s\)]+/).compact
            ability = Nomen::Ability[ar.shift]
            @template.(:div, data: { ability: ability.name }, class: :ability) do
              html = @template.label_tag ability.human_name
              html << @template.hidden_field_tag(prefix, a, class: 'ability-value')
              ar.each_with_index do |p, index|
                html << @template.select_tag(nil, @template.options_for_select(data_lists[ability.parameters[index]], p), data: { ability_parameter: index })
              end
              html << @template.link_to('#', data: { remove_closest: '.ability' }) do
                @template.(:i)
              end
              html
            end
          end.join.html_safe
        end
      end
      attrs = {}
      widget << @template.select_tag('ability-creator', abilities_for_select, name: nil)
      widget << ' '.html_safe
      widget << @template.link_to(:add.tl, '#ability-creator', data: { add_ability: prefix })
      data_lists.each do |key, selection|
        widget << @template.(:datalist, @template.options_for_select(selection), data: { ability_parameter_list: key })
      end
      widget
    end
  end
end

#access_control_list(name = :rights) ⇒ Object


665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
# File 'app/helpers/backend/form_builder.rb', line 665

def access_control_list(name = :rights)
  prefix = @lookup_model_names.first + @lookup_model_names[1..-1].collect { |x| "[#{x}]" }.join
  html = ''.html_safe
  reference = (@object.send(name) || {}).with_indifferent_access
  for resource, rights in Ekylibre::Access.resources.sort { |a, b| Ekylibre::Access.human_resource_name(a.first).ascii <=> Ekylibre::Access.human_resource_name(b.first).ascii }
    resource_reference = reference[resource] || []
    html << @template.(:div, class: 'control-group booleans') do
      @template.(:label, class: 'control-label') do
        Ekylibre::Access.human_resource_name(resource)
      end +
        @template.(:div, class: 'controls') do
          rights.collect do |interaction, right|
            checked = resource_reference.include?(interaction.to_s)
            attributes = { class: "chk-access chk-access-#{interaction}", data: { access: "#{interaction}-#{resource}" } }
            if right.dependencies
              attributes[:data][:need_accesses] = right.dependencies.join(' ')
            end
            attributes[:class] << ' active' if checked
            @template.(:label, attributes) do
              @template.check_box_tag("#{prefix}[#{name}][#{resource}][]", interaction, checked) +
                ERB::Util.h(Ekylibre::Access.human_interaction_name(interaction).strip)
            end
          end.join.html_safe
        end
    end
  end
  html
end

#actionsObject


702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'app/helpers/backend/form_builder.rb', line 702

def actions
  return nil unless @actions.any?
  @template.form_actions do
    html = ''.html_safe
    @actions.each do |action|
      html += if action[:type] == :block
                action[:content].html_safe
              else
                @template.send(action[:type], *action[:args])
              end
      html += ' '.html_safe
    end
    html
  end
end

#add(type = :block, *args, &block) ⇒ Object


718
719
720
721
722
723
724
725
726
727
# File 'app/helpers/backend/form_builder.rb', line 718

def add(type = :block, *args, &block)
  @actions ||= []
  if type == :block
    @actions << { type: type, content: @template.capture(&block) }
  else
    type = { submit: :submit_tag, link: :link_to }[type] || type
    @actions << { type: type, args: args }
  end
  true
end

#attachmentsObject


114
115
116
# File 'app/helpers/backend/form_builder.rb', line 114

def attachments
  nested_association :attachments
end

#attachments_field_setObject


108
109
110
111
112
# File 'app/helpers/backend/form_builder.rb', line 108

def attachments_field_set
  @template.field_set(:attachments) do
    attachments
  end
end

#backend_fields_for(*args, &block) ⇒ Object


472
473
474
475
476
477
478
479
480
481
482
483
# File 'app/helpers/backend/form_builder.rb', line 472

def backend_fields_for(*args, &block)
  options = args.extract_options!
  options[:wrapper] = self.options[:wrapper] if options[:wrapper].nil?
  options[:defaults] ||= self.options[:defaults]

  options[:builder] ||= if self.class < ActionView::Helpers::FormBuilder
                          self.class
                        else
                          Backend::FormBuilder
                        end
  fields_for(*(args << options), &block)
end

#clear_actions!Object


729
730
731
# File 'app/helpers/backend/form_builder.rb', line 729

def clear_actions!
  @actions = []
end

#custom_fieldsObject

Adds custom fields


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'app/helpers/backend/form_builder.rb', line 85

def custom_fields
  return nil unless @object.customizable?
  custom_fields = @object.class.custom_fields
  return nil unless custom_fields.any?
  @template.(:div, class: 'custom-fields') do
    simple_fields_for(:custom_fields, OpenStruct.new(@object.custom_fields)) do |cff|
      custom_fields.map do |custom_field|
        options = { as: custom_field.nature.to_sym, required: custom_field.required?, label: custom_field.name }
        if custom_field.choice?
          options[:collection] = custom_field.choices.collect { |c| [c.name, c.value] }
        end

        if custom_field.nature.to_sym == :number
          options[:as] = :string
          options[:input_html] = { pattern: '[0-9]+([.][0-9]+)?' }
        end

        cff.input(custom_field.column_name, options)
      end.join.html_safe
    end
  end
end

#date_range(start_attribute_name = :started_on, stop_attribute_name = :stopped_on, *args) ⇒ Object


436
437
438
439
440
441
442
443
444
445
# File 'app/helpers/backend/form_builder.rb', line 436

def date_range(start_attribute_name = :started_on, stop_attribute_name = :stopped_on, *args)
  options = args.extract_options!
  attribute_name = args.shift || options[:name] || :period
  input(attribute_name, options.merge(wrapper: :append)) do
    @template.(:span, :from.tl, class: 'add-on') +
      input(start_attribute_name, wrapper: :simplest) +
      @template.(:span, :to.tl, class: 'add-on') +
      input(stop_attribute_name, wrapper: :simplest)
  end
end

#datetime_range(*args) ⇒ Object


423
424
425
426
427
428
429
430
431
432
433
434
# File 'app/helpers/backend/form_builder.rb', line 423

def datetime_range(*args)
  options = args.extract_options!
  start_attribute_name = args.shift || :started_at
  stop_attribute_name = args.shift || :stopped_at
  attribute_name = args.shift || options[:name] || :period
  input(attribute_name, options.merge(wrapper: :append)) do
    @template.(:span, :from.tl, class: 'add-on') +
      input_field(start_attribute_name, options[:start_input_html] || options[:input_html]) +
      @template.(:span, :to.tl, class: 'add-on') +
      input_field(stop_attribute_name, options[:stop_input_html] || options[:input_html])
  end
end

#delta_field(value_attribute, delta_attribute, unit_name_attribute, unit_values, *args) ⇒ Object


447
448
449
450
451
452
453
454
455
456
457
# File 'app/helpers/backend/form_builder.rb', line 447

def delta_field(value_attribute, delta_attribute, unit_name_attribute, unit_values, *args)
  options = args.extract_options!
  attribute_name = args.shift || options[:name]

  input(attribute_name, options.merge(wrapper: :append)) do
    input(value_attribute, wrapper: :simplest) +
      @template.(:span, :delta.tl, class: 'add-on') +
      input(delta_attribute, wrapper: :simplest) +
      unit_field(unit_name_attribute, unit_values, args)
  end
end

#fields(partial = 'form') ⇒ Object


694
695
696
# File 'app/helpers/backend/form_builder.rb', line 694

def fields(partial = 'form')
  @template.(:div, base_form_error_tags + @template.render(partial, f: self), class: 'form-fields')
end

#find_input(attribute_name, options = {}, &block) ⇒ Object


186
187
188
189
190
191
192
193
194
# File 'app/helpers/backend/form_builder.rb', line 186

def find_input(attribute_name, options = {}, &block)
  input = super

  if is_nomenclature_select?(attribute_name)
    input&.options&.fetch(:collection)&.sort_by! &options.fetch(:label_method, :first)
  end

  input
end

#geolocation(attribute_name = :geolocation, options = {}) ⇒ Object


367
368
369
# File 'app/helpers/backend/form_builder.rb', line 367

def geolocation(attribute_name = :geolocation, options = {})
  point(attribute_name, options)
end

#geolocation_field(attribute_name = :geolocation, options = {}) ⇒ Object


371
372
373
# File 'app/helpers/backend/form_builder.rb', line 371

def geolocation_field(attribute_name = :geolocation, options = {})
  point_field(attribute_name, options)
end

#geometry(attribute_name, options = {}) ⇒ Object


305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'app/helpers/backend/form_builder.rb', line 305

def geometry(attribute_name, options = {})
  editor = options[:editor] || {}
  editor[:controls] ||= {}
  editor[:controls][:draw] ||= {}
  editor[:controls][:draw][:draw] = options[:draw] || {}
  editor[:controls][:importers] ||= { formats: %i[gml kml geojson], title: :import.tl, okText: :import.tl, cancelText: :close.tl }
  editor[:controls][:importers][:content] ||= @template.importer_form(editor[:controls][:importers][:formats])

  editor[:withoutLabel] = true

  geom = @object.send(attribute_name)
  if geom.present?
    geometry = Charta.new_geometry(geom)
    editor[:edit] = geometry.to_json_object
    editor[:view] = { center: geometry.centroid, zoom: 16 }
  else
    if sibling = @object.class.where("#{attribute_name} IS NOT NULL").first
      editor[:view] = { center: Charta.new_geometry(sibling.send(attribute_name)).centroid }
    elsif zone = CultivableZone.first
      editor[:view] = { center: zone.shape_centroid }
    end
  end
  show = options.delete(:show)
  unless show.is_a?(FalseClass)
    show ||= @object.class.where.not(attribute_name => nil)
    union = Charta.empty_geometry
    if show.any?
      if show.is_a?(Hash) && show.key?(:series)
        editor[:show] = show
      else
        union = show.geom_union(attribute_name)
        editor[:show] = union.to_json_object unless union.empty?
      end
    else
      editor[:show] = {}
      editor[:show][:series] = {}
    end
    editor[:useFeatures] = true
  end
  editor[:back] ||= MapLayer.available_backgrounds.collect(&:to_json_object)
  editor[:overlays] ||= MapLayer.available_overlays.collect(&:to_json_object)

  no_map = options.delete(:no_map)
  map_options = {}
  map_options = { input_html: { data: { map_editor: editor } } } unless no_map
  input(attribute_name, options.deep_merge(map_options))
end

#input(attribute_name, options = {}, &block) ⇒ Object

Updates default input method


160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'app/helpers/backend/form_builder.rb', line 160

def input(attribute_name, options = {}, &block)
  options[:input_html] ||= {}
  if options[:show]
    options[:input_html]['data-show'] = clean_targets(options.delete(:show))
  end
  if options[:hide]
    options[:input_html]['data-hide'] = clean_targets(options.delete(:hide))
  end
  unless options.key?(:disabled)
    if @object.is_a?(ActiveRecord::Base) && !@object.new_record? &&
       @object.class.readonly_attributes.include?(attribute_name.to_s)
      options[:disabled] = true unless options[:as] == :hidden
    end
  end
  autocomplete = options[:autocomplete]
  if autocomplete
    autocomplete = {} if autocomplete.is_a?(TrueClass)
    autocomplete[:column] ||= attribute_name.to_s
    autocomplete[:action] ||= :autocomplete
    autocomplete[:format] ||= :json
    options[:input_html]['data-autocomplete'] = @template.url_for(autocomplete)
  end
  super(attribute_name, options, &block)
end

#items_list(attribute_name, options = {}) ⇒ Object


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
# File 'app/helpers/backend/form_builder.rb', line 207

def items_list(attribute_name, options = {})
  prefix = @lookup_model_names.first +
           @lookup_model_names[1..-1].collect { |x| "[#{x}]" }.join +
           "[#{attribute_name}][]"
  if options[:selection]
    selection = options[:selection]
  elsif options[:of]
    selection = []
    if options[:of].to_s =~ /\#/
      array = options[:of].to_s.split('#')
      selection = Nomen[array.first].property_natures[array.second].selection
    else
      selection = Nomen[options[:of]].selection
    end
  else
    raise 'Need selection'
  end
  selection -= Indicateable::DEPRECATED if attribute_name == :variable_indicators_list || attribute_name == :frozen_indicators_list
  list = @object.send(attribute_name) || []
  input(attribute_name, options) do
    @template.(:span, class: 'control-group symbol-list') do
      selection.collect do |human_name, name|
        checked = list.include?(name.to_sym)
        @template.label_tag(nil, class: "nomenclature-item#{' checked' if checked}") do
          @template.check_box_tag(prefix, name, checked) +
            @template.(:span, human_name)
        end
      end.join.html_safe
    end
  end
end

#linestring(attribute_name, options = {}) ⇒ Object


301
302
303
# File 'app/helpers/backend/form_builder.rb', line 301

def linestring(attribute_name, options = {})
  geometry(attribute_name, options.merge(draw: { polygon: false, polyline: true }))
end

#list_input(association, options = {}) ⇒ Object


31
32
33
# File 'app/helpers/backend/form_builder.rb', line 31

def list_input(association, options = {})
  # TODO
end

#money(attribute_name, *args) ⇒ Object


413
414
415
416
417
418
419
420
421
# File 'app/helpers/backend/form_builder.rb', line 413

def money(attribute_name, *args)
  options = args.extract_options!
  currency_attribute_name = args.shift || options[:currency_attribute] || :currency
  input(attribute_name, options.merge(wrapper: :append)) do
    html = input_field(attribute_name)
    html << input_field(currency_attribute_name, collection: Nomen::Currency.items.values.collect { |c| [c.human_name, c.name.to_s] }.sort)
    html
  end
end

#nested_association(association, *args) ⇒ Object

Adds nested association support


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'app/helpers/backend/form_builder.rb', line 51

def nested_association(association, *args)
  options = args.extract_options!
  reflection = find_association_reflection(association)
  raise "Association #{association.inspect} not found" unless reflection
  if block_given?
    ActiveSupport::Deprecation.warn "Nested association don't take code block anymore. Use partial '#{association.to_s.singularize}_fields' instead."
  end
  # raise ArgumentError.new("Reflection #{reflection.name} must be a has_many") if reflection.macro != :has_many
  item = association.to_s.singularize
  partial = options[:partial] || item + '_fields'
  options[:locals] ||= {}
  html = simple_fields_for(association, options[:collection]) do |nested|
    @template.render(partial, options[:locals].merge(f: nested))
  end
  html_options = { id: "#{association}-field", class: "nested-#{association} nested-association" }
  if reflection.macro == :has_many
    unless options[:new].is_a?(FalseClass)
      html << @template.(:div, class: 'links') do
        @template.link_to_add_association(options[:button_label] || "labels.add_#{item}".t, self, association, 'data-no-turbolink' => true, partial: partial, render_options: { locals: options[:locals] }, class: "nested-add add-#{item}")
      end
    end
    if options[:minimum]
      html_options[:data] ||= {}
      html_options[:data][:association_insertion_minimum] = options[:minimum]
    end
    if options[:maximum]
      html_options[:data] ||= {}
      html_options[:data][:association_insertion_maximum] = options[:maximum]
    end
  end
  @template.(:div, html, html_options)
end

#picture(attribute_name = :picture, options = {}) ⇒ Object


196
197
198
199
200
201
202
203
204
205
# File 'app/helpers/backend/form_builder.rb', line 196

def picture(attribute_name = :picture, options = {})
  format = options.delete(:format) || :thumb
  input(attribute_name, options) do
    html = file_field(attribute_name)
    if @object.send(attribute_name).file?
      html << @template.(:div, @template.image_tag(@object.send(attribute_name).url(format)), class: 'preview picture')
    end
    html
  end
end

#point(attribute_name, options = {}) ⇒ Object


375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'app/helpers/backend/form_builder.rb', line 375

def point(attribute_name, options = {})
  marker = {}
  if geom = @object.send(attribute_name)
    marker[:marker] = Charta.new_geometry(geom).to_json_object['coordinates'].reverse
    marker[:view] = { center: marker[:marker] }
  else
    siblings = @object.class.where("#{attribute_name} IS NOT NULL").order(id: :desc)
    if siblings.any?
      sibling_point = siblings.first.send(attribute_name).to_rgeo
      marker[:view] = { center: [sibling_point.lat, sibling_point.lon] }
    elsif zone = CultivableZone.first
      marker[:view] = { center: zone.shape_centroid }
    end
    marker[:marker] = marker[:view][:center] if marker[:view]
  end
  marker[:background] ||= MapLayer.available_backgrounds.collect(&:to_json_object)
  input(attribute_name, options.merge(input_html: { data: { map_marker: marker } }))
end

#point_field(attribute_name, options = {}) ⇒ Object


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'app/helpers/backend/form_builder.rb', line 394

def point_field(attribute_name, options = {})
  marker = {}
  if geom = @object.send(attribute_name)
    coordinates = Charta.new_geometry(geom).to_json_object['coordinates']
    marker[:marker] = coordinates.reverse if coordinates
    marker[:view] = { center: marker[:marker] }
  else
    if sibling = @object.class.where("#{attribute_name} IS NOT NULL").first
      marker[:view] = { center: Charta.new_geometry(sibling.send(attribute_name)).centroid }
    elsif zone = CultivableZone.first
      marker[:view] = { center: zone.shape_centroid }
    end
    marker[:marker] = marker[:view][:center] if marker[:view]
  end
  marker[:background] ||= MapLayer.available_backgrounds.collect(&:to_json_object).first
  marker[:background] &&= MapLayer.default_background.to_json_object
  input_field(attribute_name, options.merge(data: { map_marker: marker }))
end

#polygon(attribute_name, options = {}) ⇒ Object


297
298
299
# File 'app/helpers/backend/form_builder.rb', line 297

def polygon(attribute_name, options = {})
  geometry(attribute_name, options)
end

#product_formObject


485
486
487
488
489
490
491
492
# File 'app/helpers/backend/form_builder.rb', line 485

def product_form
  model = object.class
  until @template.lookup_context.exists?("backend/#{model.name.tableize}/form", [], true)
    model = model.superclass
    break if model == ActiveRecord::Base || model == Ekylibre::Record::Base
  end
  @template.render "backend/#{model.name.tableize}/form", f: self
end

#product_form_frame(options = {}, &block) ⇒ Object

Build a frame for all product _forms


495
496
497
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
# File 'app/helpers/backend/form_builder.rb', line 495

def product_form_frame(options = {}, &block)
  html = ''.html_safe

  variant = @object.variant
  unless variant
    variant_id = @template.params[:variant_id]
    variant = ProductNatureVariant.where(id: variant_id.to_i).first if variant_id
  end

  full_name = nil
  if @template.params[:person_id]
    person = Entity.find(@template.params[:person_id])
    if person
      @object.born_at ||= person.born_at
      full_name = Entity.find(@template.params[:person_id]).full_name
    end
  end

  options[:input_html] ||= {}
  options[:input_html][:class] ||= ''

  if variant
    @object.nature ||= variant.nature
    whole_indicators = variant.whole_indicators
    # Add product type selector
    form = @template.field_set options[:input_html] do
      fs = input(:variant_id, value: variant.id, as: :hidden)
      # Add name
      fs << (full_name.nil? ? input(:name) : input(:name, input_html: { value: full_name }))
      # Add work number
      fs << input(:work_number) unless options[:work_number].is_a?(FalseClass)
      # Add variant selector
      fs << variety(scope: variant)

      fs << input(:born_at)
      fs << input(:dead_at)

      fs << nested_association(:labellings)

      # error message for indicators
      if Rails.env.development?
        fs << @object.errors.inspect if @object.errors.any?
      end

      # Adds owner fields
      if @object.initializeable?
        fs << @template.render(partial: 'backend/shared/initial_values_form', locals: { f: self })
      end

      # Add custom fields
      fs << custom_fields

      fs << attachments

      fs
    end
    html << form

    # Add form body
    html += if block_given?
              @template.capture(&block)
            else
              @template.render(partial: 'backend/shared/default_product_form', locals: { f: self })
            end

    # Add first indicators
    indicators = variant.variable_indicators.delete_if do |i|
      whole_indicators.include?(i) || %i[geolocation shape].include?(i.name.to_sym)
    end
    if object.new_record? && indicators.any?

      if @object.readings.empty?
        indicators.each do |indicator|
          @object.readings.build(indicator_name: indicator.name)
        end
      end

      html << @template.field_set(:indicators) do
        fs = ''.html_safe
        readings_without_shape = @object.readings.reject do |reading|
          # Based on L551 delete_if block
          indicator = reading.indicator_name
          whole_indicators.include?(indicator) ||
            %i[geolocation shape].include?(indicator.to_sym)
        end
        readings_without_shape.each do |reading|
          # error message for indicators
          if Rails.env.development?
            fs << reading.errors.inspect if reading.errors.any?
          end
          fs << backend_fields_for(:readings, reading) do |indfi|
            indfi.input(:product_id, as: :hidden) + indfi.reading
          end
        end
        fs
      end
    end

  else
    clear_actions!
    variants = ProductNatureVariant.of_variety(@object.class.name.underscore)
    if variants.any?
      html << @template.field_set(:choose_a_type_of_product) do
        #           buttons = ''.html_safe
        #           for variant in ProductNatureVariant.of_variety(@object.class.name.underscore)
        #             buttons << @template.link_to(variant.name, { action: :new, variant_id: variant.id }, class: 'btn')
        #           end
        #           buttons
        choices = {}
        choices[:action] ||= :unroll
        choices[:controller] ||= :product_nature_variants

        new_url = {}
        new_url[:controller] ||= @object.class.name.underscore.pluralize.downcase
        new_url[:action] ||= :new

        choices[:scope] = { of_variety: @object.class.name.underscore.to_sym } if @object.class.name.present?

        input_id = :variant_id

        html_options = {}
        html_options[:data] ||= {}
        @template.(:div, class: 'control-group') do
          @template.(:label, Product.human_attribute_name(:variant), class: 'control-label') +
            @template.(:div, class: 'controls') do
              input_field(:variant, html_options.deep_merge(as: :string, id: input_id, data: { selector: @template.url_for(choices), redirect_on_change_url: @template.url_for(new_url) }))
            end
        end
      end
    end

  end

  html
end

#reading(options = {}) ⇒ Object


118
119
120
121
# File 'app/helpers/backend/form_builder.rb', line 118

def reading(options = {})
  indicator = Nomen::Indicator.find!(@object.indicator_name)
  @template.render(partial: 'backend/shared/reading_form', locals: { f: self, indicator: indicator, hidden: (options[:as] == :hidden) })
end

#referenced_association(association, options = {}) ⇒ Object

Display a selector with “new” button


36
37
38
39
40
# File 'app/helpers/backend/form_builder.rb', line 36

def referenced_association(association, options = {})
  return self.association(association, options) if options[:as] == :hidden
  options = referenced_association_input_options(association, options)
  input(options[:reflection].foreign_key, options)
end

#referenced_association_field(association, options = {}) ⇒ Object

Display a selector with “new” button


43
44
45
46
47
48
# File 'app/helpers/backend/form_builder.rb', line 43

def referenced_association_field(association, options = {})
  return self.association(association, options) if options[:as] == :hidden
  options = referenced_association_input_options(association, options)
  html_options = options[:input_html].merge(options.slice(:as, :reflection))
  input_field(options[:reflection].foreign_key, html_options)
end

#referenced_nomenclature(association, options = {}) ⇒ Object

Raises:

  • (ArgumentError)

22
23
24
25
26
27
28
29
# File 'app/helpers/backend/form_builder.rb', line 22

def referenced_nomenclature(association, options = {})
  klass = @object.class
  reflection = klass.nomenclature_reflections[association]
  raise ArgumentError, "Invalid nomenclature reflection: #{association}" unless reflection
  options[:collection] ||= reflection.klass.selection
  options[:label] ||= klass.human_attribute_name(association)
  input(reflection.foreign_key, options)
end

#shape(attribute_name = :shape, options = {}) ⇒ Object


293
294
295
# File 'app/helpers/backend/form_builder.rb', line 293

def shape(attribute_name = :shape, options = {})
  geometry(attribute_name, options)
end

#shape_field(attribute_name = :shape, options = {}) ⇒ Object


353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'app/helpers/backend/form_builder.rb', line 353

def shape_field(attribute_name = :shape, options = {})
  raise @object.send(attribute_name)
  geometry = Charta.new_geometry(@object.send(attribute_name) || Charta.empty_geometry)
  options[:input_html] ||= {}
  options[:input_html][:data] ||= {}
  options[:input_html][:data][:map_editor] ||= {}
  options[:input_html][:data][:map_editor] ||= {}
  options[:input_html][:data][:map_editor][:back] ||= MapLayer.available_backgrounds.collect(&:to_json_object)
  options[:input_html][:data][:map_editor][:overlays] ||= MapLayer.available_overlays.collect(&:to_json_object)

  # return self.input(attribute_name, options.merge(input_html: {data: {spatial: geometry.to_json_object}}))
  input_field(attribute_name, options.merge(input_html: { data: { map_editor: { edit: geometry.to_json_object } } }))
end

#subset(name, options = {}, &block) ⇒ Object

Load a partial


460
461
462
463
464
465
466
467
468
469
470
# File 'app/helpers/backend/form_builder.rb', line 460

def subset(name, options = {}, &block)
  options[:id] ||= name
  if options[:depend_on]
    options['data-depend-on'] = options.delete(:depend_on)
  end
  if block_given?
    return @template.(:div, capture(&block), options)
  else
    return @template.(:div, @template.render(partial: "#{name}_form", locals: { f: self, object: @object }), options)
  end
end

#variant_quantifier_of(association, *args, &block) ⇒ Object


123
124
125
126
127
# File 'app/helpers/backend/form_builder.rb', line 123

def variant_quantifier_of(association, *args, &block)
  input("#{association}_quantifier", wrapper: :append) do
    variant_quantifier_of_field(association, *args, &block)
  end
end

#variant_quantifier_of_field(association, *args) ⇒ Object


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
# File 'app/helpers/backend/form_builder.rb', line 129

def variant_quantifier_of_field(association, *args)
  options = args.extract_options!
  unless reflection = find_association_reflection(association)
    raise "Association #{association.inspect} not found"
  end
  indicator_column = options[:indicator_column] || "#{association}_indicator"
  unit_column = options[:unit_column] || "#{association}_unit"
  html_options = { data: { variant_quantifier: "#{@object.class.name.underscore}_#{reflection.foreign_key}" } }
  # Adds quantifier
  %i[population working_duration].each do |quantifier|
    html_options[:data]["quantifiers_#{quantifier}".to_sym] = true if options[quantifier]
  end
  # Specify scope
  html_options[:data][:use_closest] = options[:closest] if options[:closest]
  option_tags = nil
  if variant = @object.send(association)
    quantifier_id = "#{@object.send(indicator_column)}-#{@object.send(unit_column)}"
    option_tags = variant.unified_quantifiers(options.slice(:population, :working_duration)).map do |quantifier|
      # Please update app/views/backend/product_nature_variants/quantifiers view if you change something here
      attrs = { value: "#{quantifier[:indicator][:name]}-#{quantifier[:unit][:name]}", data: { indicator: quantifier[:indicator][:name], unit: quantifier[:unit][:name], unit_symbol: quantifier[:unit][:symbol] } }
      attrs[:selected] = true if attrs[:value] == quantifier_id
      @template.(:option, :unit_and_indicator.tl(indicator: quantifier[:indicator][:human_name], unit: quantifier[:unit][:human_name]), attrs)
    end.join.html_safe
  end
  html = @template.select_tag("#{association}_quantifier", option_tags, html_options)
  html << input_field(indicator_column, as: :hidden, class: 'quantifier-indicator')
  html << input_field(unit_column, as: :hidden, class: 'quantifier-unit')
  html
end

#variety(options = {}) ⇒ Object


631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'app/helpers/backend/form_builder.rb', line 631

def variety(options = {})
  scope = options[:scope]
  varieties = Nomen::Variety.selection(scope ? scope.variety : nil)
  child_scope = options[:child_scope]
  if child_scope
    varieties.keep_if { |(_l, n)| child_scope.all? { |c| c.variety? && Nomen::Variety.find(c.variety) <= n } }
  end
  @object.variety ||= scope.variety if scope
  @object.variety ||= varieties.first.last if @object.new_record? && varieties.first
  if options[:derivative_of] || (scope && scope.derivative_of)
    derivatives = Nomen::Variety.selection(scope ? scope.derivative_of : nil)
    @object.derivative_of ||= scope.derivative_of if scope
    @object.derivative_of ||= derivatives.first.last if @object.new_record? && derivatives.first
    if child_scope
      derivatives.keep_if { |(_l, n)| child_scope.all? { |c| c.derivative_of? && Nomen::Variety.find(c.derivative_of) <= n } }
    end
  end
  if !derivatives.nil? && derivatives.any?
    return input(:variety, wrapper: :append, class: :inline) do
      field = ('<span class="add-on">' <<
          ERB::Util.h(:x_of_y.tl(x: '{@@@@[email protected]@@@}', y: '{@@@@[email protected]@@@}')) <<
          '</span>')
      field.gsub!('{@@', '</span>')
      field.gsub!('@@}', '<span class="add-on">')
      field.gsub!('<span class="add-on"></span>', '')
      field.gsub!('@@[email protected]@', input_field(:variety, as: :select, collection: varieties))
      field.gsub!('@@[email protected]@', input(:derivative_of, as: :select, collection: derivatives, wrapper: :nested))
      field.html_safe
    end
  else
    return input(:variety, collection: varieties)
  end
end

#yes_no_radio(attribute_name, options = {}) ⇒ Object


698
699
700
# File 'app/helpers/backend/form_builder.rb', line 698

def yes_no_radio(attribute_name, options = {})
  input(attribute_name, options.merge(as: :radio_buttons, collection: [[::I18n.t('boolean.polar.true_class'), true], [I18n.t('boolean.polar.false_class'), false]]))
end