Module: ApplicationHelper

Defined in:
app/helpers/application_helper.rb

Overview

Copyright © 2008-2013 Michael Dvorkin and contributors.

Fat Free CRM is freely distributable under the terms of MIT license. See MIT-LICENSE file or www.opensource.org/licenses/mit-license.php


Instance Method Summary collapse

Instance Method Details

#address_field(form, object, attribute, extra_styles) ⇒ Object

Render a text field that is part of compound address.




329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'app/helpers/application_helper.rb', line 329

def address_field(form, object, attribute, extra_styles)
  hint = "#{t(attribute)}..."
  if object.send(attribute).blank?
    form.text_field(attribute,
      :style   => "margin-top: 6px; #{extra_styles}",
      :placeholder => hint
    )
  else
    form.text_field(attribute,
      :style   => "margin-top: 6px; #{extra_styles}",
      :placeholder => hint
    )
  end
end

#arrow_for(id) ⇒ Object




100
101
102
# File 'app/helpers/application_helper.rb', line 100

def arrow_for(id)
  (:span, "►".html_safe, :id => "#{id}_arrow", :class => :arrow)
end

#avatar_for(model, args = {}) ⇒ Object

Entities can have associated avatars or gravatars. Only calls Gravatar in production env. Gravatar won’t serve default images if they are not publically available: en.gravatar.com/site/implement/images




304
305
306
307
308
309
310
311
312
313
314
315
# File 'app/helpers/application_helper.rb', line 304

def avatar_for(model, args = {})
  args = { :class => 'gravatar', :size => :large }.merge(args)

  if model.respond_to?(:avatar) and model.avatar.present?
    Avatar
    image_tag(model.avatar.image.url(args[:size]), args)
  else
    args = Avatar.size_from_style!(args) # convert size format :large => '75x75'
    gravatar_image_tag(model.email, args)
  end

end

#col(title, value, last = false, email = false) ⇒ Object

Create a column in the ‘asset_attributes’ table.




409
410
411
412
413
414
415
416
417
418
419
# File 'app/helpers/application_helper.rb', line 409

def col(title, value, last = false, email = false)
  # Parse and format urls as links.
  fmt_value = (value.to_s || "").gsub("\n", "<br />")
  fmt_value = if email
      link_to_email(fmt_value)
    else
      fmt_value.gsub(/((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/\+#]*[\w\-\@?^=%&amp;\/\+#])?)/, "<a href=\"\\1\">\\1</a>")
    end
  %Q^<th#{last ? " class=\"last\"" : ""}>#{title}:</th>
<td#{last ? " class=\"last\"" : ""}>#{fmt_value}</td>^.html_safe
end

#confirm_delete(model, params = {}) ⇒ Object




215
216
217
218
219
220
221
222
223
# File 'app/helpers/application_helper.rb', line 215

def confirm_delete(model, params = {})
  question = %(<span class="warn">#{t(:confirm_delete, model.class.to_s.downcase)}</span>).html_safe
  yes = link_to(t(:yes_button), params[:url] || model, :method => :delete)
  no = link_to_function(t(:no_button), "$('menu').update($('confirm').innerHTML)")
  update_page do |page|
    page << "$('confirm').update($('menu').innerHTML)"
    page[:menu].replace_html "#{question} #{yes} : #{no}"
  end
end

#current_view_nameObject


Return name of current view



437
438
439
440
441
# File 'app/helpers/application_helper.rb', line 437

def current_view_name
  controller = params['controller']
  action = (params['action'] == 'show') ? 'show' : 'index' # create update redraw filter index actions all use index view
  current_user.pref[:"#{controller}_#{action}_view"]
end

#entity_filter_checkbox(name, value, count) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'app/helpers/application_helper.rb', line 392

def entity_filter_checkbox(name, value, count)
  checked = (session["#{controller_name}_filter"].present? ? session["#{controller_name}_filter"].split(",").include?(value.to_s) : count.to_i > 0)
  values = %Q{$$("input[name='#{name}[]']").findAll(function (el) { return el.checked }).pluck("value")}
  params = h(%Q{"#{name}=" + #{values} + "&query=" + $("query").value})

  onclick = remote_function(
    :url      => { :action => :filter },
    :with     => params,
    :loading  => "$('loading').show()",
    :complete => "$('loading').hide()"
  )
  check_box_tag("#{name}[]", value, checked, :id => value, :onclick => onclick)
end

#exposedObject



195
# File 'app/helpers/application_helper.rb', line 195

def exposed;   { :style => "display:block;"      }; end

#generate_js_for_popups(related, *assets) ⇒ Object



70
71
72
73
74
# File 'app/helpers/application_helper.rb', line 70

def generate_js_for_popups(related, *assets)
  assets.map do |asset|
    render(:partial => "shared/select_popup", :locals => { :related => related, :popup => asset })
  end.join
end

#get_browser_timezone_offsetObject

Ajax helper to pass browser timezone offset to the server.




291
292
293
294
295
296
297
298
# File 'app/helpers/application_helper.rb', line 291

def get_browser_timezone_offset
  unless session[:timezone_offset]
    remote_function(
      :url  => timezone_path,
      :with => "'offset='+(new Date()).getTimezoneOffset()"
    )
  end
end

#get_default_permissions_intro(access, text) ⇒ Object

Returns default permissions intro.




319
320
321
322
323
324
325
# File 'app/helpers/application_helper.rb', line 319

def get_default_permissions_intro(access, text)
  case access
    when "Private" then t(:permissions_intro_private, text)
    when "Public"  then t(:permissions_intro_public,  text)
    when "Shared"  then t(:permissions_intro_shared,  text)
  end
end

#group_optionsObject



384
385
386
# File 'app/helpers/application_helper.rb', line 384

def group_options
  Group.all.map {|g| [g.name, g.id]}
end

#hiddenObject




194
# File 'app/helpers/application_helper.rb', line 194

def hidden;    { :style => "display:none;"       }; end

#hidden_if(you_ask) ⇒ Object




205
206
207
# File 'app/helpers/application_helper.rb', line 205

def hidden_if(you_ask)
  you_ask ? hidden : exposed
end

#invisibleObject



196
# File 'app/helpers/application_helper.rb', line 196

def invisible; { :style => "visibility:hidden;"  }; end

#invisible_if(you_ask) ⇒ Object




210
211
212
# File 'app/helpers/application_helper.rb', line 210

def invisible_if(you_ask)
  you_ask ? invisible : visible
end

#jumpbox(current) ⇒ Object




180
181
182
183
184
185
186
# File 'app/helpers/application_helper.rb', line 180

def jumpbox(current)
  tabs = [ :campaigns, :accounts, :leads, :contacts, :opportunities ]
  current = tabs.first unless tabs.include?(current)
  tabs.map do |tab|
    link_to_function(t("tab_#{tab}"), "crm.jumper('#{tab}')", :class => (tab == current ? 'selected' : ''))
  end.join(" | ").html_safe
end



144
145
146
147
148
149
150
# File 'app/helpers/application_helper.rb', line 144

def link_to_cancel(url, params = {})
  url = params[:url] if params[:url]
  link_to(t(:cancel),
    url + "#{url.include?('?') ? '&' : '?'}cancel=true",
    :remote => true
  )
end



153
154
155
156
157
158
159
# File 'app/helpers/application_helper.rb', line 153

def link_to_close(url)
  link_to("x", url + "#{url.include?('?') ? '&' : '?'}cancel=true",
    :remote => true,
    :class => "close",
    :title => t(:close_form)
  )
end



117
118
119
120
121
122
123
124
125
126
127
128
# File 'app/helpers/application_helper.rb', line 117

def link_to_delete(record, options = {})
  object = record.is_a?(Array) ? record.last : record
  confirm = options[:confirm] || nil

  link_to(t(:delete) + "!",
    options[:url] || url_for(record),
    :method => :delete,
    :remote => true,
    :onclick => visual_effect(:highlight, dom_id(object), :startcolor => "#ffe4e1"),
    :confirm => confirm
  )
end



131
132
133
134
135
136
137
138
139
140
141
# File 'app/helpers/application_helper.rb', line 131

def link_to_discard(object)
  current_url = (request.xhr? ? request.referer : request.fullpath)
  parent, parent_id = current_url.scan(%r|/(\w+)/(\d+)|).flatten

  link_to(t(:discard),
    url_for(:controller => parent, :action => :discard, :id => parent_id, :attachment => object.class.name, :attachment_id => object.id),
    :method  => :post,
    :remote  => true,
    :onclick => visual_effect(:highlight, dom_id(object), :startcolor => "#ffe4e1")
  )
end



105
106
107
108
109
110
111
112
113
114
# File 'app/helpers/application_helper.rb', line 105

def link_to_edit(record, options = {})
  object = record.is_a?(Array) ? record.last : record

  name = (params[:klass_name] || object.class.name).underscore.downcase
  link_to(t(:edit),
    options[:url] || polymorphic_url(record, :action => :edit),
    :remote  => true,
    :onclick => "this.href = this.href.split('?')[0] + '?previous='+crm.find_form('edit_#{name}');"
  )
end

Bcc: to dropbox address if the dropbox has been set up.




163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'app/helpers/application_helper.rb', line 163

def link_to_email(email, length = nil, &block)
  name = (length ? truncate(email, :length => length) : email)
  if Setting.email_dropbox && Setting.email_dropbox[:address].present?
    mailto = "#{email}?bcc=#{Setting.email_dropbox[:address]}"
  else
    mailto = email
  end
  if block_given?
    link_to("mailto:#{mailto}", :title => email) do
      yield
    end
  else
    link_to(h(name), "mailto:#{mailto}", :title => email)
  end
end



86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/helpers/application_helper.rb', line 86

def link_to_inline(id, url, options = {})
  text = options[:text] || t(id, :default => id.to_s.titleize)
  text = (arrow_for(id) + text) unless options[:plain]
  related = (options[:related] ? "&related=#{options[:related]}" : '')

  link_to(text,
    url + "#{url.include?('?') ? '&' : '?'}cancel=false" + related,
    :remote => true,
    :onclick => "this.href = this.href.replace(/cancel=(true|false)/,'cancel='+ Element.visible('#{id}'));",
    :class => options[:class]
  )
end

Helper to display links to supported data export formats.




356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'app/helpers/application_helper.rb', line 356

def links_to_export(action=:index)
  token = current_user.single_access_token
  url_params = {:action => action}
  url_params.merge!(:id => params[:id]) unless params[:id].blank?
  url_params.merge!(:query => params[:query]) unless params[:query].blank?
  url_params.merge!(:q => params[:q]) unless params[:q].blank?
  url_params.merge!(:view => @view) unless @view.blank? # tasks
  url_params.merge!(:id => params[:id]) unless params[:id].blank?

  exports = %w(xls csv).map do |format|
    link_to(format.upcase, url_params.merge(:format => format), :title => I18n.t(:"to_#{format}")) unless action.to_s == "show"
  end

  feeds = %w(rss atom).map do |format|
    link_to(format.upcase, url_params.merge(:format => format, :authentication_credentials => token), :title => I18n.t(:"to_#{format}"))
  end

  links = %W(perm).map do |format|
    link_to(format.upcase, url_params, :title => I18n.t(:"to_#{format}"))
  end

  (exports + feeds + links).compact.join(' | ')
end

#list_of_entitiesObject



388
389
390
# File 'app/helpers/application_helper.rb', line 388

def list_of_entities
  ENTITIES
end

#load_select_popups_for(related, *assets) ⇒ Object




63
64
65
66
67
68
# File 'app/helpers/application_helper.rb', line 63

def load_select_popups_for(related, *assets)
  js = generate_js_for_popups(related, *assets)
  content_for(:javascript_epilogue) do
    raw "document.observe('dom:loaded', function() { #{js} });"
  end
end

#one_submit_only(form) ⇒ Object




200
201
202
# File 'app/helpers/application_helper.rb', line 200

def one_submit_only(form)
  { :onsubmit => "$$('#'+this.id+' input[type=\"submit\"]')[0].disabled = true" }
end

#options_menu_item(option, key, url = nil) ⇒ Object




277
278
279
280
281
282
283
284
285
286
287
# File 'app/helpers/application_helper.rb', line 277

def options_menu_item(option, key, url = nil)
  name = t("option_#{key}")
  "{ name: \"#{name.titleize}\", on_select: function() {" +
  remote_function(
    :url       => url || send("redraw_#{controller.controller_name}_path"),
    :with      => "'#{option}=#{key}&query=' + $(\"query\").value",
    :condition => "$('#{option}').innerHTML != '#{name}'",
    :loading   => "$('#{option}').update('#{name}'); $('loading').show()",
    :complete  => "$('loading').hide()"
  ) + "}}"
end

#rating_select(name, options = {}) ⇒ Object

We need this because standard Rails [select] turns &#9733; into &amp;#9733;




78
79
80
81
82
83
# File 'app/helpers/application_helper.rb', line 78

def rating_select(name, options = {})
  stars = Hash[ (1..5).map { |star| [ star, "&#9733;" * star ] } ].sort
  options_for_select = %Q(<option value="0"#{options[:selected].to_i == 0 ? ' selected="selected"' : ''}>#{t :select_none}</option>)
  options_for_select << stars.map { |star| %(<option value="#{star.first}"#{options[:selected] == star.first ? ' selected="selected"' : ''}>#{star.last}</option>) }.join
  select_tag name, options_for_select.html_safe, options
end

#redraw(option, value, url = nil) ⇒ Object

Ajax helper to refresh current index page once the user selects an option.




263
264
265
266
267
268
269
270
271
272
273
274
# File 'app/helpers/application_helper.rb', line 263

def redraw(option, value, url = nil)
  if value.is_a?(Array)
    param, value = value.first, value.last
  end
  remote_function(
    :url       => url || send("redraw_#{controller.controller_name}_path"),
    :with      => "'#{option}=#{param || value}'",
    :condition => "$('#{option}').innerHTML != '#{value}'",
    :loading   => "$('#{option}').update('#{value}'); $('loading').show()",
    :complete  => "$('loading').hide()"
  )
end

#refresh_sidebar(action = nil, shake = nil) ⇒ Object

Reresh sidebar using the action view within the current controller.




232
233
234
# File 'app/helpers/application_helper.rb', line 232

def refresh_sidebar(action = nil, shake = nil)
  refresh_sidebar_for(controller.controller_name, action, shake)
end

#refresh_sidebar_for(view, action = nil, shake = nil) ⇒ Object

Refresh sidebar using the action view within an arbitrary controller.




238
239
240
241
242
243
# File 'app/helpers/application_helper.rb', line 238

def refresh_sidebar_for(view, action = nil, shake = nil)
  update_page do |page|
    page[:sidebar].replace_html :partial => "layouts/sidebar", :locals => { :view => view, :action => action }
    page[shake].visual_effect(:shake, :duration => 0.2, :distance => 3) if shake
  end
end

#section(related, assets) ⇒ Object




48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/helpers/application_helper.rb', line 48

def section(related, assets)
  asset = assets.to_s.singularize
  create_id  = "create_#{asset}"
  select_id  = "select_#{asset}"
  create_url = controller.send(:"new_#{asset}_path")

  html = tag(:br)
  html << (:div, link_to(t(select_id), "#", :id => select_id), :class => "subtitle_tools")
  html << (:div, "&nbsp;|&nbsp;".html_safe, :class => "subtitle_tools")
  html << (:div, link_to_inline(create_id, create_url, :related => dom_id(related), :text => t(create_id)), :class => "subtitle_tools")
  html << (:div, t(assets), :class => :subtitle, :id => "create_#{asset}_title")
  html << (:div, "", :class => :remote, :id => create_id, :style => "display:none;")
end

#section_title(id, hidden = true, text = nil, info_text = nil) ⇒ Object


Combines the ‘subtitle’ helper with the small info text on the same line.



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

def section_title(id, hidden = true, text = nil, info_text = nil)
  text = id.to_s.split("_").last.capitalize if text == nil
  ("div", :class => "subtitle show_attributes") do
    content = link_to("<small>#{ hidden ? "&#9658;" : "&#9660;" }</small> #{text}".html_safe,
      url_for(:controller => :home, :action => :toggle, :id => id),
      :remote  => true,
      :onclick => "crm.flip_subtitle(this)"
    )
    content << ("small", info_text.to_s, {:class => "subtitle_inline_info", :id => "#{id}_intro", :style => hidden ? "" : "display:none;"})
  end
end

#show_flash(options = { :sticky => false }) ⇒ Object

Show existing flash or embed hidden paragraph ready for flash




26
27
28
29
30
31
32
33
34
35
# File 'app/helpers/application_helper.rb', line 26

def show_flash(options = { :sticky => false })
  [:error, :warning, :info, :notice].each do |type|
    if flash[type]
      html = (:div, h(flash[type]), :id => "flash")
      flash[type] = nil
      return html << (:script, "crm.flash('#{type}', #{options[:sticky]})".html_safe, :type => "text/javascript")
    end
  end
  (:p, nil, :id => "flash", :style => "display:none;")
end

#shown_on_landing_page?Boolean

Return true if:

- it's an Ajax request made from the asset landing page (i.e. create opportunity
  from a contact landing page) OR
- we're actually showing asset landing page.

Returns:

  • (Boolean)


349
350
351
352
# File 'app/helpers/application_helper.rb', line 349

def shown_on_landing_page?
  !!((request.xhr? && request.referer =~ %r|/\w+/\d+|) ||
     (!request.xhr? && request.fullpath =~ %r|/\w+/\d+|))
end

#spacer(width = 10) ⇒ Object




226
227
228
# File 'app/helpers/application_helper.rb', line 226

def spacer(width = 10)
  image_tag "1x1.gif", :width => width, :height => 1, :alt => nil
end

#styles_for(*models) ⇒ Object




189
190
191
# File 'app/helpers/application_helper.rb', line 189

def styles_for(*models)
  render :partial => "shared/inline_styles", :locals => { :models => models }
end

#subtitle(id, hidden = true, text = id.to_s.split("_").last.capitalize) ⇒ Object




38
39
40
41
42
43
44
45
# File 'app/helpers/application_helper.rb', line 38

def subtitle(id, hidden = true, text = id.to_s.split("_").last.capitalize)
  ("div",
    link_to("<small>#{ hidden ? "&#9658;" : "&#9660;" }</small> #{text}".html_safe,
      url_for(:controller => :home, :action => :toggle, :id => id),
      :remote => true,
      :onclick => "crm.flip_subtitle(this)"
    ), :class => "subtitle")
end

#tabless_layout?Boolean


Returns:

  • (Boolean)


19
20
21
22
# File 'app/helpers/application_helper.rb', line 19

def tabless_layout?
  %w(authentications passwords).include?(controller.controller_name) ||
  ((controller.controller_name == "users") && (%w(create new).include?(controller.action_name)))
end

#tabs(tabs = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'app/helpers/application_helper.rb', line 8

def tabs(tabs = nil)
  tabs ||= controller_path =~ /admin/ ? FatFreeCRM::Tabs.admin : FatFreeCRM::Tabs.main
  if tabs
    @current_tab ||= tabs.first[:text] # Select first tab by default.
    tabs.each { |tab| tab[:active] = (@current_tab == tab[:text] || @current_tab == tab[:url][:controller]) }
  else
    raise FatFreeCRM::MissingSettings, "Tab settings are missing, please run <b>rake ffcrm:setup</b> command."
  end
end

#template_for_current_viewObject


Get template in current context with current view name



445
446
447
448
449
450
# File 'app/helpers/application_helper.rb', line 445

def template_for_current_view
  controller = params['controller']
  action = (params['action'] == 'show') ? 'show' : 'index' # create update redraw filter index actions all use index view
  template = FatFreeCRM::ViewFactory.template_for_current_view(:controller => controller, :action => action, :name => current_view_name)
  template
end

#user_optionsObject



380
381
382
# File 'app/helpers/application_helper.rb', line 380

def user_options
  User.all.map {|u| [u.full_name, u.id]}
end

#view_buttonsObject


Generate buttons for available views given the current context



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'app/helpers/application_helper.rb', line 454

def view_buttons
  controller = params['controller']
  action = (params['action'] == 'show') ? 'show' : 'index' # create update redraw filter index actions all use index view
  views = FatFreeCRM::ViewFactory.views_for(:controller => controller, :action => action)
  return nil unless views.size > 1
   :ul, :class => 'format-buttons' do
    views.collect do |view|
      classes = if (current_view_name == view.name) or (current_view_name == nil and view.template == nil) # nil indicates default template.
          "#{view.name}-button active"
        else
          "#{view.name}-button"
        end
      (:li) do
        url = (action == "index") ? send("redraw_#{controller}_path") : send("#{controller.singularize}_path")
        link_to('#', :title => t(view.name, :default => view.title), :"data-view" => view.name, :"data-url" => url, :"data-context" => action, :class => classes) do
          image_tag(view.icon || 'brief.png')
        end
      end
    end.join('').html_safe
  end
end

#visibleObject



197
# File 'app/helpers/application_helper.rb', line 197

def visible;   { :style => "visibility:visible;" }; end

#web_presence_icons(person) ⇒ Object

Display web presence mini-icons for Contact or Lead.




247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'app/helpers/application_helper.rb', line 247

def web_presence_icons(person)
  [ :blog, :linkedin, :facebook, :twitter, :skype ].map do |site|
    url = person.send(site)
    unless url.blank?
      if site == :skype then
        url = "callto:" << url
      else
        url = "http://" << url unless url.match(/^https?:\/\//)
      end
      link_to(image_tag("#{site}.gif", :size => "15x15"), url, :"data-popup" => true, :title => t(:open_in_window, url))
    end
  end.compact.join("\n").html_safe
end