Module: CamaleonCms::CustomFieldsRead

Extended by:
ActiveSupport::Concern
Included in:
PostDefault, TermTaxonomy
Defined in:
app/models/concerns/camaleon_cms/custom_fields_read.rb

Instance Method Summary collapse

Instance Method Details

#add_custom_field_group(values, kind = "Post") ⇒ Object Also known as: add_field_group

Model supported: PostType, Category, Post, Posttag, Widget, Plugin, Theme, User and Custom models pre configured Note 1: If you need add fields for all post's or all categories, then you need to add the fields into the

post_type.add_custom_field_group(values, kind = "Post")
post_type.add_custom_field_group(values, kind = "Category")

Note 2: If you need add fields for only the Post_type, you have to use options or metas return: CustomFieldGroup object kind: argument only for PostType model: (Post | Category | PostTag), default => Post. If kind = “” this will add group for all post_types


162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 162

def add_custom_field_group(values, kind = "Post")
  values = values.with_indifferent_access
  group = get_field_groups(kind).where(slug: values[:slug]).first
  unless group.present?
    site = _cama_get_field_site
    values[:parent_id] = site.id if site.present?
    if self.is_a?(CamaleonCms::Post) # harcoded for post to support custom field groups
      group = CamaleonCms::CustomFieldGroup.where(object_class: "Post", objectid: self.id).create!(values)
    else
      group = get_field_groups(kind).create!(values)
    end
  end
  group
end

#add_custom_field_to_default_group(item, options, kind = "Post") ⇒ Object Also known as: add_field

Add custom fields for a default group: This will create a new group with slug=_default if it doesn't exist yet more details in add_manual_field(item, options) from custom field groups kind: argument only for PostType model: (Post | Category | PostTag), default => Post


182
183
184
185
186
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 182

def add_custom_field_to_default_group(item, options, kind = "Post")
  g = get_field_groups(kind).where(slug: "_default").first
  g = add_custom_field_group({name: "Default Field Group", slug: "_default"}, kind) unless g.present?
  g.add_manual_field(item, options)
end

#get_field_groups(args = {}) ⇒ Object

Sample: mypost.get_field_groups() ==> return fields for posts from parent posttype Sample: mycat.get_field_groups() ==> return fields for categories from parent posttype Sample: myposttag.get_field_groups() ==> return fields for posttags from parent posttype Sample: mypost_type.get_field_groups('Post') => return custom fields for posts Sample: mypost_type.get_field_groups('Category') => return custom fields for posts Sample: mypost_type.get_field_groups('PostTag') => return custom fields for posts


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 29

def get_field_groups(args = {})
  args = args.is_a?(String) ?  {kind: args, include_parent: false } : {kind: "Post", include_parent: false }.merge(args)
  class_name = self.class.to_s.parseCamaClass
  case class_name
    when 'Category','PostTag'
      self.post_type.get_field_groups(class_name)
    when 'Post'
      if self.term_relationships.size.zero? && args[:cat_ids].nil?
        CamaleonCms::CustomFieldGroup.where("(objectid = ? AND object_class = ?) OR (objectid = ? AND object_class = ?)", self.id || -1, class_name, self.post_type.id, "PostType_#{class_name}")
      else
        cat_ids = self.categories.map(&:id)
        cat_ids += args[:cat_ids] unless args[:cat_ids].nil?
        cat_ids += CamaleonCms::Category.find(cat_ids).map {|category| _category_parents_ids(category)}.flatten.uniq
        CamaleonCms::CustomFieldGroup.where("(objectid = ? AND object_class = ?) OR
                                             (objectid = ? AND object_class = ?) OR
                                             (objectid IN (?) AND object_class = ?)",
                                            self.id || -1, class_name,
                                            self.post_type.id, "PostType_#{class_name}",
                                            cat_ids, "Category_#{class_name}")
      end
    when 'NavMenuItem'
      self.main_menu.custom_field_groups
    when 'PostType'
      if args[:kind] == "all"
        CamaleonCms::CustomFieldGroup.where(object_class: ["PostType_Post", "PostType_Post", "PostType_PostTag", "PostType"], objectid:  self.id )
      elsif args[:kind] == "post_type"
        self.custom_field_groups
      else
        CamaleonCms::CustomFieldGroup.where(object_class: "PostType_#{args[:kind]}", objectid:  self.id )
      end
    else # 'Plugin' or other classes
      self.field_groups
  end
end

#get_field_object(slug) ⇒ Object

return field object for current model


190
191
192
193
194
195
196
197
198
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 190

def get_field_object(slug)
  CamaleonCms::CustomField.where(
    slug: slug,
    parent_id: get_field_groups.pluck(:id),
  ).first || CamaleonCms::CustomField.where(
    slug: slug,
    parent_id: get_field_groups({include_parent: true})
  ).first
end

#get_field_value(_key, _default = nil, group_number = 0) ⇒ Object Also known as: get_field, get_field!

get custom field value _key: custom field key if value is not present, then return default return default only if the field was not registered


76
77
78
79
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 76

def get_field_value(_key, _default = nil, group_number = 0)
  v = get_field_values(_key, group_number).first rescue _default
  v.present? ? v : _default
end

#get_field_values(_key, group_number = 0) ⇒ Object Also known as: get_fields

get custom field values _key: custom field key


85
86
87
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 85

def get_field_values(_key, group_number = 0)
  custom_field_values.loaded? ? custom_field_values.select{|f| f.custom_field_slug == _key && f.group_number == group_number}.map{|f| f.value } : custom_field_values.where(custom_field_slug: _key, group_number: group_number).pluck(:value)
end

#get_field_values_hash(include_options = false) ⇒ Object

return all values “single value”, key2: [multiple, values], key3: value4 if include_options = false {values: “single value”, options: {a:1, b: 4}, key2: [multiple, values], options: {a=1, b=2 }} if include_options = true


122
123
124
125
126
127
128
129
130
131
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 122

def get_field_values_hash(include_options = false)
  fields = {}
  self.custom_field_values.to_a.uniq.each do |field_value|
    custom_field = field_value.custom_fields
    values = custom_field.values.where(objectid: self.id).pluck(:value)
    fields[field_value.custom_field_slug] = custom_field.cama_options[:multiple].to_s.to_bool ? values : values.first unless include_options
    fields[field_value.custom_field_slug] = {values: custom_field.cama_options[:multiple].to_s.to_bool ? values : values.first, options: custom_field.cama_options, id: custom_field.id} if include_options
  end
  fields.to_sym
end

#get_fields_grouped(field_keys) ⇒ Object

return the values of custom fields grouped by group_number field_keys: (array of keys) samples: my_object.get_fields_grouped(['my_slug1', 'my_slug2'])

return: [
          { 'my_slug1' => ["val 1"], 'my_slug2' => ['val 2']},
          { 'my_slug1' => ["val2 for slug1"], 'my_slug2' => ['val 2 for slug2']}
] ==> 2 groups

return: [
          { 'my_slug1' => ["val 1", 'val 2 for fields multiple support'], 'my_slug2' => ['val 2']},
          { 'my_slug1' => ["val2 for slug1", 'val 2'], 'my_slug2' => ['val 2 for slug2']}
          { 'my_slug1' => ["val3 for slug1", 'val 3'], 'my_slug2' => ['val 3 for slug2']}
] ==> 3 groups

puts res[0]['my_slug1'].first ==> "val 1"

105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 105

def get_fields_grouped(field_keys)
  res = []
  custom_field_values.where(custom_field_slug: field_keys).order(group_number: :asc).group_by(&:group_number).each do |group_number, group_fields|
    group = {}
    field_keys.each do |field_key|
      _tmp = []
      group_fields.each{ |field| _tmp << field.value if field_key == field.custom_field_slug }
      group[field_key] = _tmp if _tmp.present?
    end
    res << group
  end
  res
end

#get_fields_object(f = true) ⇒ Object

return all custom fields for current element {options: {, values: [], name: '', …} } deprecated f attribute


136
137
138
139
140
141
142
143
144
145
146
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 136

def get_fields_object(f=true)
  fields = {}
  self.custom_field_values.eager_load(:custom_fields).to_a.uniq.each do |field_value|
    custom_field = field_value.custom_fields
    # if custom_field.options[:show_frontend].to_s.to_bool
    values = custom_field.values.where(objectid: self.id).pluck(:value)
    fields[field_value.custom_field_slug] = custom_field.attributes.merge(options: custom_field.cama_options, values: custom_field.cama_options[:multiple].to_s.to_bool ? values : values.first)
    # end
  end
  fields.to_sym
end

#get_user_field_groups(site) ⇒ Object

get custom field groups for current user return collections CustomFieldGroup site: site object


67
68
69
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 67

def get_user_field_groups(site)
  site.custom_field_groups.where(object_class: self.class.to_s.parseCamaClass)
end

#save_field_value(key, value, order = 0, clear = true) ⇒ Object

Set custom field values for current model key: slug of the custom field value: array of values for multiple values support value: string value


234
235
236
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 234

def save_field_value(key, value, order = 0, clear = true)
  set_field_value(key, value, {clear: clear, order: order})
end

#set_field_value(key, value, args = {}) ⇒ Object

Set custom field values for current model (support for multiple group values) key: (string required) slug of the custom field value: (array | string) array: array of values for multiple values support, string: uniq value for the custom field args:

field_id: (integer optional) identifier of the custom field
order: order or position of the field value
group_number: number of the group (only for custom field group with is_repeat enabled)
clear: (boolean, default true) if true, will remove previous values and set these values, if not will append values

return false if the was not saved because there is not present the field with slug: key sample: my_post.set_field_value('subtitle', 'Sub Title') sample: my_post.set_field_value('subtitle', ['Sub Title1', 'Sub Title2']) # set values for a field (for fields that support multiple values) sample: my_post.set_field_value('subtitle', 'Sub Title', 1) sample: my_post.set_field_value('subtitle', 'Sub Title', 1, group_number: 1) # add field values for fields in group 1


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 251

def set_field_value(key, value, args = {})
  args = {order: 0, group_number: 0, field_id: nil, clear: true}.merge(args)
  args[:field_id] = get_field_object(key).id rescue nil unless args[:field_id].present?
  unless args[:field_id].present?
    raise ArgumentError, "There is no custom field configured for #{key}"
  end
  self.custom_field_values.where({custom_field_slug: key, group_number: args[:group_number]}).delete_all if args[:clear]
  v = {custom_field_id: args[:field_id], custom_field_slug: key, value: fix_meta_value(value), term_order: args[:order], group_number: args[:group_number]}
  if value.is_a?(Array)
    value.each do |val|
      self.custom_field_values.create!(v.merge({value: fix_meta_value(val)}))
    end
  else
    self.custom_field_values.create!(v)
  end
end

#set_field_values(datas = {}) ⇒ Object

save all fields sent from browser (reservated for browser request) sample:

"0"=>{ "untitled-text-box"=>{"id"=>"262", "values"=>{"0"=>"33333"}},
"1"=>{ "untitled-text-box"=>"values"=>{"0"=>"33333"}}

}


206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 206

def set_field_values(datas = {})
  if datas.present?
    ActiveRecord::Base.transaction do 
      self.custom_field_values.delete_all
      datas.each do |index, fields_data|
        fields_data.each do |field_key, values|
          if values[:values].present?
            order_value = -1
            ((values[:values].is_a?(Hash) || values[:values].is_a?(ActionController::Parameters)) ? values[:values].values : values[:values]).each do |value|
              item = self.custom_field_values.create!({custom_field_id: values[:id], custom_field_slug: field_key, value: fix_meta_value(value), term_order: order_value += 1, group_number: values[:group_number] || 0})
            end
          end
        end
      end
    end
  end
end

#update_field_value(_key, value = nil, group_number = 0) ⇒ Object

update new value for field with slug _key Sample: my_posy.update_field_value('sub_title', 'Test Sub Title')


226
227
228
# File 'app/models/concerns/camaleon_cms/custom_fields_read.rb', line 226

def update_field_value(_key, value = nil, group_number = 0)
  self.custom_field_values.where(custom_field_slug: _key, group_number: group_number).first.update_column('value', value) rescue nil
end