##// END OF EJS Templates
TabularFormBuilder moved out of application_helper.rb...
Jean-Philippe Lang -
r1015:66420fe4b7ec
parent child
Show More
@@ -0,0 +1,51
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 require 'action_view/helpers/form_helper'
19
20 class TabularFormBuilder < ActionView::Helpers::FormBuilder
21 include GLoc
22
23 def initialize(object_name, object, template, options, proc)
24 set_language_if_valid options.delete(:lang)
25 @object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
26 end
27
28 (field_helpers - %w(radio_button hidden_field) + %w(date_select)).each do |selector|
29 src = <<-END_SRC
30 def #{selector}(field, options = {})
31 return super if options.delete :no_label
32 label_text = l(options[:label]) if options[:label]
33 label_text ||= l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym)
34 label_text << @template.content_tag("span", " *", :class => "required") if options.delete(:required)
35 label = @template.content_tag("label", label_text,
36 :class => (@object && @object.errors[field] ? "error" : nil),
37 :for => (@object_name.to_s + "_" + field.to_s))
38 label + super
39 end
40 END_SRC
41 class_eval src, __FILE__, __LINE__
42 end
43
44 def select(field, choices, options = {}, html_options = {})
45 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
46 label = @template.content_tag("label", label_text,
47 :class => (@object && @object.errors[field] ? "error" : nil),
48 :for => (@object_name.to_s + "_" + field.to_s))
49 label + super
50 end
51 end
@@ -1,421 +1,386
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 module ApplicationHelper
19 19 include Redmine::WikiFormatting::Macros::Definitions
20 20
21 21 def current_role
22 22 @current_role ||= User.current.role_for_project(@project)
23 23 end
24 24
25 25 # Return true if user is authorized for controller/action, otherwise false
26 26 def authorize_for(controller, action)
27 27 User.current.allowed_to?({:controller => controller, :action => action}, @project)
28 28 end
29 29
30 30 # Display a link if user is authorized
31 31 def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
32 32 link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
33 33 end
34 34
35 35 # Display a link to user's account page
36 36 def link_to_user(user)
37 37 user ? link_to(user, :controller => 'account', :action => 'show', :id => user) : 'Anonymous'
38 38 end
39 39
40 40 def link_to_issue(issue)
41 41 link_to "#{issue.tracker.name} ##{issue.id}", :controller => "issues", :action => "show", :id => issue
42 42 end
43 43
44 44 def toggle_link(name, id, options={})
45 45 onclick = "Element.toggle('#{id}'); "
46 46 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
47 47 onclick << "return false;"
48 48 link_to(name, "#", :onclick => onclick)
49 49 end
50 50
51 51 def show_and_goto_link(name, id, options={})
52 52 onclick = "Element.show('#{id}'); "
53 53 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
54 54 onclick << "location.href='##{id}-anchor'; "
55 55 onclick << "return false;"
56 56 link_to(name, "#", options.merge(:onclick => onclick))
57 57 end
58 58
59 59 def image_to_function(name, function, html_options = {})
60 60 html_options.symbolize_keys!
61 61 tag(:input, html_options.merge({
62 62 :type => "image", :src => image_path(name),
63 63 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
64 64 }))
65 65 end
66 66
67 67 def prompt_to_remote(name, text, param, url, html_options = {})
68 68 html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
69 69 link_to name, {}, html_options
70 70 end
71 71
72 72 def format_date(date)
73 73 return nil unless date
74 74 # "Setting.date_format.size < 2" is a temporary fix (content of date_format setting changed)
75 75 @date_format ||= (Setting.date_format.blank? || Setting.date_format.size < 2 ? l(:general_fmt_date) : Setting.date_format)
76 76 date.strftime(@date_format)
77 77 end
78 78
79 79 def format_time(time, include_date = true)
80 80 return nil unless time
81 81 time = time.to_time if time.is_a?(String)
82 82 zone = User.current.time_zone
83 83 if time.utc?
84 84 local = zone ? zone.adjust(time) : time.getlocal
85 85 else
86 86 local = zone ? zone.adjust(time.getutc) : time
87 87 end
88 88 @date_format ||= (Setting.date_format.blank? || Setting.date_format.size < 2 ? l(:general_fmt_date) : Setting.date_format)
89 89 @time_format ||= (Setting.time_format.blank? ? l(:general_fmt_time) : Setting.time_format)
90 90 include_date ? local.strftime("#{@date_format} #{@time_format}") : local.strftime(@time_format)
91 91 end
92 92
93 93 def authoring(created, author)
94 94 time_tag = content_tag('acronym', distance_of_time_in_words(Time.now, created), :title => format_time(created))
95 95 l(:label_added_time_by, author || 'Anonymous', time_tag)
96 96 end
97 97
98 98 def day_name(day)
99 99 l(:general_day_names).split(',')[day-1]
100 100 end
101 101
102 102 def month_name(month)
103 103 l(:actionview_datehelper_select_month_names).split(',')[month-1]
104 104 end
105 105
106 106 def pagination_links_full(paginator, count=nil, options={})
107 107 page_param = options.delete(:page_param) || :page
108 108 url_param = params.dup
109 109
110 110 html = ''
111 111 html << link_to_remote(('&#171; ' + l(:label_previous)),
112 112 {:update => "content", :url => url_param.merge(page_param => paginator.current.previous)},
113 113 {:href => url_for(:params => url_param.merge(page_param => paginator.current.previous))}) + ' ' if paginator.current.previous
114 114
115 115 html << (pagination_links_each(paginator, options) do |n|
116 116 link_to_remote(n.to_s,
117 117 {:url => {:params => url_param.merge(page_param => n)}, :update => 'content'},
118 118 {:href => url_for(:params => url_param.merge(page_param => n))})
119 119 end || '')
120 120
121 121 html << ' ' + link_to_remote((l(:label_next) + ' &#187;'),
122 122 {:update => "content", :url => url_param.merge(page_param => paginator.current.next)},
123 123 {:href => url_for(:params => url_param.merge(page_param => paginator.current.next))}) if paginator.current.next
124 124
125 125 unless count.nil?
126 126 html << [" (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})", per_page_links(paginator.items_per_page)].compact.join(' | ')
127 127 end
128 128
129 129 html
130 130 end
131 131
132 132 def per_page_links(selected=nil)
133 133 links = Setting.per_page_options_array.collect do |n|
134 134 n == selected ? n : link_to_remote(n, {:update => "content", :url => params.dup.merge(:per_page => n)},
135 135 {:href => url_for(params.dup.merge(:per_page => n))})
136 136 end
137 137 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
138 138 end
139 139
140 140 def set_html_title(text)
141 141 @html_header_title = text
142 142 end
143 143
144 144 def html_title
145 145 title = []
146 146 title << @project.name if @project
147 147 title << @html_header_title
148 148 title << Setting.app_title
149 149 title.compact.join(' - ')
150 150 end
151 151
152 152 ACCESSKEYS = {:edit => 'e',
153 153 :preview => 'r',
154 154 :quick_search => 'f',
155 155 :search => '4',
156 156 }.freeze unless const_defined?(:ACCESSKEYS)
157 157
158 158 def accesskey(s)
159 159 ACCESSKEYS[s]
160 160 end
161 161
162 162 # Formats text according to system settings.
163 163 # 2 ways to call this method:
164 164 # * with a String: textilizable(text, options)
165 165 # * with an object and one of its attribute: textilizable(issue, :description, options)
166 166 def textilizable(*args)
167 167 options = args.last.is_a?(Hash) ? args.pop : {}
168 168 case args.size
169 169 when 1
170 170 obj = nil
171 171 text = args.shift || ''
172 172 when 2
173 173 obj = args.shift
174 174 text = obj.send(args.shift)
175 175 else
176 176 raise ArgumentError, 'invalid arguments to textilizable'
177 177 end
178 178
179 179 # when using an image link, try to use an attachment, if possible
180 180 attachments = options[:attachments]
181 181 if attachments
182 182 text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(gif|jpg|jpeg|png))!/) do |m|
183 183 style = $1
184 184 filename = $6
185 185 rf = Regexp.new(filename, Regexp::IGNORECASE)
186 186 # search for the picture in attachments
187 187 if found = attachments.detect { |att| att.filename =~ rf }
188 188 image_url = url_for :controller => 'attachments', :action => 'download', :id => found.id
189 189 "!#{style}#{image_url}!"
190 190 else
191 191 "!#{style}#{filename}!"
192 192 end
193 193 end
194 194 end
195 195
196 196 text = (Setting.text_formatting == 'textile') ?
197 197 Redmine::WikiFormatting.to_html(text) { |macro, args| exec_macro(macro, obj, args) } :
198 198 simple_format(auto_link(h(text)))
199 199
200 200 # different methods for formatting wiki links
201 201 case options[:wiki_links]
202 202 when :local
203 203 # used for local links to html files
204 204 format_wiki_link = Proc.new {|project, title| "#{title}.html" }
205 205 when :anchor
206 206 # used for single-file wiki export
207 207 format_wiki_link = Proc.new {|project, title| "##{title}" }
208 208 else
209 209 format_wiki_link = Proc.new {|project, title| url_for :controller => 'wiki', :action => 'index', :id => project, :page => title }
210 210 end
211 211
212 212 project = options[:project] || @project
213 213
214 214 # turn wiki links into html links
215 215 # example:
216 216 # [[mypage]]
217 217 # [[mypage|mytext]]
218 218 # wiki links can refer other project wikis, using project name or identifier:
219 219 # [[project:]] -> wiki starting page
220 220 # [[project:|mytext]]
221 221 # [[project:mypage]]
222 222 # [[project:mypage|mytext]]
223 223 text = text.gsub(/\[\[([^\]\|]+)(\|([^\]\|]+))?\]\]/) do |m|
224 224 link_project = project
225 225 page = $1
226 226 title = $3
227 227 if page =~ /^([^\:]+)\:(.*)$/
228 228 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
229 229 page = title || $2
230 230 title = $1 if page.blank?
231 231 end
232 232
233 233 if link_project && link_project.wiki
234 234 # check if page exists
235 235 wiki_page = link_project.wiki.find_page(page)
236 236 link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page)),
237 237 :class => ('wiki-page' + (wiki_page ? '' : ' new')))
238 238 else
239 239 # project or wiki doesn't exist
240 240 title || page
241 241 end
242 242 end
243 243
244 244 # turn issue and revision ids into links
245 245 # example:
246 246 # #52 -> <a href="/issues/show/52">#52</a>
247 247 # r52 -> <a href="/repositories/revision/6?rev=52">r52</a> (project.id is 6)
248 248 text = text.gsub(%r{([\s\(,-^])(#|r)(\d+)(?=[[:punct:]]|\s|<|$)}) do |m|
249 249 leading, otype, oid = $1, $2, $3
250 250 link = nil
251 251 if otype == 'r'
252 252 if project && (changeset = project.changesets.find_by_revision(oid))
253 253 link = link_to("r#{oid}", {:controller => 'repositories', :action => 'revision', :id => project.id, :rev => oid}, :class => 'changeset',
254 254 :title => truncate(changeset.comments, 100))
255 255 end
256 256 else
257 257 if issue = Issue.find_by_id(oid.to_i, :include => [:project, :status], :conditions => Project.visible_by(User.current))
258 258 link = link_to("##{oid}", {:controller => 'issues', :action => 'show', :id => oid}, :class => 'issue',
259 259 :title => "#{truncate(issue.subject, 100)} (#{issue.status.name})")
260 260 link = content_tag('del', link) if issue.closed?
261 261 end
262 262 end
263 263 leading + (link || "#{otype}#{oid}")
264 264 end
265 265
266 266 text
267 267 end
268 268
269 269 # Same as Rails' simple_format helper without using paragraphs
270 270 def simple_format_without_paragraph(text)
271 271 text.to_s.
272 272 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
273 273 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
274 274 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
275 275 end
276 276
277 277 def error_messages_for(object_name, options = {})
278 278 options = options.symbolize_keys
279 279 object = instance_variable_get("@#{object_name}")
280 280 if object && !object.errors.empty?
281 281 # build full_messages here with controller current language
282 282 full_messages = []
283 283 object.errors.each do |attr, msg|
284 284 next if msg.nil?
285 285 msg = msg.first if msg.is_a? Array
286 286 if attr == "base"
287 287 full_messages << l(msg)
288 288 else
289 289 full_messages << "&#171; " + (l_has_string?("field_" + attr) ? l("field_" + attr) : object.class.human_attribute_name(attr)) + " &#187; " + l(msg) unless attr == "custom_values"
290 290 end
291 291 end
292 292 # retrieve custom values error messages
293 293 if object.errors[:custom_values]
294 294 object.custom_values.each do |v|
295 295 v.errors.each do |attr, msg|
296 296 next if msg.nil?
297 297 msg = msg.first if msg.is_a? Array
298 298 full_messages << "&#171; " + v.custom_field.name + " &#187; " + l(msg)
299 299 end
300 300 end
301 301 end
302 302 content_tag("div",
303 303 content_tag(
304 304 options[:header_tag] || "span", lwr(:gui_validation_error, full_messages.length) + ":"
305 305 ) +
306 306 content_tag("ul", full_messages.collect { |msg| content_tag("li", msg) }),
307 307 "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
308 308 )
309 309 else
310 310 ""
311 311 end
312 312 end
313 313
314 314 def lang_options_for_select(blank=true)
315 315 (blank ? [["(auto)", ""]] : []) +
316 316 GLoc.valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
317 317 end
318 318
319 319 def label_tag_for(name, option_tags = nil, options = {})
320 320 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
321 321 content_tag("label", label_text)
322 322 end
323 323
324 324 def labelled_tabular_form_for(name, object, options, &proc)
325 325 options[:html] ||= {}
326 326 options[:html].store :class, "tabular"
327 327 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
328 328 end
329 329
330 330 def check_all_links(form_name)
331 331 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
332 332 " | " +
333 333 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
334 334 end
335 335
336 336 def progress_bar(pcts, options={})
337 337 pcts = [pcts, pcts] unless pcts.is_a?(Array)
338 338 pcts[1] = pcts[1] - pcts[0]
339 339 pcts << (100 - pcts[1] - pcts[0])
340 340 width = options[:width] || '100px;'
341 341 legend = options[:legend] || ''
342 342 content_tag('table',
343 343 content_tag('tr',
344 344 (pcts[0] > 0 ? content_tag('td', '', :width => "#{pcts[0].floor}%;", :class => 'closed') : '') +
345 345 (pcts[1] > 0 ? content_tag('td', '', :width => "#{pcts[1].floor}%;", :class => 'done') : '') +
346 346 (pcts[2] > 0 ? content_tag('td', '', :width => "#{pcts[2].floor}%;", :class => 'todo') : '')
347 347 ), :class => 'progress', :style => "width: #{width};") +
348 348 content_tag('p', legend, :class => 'pourcent')
349 349 end
350 350
351 351 def context_menu_link(name, url, options={})
352 352 options[:class] ||= ''
353 353 if options.delete(:selected)
354 354 options[:class] << ' icon-checked disabled'
355 355 options[:disabled] = true
356 356 end
357 357 if options.delete(:disabled)
358 358 options.delete(:method)
359 359 options.delete(:confirm)
360 360 options.delete(:onclick)
361 361 options[:class] << ' disabled'
362 362 url = '#'
363 363 end
364 364 link_to name, url, options
365 365 end
366 366
367 367 def calendar_for(field_id)
368 368 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
369 369 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
370 370 end
371 371
372 372 def wikitoolbar_for(field_id)
373 373 return '' unless Setting.text_formatting == 'textile'
374 374 javascript_include_tag('jstoolbar') + javascript_tag("var toolbar = new jsToolBar($('#{field_id}')); toolbar.draw();")
375 375 end
376 376
377 377 def content_for(name, content = nil, &block)
378 378 @has_content ||= {}
379 379 @has_content[name] = true
380 380 super(name, content, &block)
381 381 end
382 382
383 383 def has_content?(name)
384 384 (@has_content && @has_content[name]) || false
385 385 end
386 386 end
387
388 class TabularFormBuilder < ActionView::Helpers::FormBuilder
389 include GLoc
390
391 def initialize(object_name, object, template, options, proc)
392 set_language_if_valid options.delete(:lang)
393 @object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
394 end
395
396 (field_helpers - %w(radio_button hidden_field) + %w(date_select)).each do |selector|
397 src = <<-END_SRC
398 def #{selector}(field, options = {})
399 return super if options.delete :no_label
400 label_text = l(options[:label]) if options[:label]
401 label_text ||= l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym)
402 label_text << @template.content_tag("span", " *", :class => "required") if options.delete(:required)
403 label = @template.content_tag("label", label_text,
404 :class => (@object && @object.errors[field] ? "error" : nil),
405 :for => (@object_name.to_s + "_" + field.to_s))
406 label + super
407 end
408 END_SRC
409 class_eval src, __FILE__, __LINE__
410 end
411
412 def select(field, choices, options = {}, html_options = {})
413 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
414 label = @template.content_tag("label", label_text,
415 :class => (@object && @object.errors[field] ? "error" : nil),
416 :for => (@object_name.to_s + "_" + field.to_s))
417 label + super
418 end
419
420 end
421
General Comments 0
You need to be logged in to leave comments. Login now