##// END OF EJS Templates
Use #reduce instead of #inject for getting the intersection of arrays....
Jean-Philippe Lang -
r8707:8c38510ee504
parent child
Show More
@@ -1,66 +1,66
1 class ContextMenusController < ApplicationController
1 class ContextMenusController < ApplicationController
2 helper :watchers
2 helper :watchers
3 helper :issues
3 helper :issues
4
4
5 def issues
5 def issues
6 @issues = Issue.visible.all(:conditions => {:id => params[:ids]}, :include => :project)
6 @issues = Issue.visible.all(:conditions => {:id => params[:ids]}, :include => :project)
7 if (@issues.size == 1)
7 if (@issues.size == 1)
8 @issue = @issues.first
8 @issue = @issues.first
9 end
9 end
10
10
11 @allowed_statuses = @issues.map(&:new_statuses_allowed_to).inject{|memo,a| memo & a}
11 @allowed_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
12 @projects = @issues.collect(&:project).compact.uniq
12 @projects = @issues.collect(&:project).compact.uniq
13 @project = @projects.first if @projects.size == 1
13 @project = @projects.first if @projects.size == 1
14
14
15 @can = {:edit => User.current.allowed_to?(:edit_issues, @projects),
15 @can = {:edit => User.current.allowed_to?(:edit_issues, @projects),
16 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
16 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
17 :update => (User.current.allowed_to?(:edit_issues, @projects) || (User.current.allowed_to?(:change_status, @projects) && !@allowed_statuses.blank?)),
17 :update => (User.current.allowed_to?(:edit_issues, @projects) || (User.current.allowed_to?(:change_status, @projects) && !@allowed_statuses.blank?)),
18 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
18 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
19 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
19 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
20 :delete => User.current.allowed_to?(:delete_issues, @projects)
20 :delete => User.current.allowed_to?(:delete_issues, @projects)
21 }
21 }
22 if @project
22 if @project
23 if @issue
23 if @issue
24 @assignables = @issue.assignable_users
24 @assignables = @issue.assignable_users
25 else
25 else
26 @assignables = @project.assignable_users
26 @assignables = @project.assignable_users
27 end
27 end
28 @trackers = @project.trackers
28 @trackers = @project.trackers
29 else
29 else
30 #when multiple projects, we only keep the intersection of each set
30 #when multiple projects, we only keep the intersection of each set
31 @assignables = @projects.map(&:assignable_users).inject{|memo,a| memo & a}
31 @assignables = @projects.map(&:assignable_users).reduce(:&)
32 @trackers = @projects.map(&:trackers).inject{|memo,t| memo & t}
32 @trackers = @projects.map(&:trackers).reduce(:&)
33 end
33 end
34
34
35 @priorities = IssuePriority.active.reverse
35 @priorities = IssuePriority.active.reverse
36 @back = back_url
36 @back = back_url
37
37
38 @options_by_custom_field = {}
38 @options_by_custom_field = {}
39 if @can[:edit]
39 if @can[:edit]
40 custom_fields = @issues.map(&:available_custom_fields).inject {|memo, f| memo & f}.select do |f|
40 custom_fields = @issues.map(&:available_custom_fields).reduce(:&).select do |f|
41 %w(bool list user version).include?(f.field_format) && !f.multiple?
41 %w(bool list user version).include?(f.field_format) && !f.multiple?
42 end
42 end
43 custom_fields.each do |field|
43 custom_fields.each do |field|
44 values = field.possible_values_options(@projects)
44 values = field.possible_values_options(@projects)
45 if values.any?
45 if values.any?
46 @options_by_custom_field[field] = values
46 @options_by_custom_field[field] = values
47 end
47 end
48 end
48 end
49 end
49 end
50
50
51 render :layout => false
51 render :layout => false
52 end
52 end
53
53
54 def time_entries
54 def time_entries
55 @time_entries = TimeEntry.all(
55 @time_entries = TimeEntry.all(
56 :conditions => {:id => params[:ids]}, :include => :project)
56 :conditions => {:id => params[:ids]}, :include => :project)
57 @projects = @time_entries.collect(&:project).compact.uniq
57 @projects = @time_entries.collect(&:project).compact.uniq
58 @project = @projects.first if @projects.size == 1
58 @project = @projects.first if @projects.size == 1
59 @activities = TimeEntryActivity.shared.active
59 @activities = TimeEntryActivity.shared.active
60 @can = {:edit => User.current.allowed_to?(:edit_time_entries, @projects),
60 @can = {:edit => User.current.allowed_to?(:edit_time_entries, @projects),
61 :delete => User.current.allowed_to?(:edit_time_entries, @projects)
61 :delete => User.current.allowed_to?(:edit_time_entries, @projects)
62 }
62 }
63 @back = back_url
63 @back = back_url
64 render :layout => false
64 render :layout => false
65 end
65 end
66 end
66 end
@@ -1,428 +1,428
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class IssuesController < ApplicationController
18 class IssuesController < ApplicationController
19 menu_item :new_issue, :only => [:new, :create]
19 menu_item :new_issue, :only => [:new, :create]
20 default_search_scope :issues
20 default_search_scope :issues
21
21
22 before_filter :find_issue, :only => [:show, :edit, :update]
22 before_filter :find_issue, :only => [:show, :edit, :update]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy]
24 before_filter :check_project_uniqueness, :only => [:move, :perform_move]
24 before_filter :check_project_uniqueness, :only => [:move, :perform_move]
25 before_filter :find_project, :only => [:new, :create]
25 before_filter :find_project, :only => [:new, :create]
26 before_filter :authorize, :except => [:index]
26 before_filter :authorize, :except => [:index]
27 before_filter :find_optional_project, :only => [:index]
27 before_filter :find_optional_project, :only => [:index]
28 before_filter :check_for_default_issue_status, :only => [:new, :create]
28 before_filter :check_for_default_issue_status, :only => [:new, :create]
29 before_filter :build_new_issue_from_params, :only => [:new, :create]
29 before_filter :build_new_issue_from_params, :only => [:new, :create]
30 accept_rss_auth :index, :show
30 accept_rss_auth :index, :show
31 accept_api_auth :index, :show, :create, :update, :destroy
31 accept_api_auth :index, :show, :create, :update, :destroy
32
32
33 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
33 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
34
34
35 helper :journals
35 helper :journals
36 helper :projects
36 helper :projects
37 include ProjectsHelper
37 include ProjectsHelper
38 helper :custom_fields
38 helper :custom_fields
39 include CustomFieldsHelper
39 include CustomFieldsHelper
40 helper :issue_relations
40 helper :issue_relations
41 include IssueRelationsHelper
41 include IssueRelationsHelper
42 helper :watchers
42 helper :watchers
43 include WatchersHelper
43 include WatchersHelper
44 helper :attachments
44 helper :attachments
45 include AttachmentsHelper
45 include AttachmentsHelper
46 helper :queries
46 helper :queries
47 include QueriesHelper
47 include QueriesHelper
48 helper :repositories
48 helper :repositories
49 include RepositoriesHelper
49 include RepositoriesHelper
50 helper :sort
50 helper :sort
51 include SortHelper
51 include SortHelper
52 include IssuesHelper
52 include IssuesHelper
53 helper :timelog
53 helper :timelog
54 helper :gantt
54 helper :gantt
55 include Redmine::Export::PDF
55 include Redmine::Export::PDF
56
56
57 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
57 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
58 verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
58 verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
59 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
59 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
60
60
61 def index
61 def index
62 retrieve_query
62 retrieve_query
63 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
63 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
64 sort_update(@query.sortable_columns)
64 sort_update(@query.sortable_columns)
65
65
66 if @query.valid?
66 if @query.valid?
67 case params[:format]
67 case params[:format]
68 when 'csv', 'pdf'
68 when 'csv', 'pdf'
69 @limit = Setting.issues_export_limit.to_i
69 @limit = Setting.issues_export_limit.to_i
70 when 'atom'
70 when 'atom'
71 @limit = Setting.feeds_limit.to_i
71 @limit = Setting.feeds_limit.to_i
72 when 'xml', 'json'
72 when 'xml', 'json'
73 @offset, @limit = api_offset_and_limit
73 @offset, @limit = api_offset_and_limit
74 else
74 else
75 @limit = per_page_option
75 @limit = per_page_option
76 end
76 end
77
77
78 @issue_count = @query.issue_count
78 @issue_count = @query.issue_count
79 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
79 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
80 @offset ||= @issue_pages.current.offset
80 @offset ||= @issue_pages.current.offset
81 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
81 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
82 :order => sort_clause,
82 :order => sort_clause,
83 :offset => @offset,
83 :offset => @offset,
84 :limit => @limit)
84 :limit => @limit)
85 @issue_count_by_group = @query.issue_count_by_group
85 @issue_count_by_group = @query.issue_count_by_group
86
86
87 respond_to do |format|
87 respond_to do |format|
88 format.html { render :template => 'issues/index', :layout => !request.xhr? }
88 format.html { render :template => 'issues/index', :layout => !request.xhr? }
89 format.api {
89 format.api {
90 Issue.load_relations(@issues) if include_in_api_response?('relations')
90 Issue.load_relations(@issues) if include_in_api_response?('relations')
91 }
91 }
92 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
92 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
93 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
93 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
94 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
94 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
95 end
95 end
96 else
96 else
97 respond_to do |format|
97 respond_to do |format|
98 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
98 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
99 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
99 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
100 format.api { render_validation_errors(@query) }
100 format.api { render_validation_errors(@query) }
101 end
101 end
102 end
102 end
103 rescue ActiveRecord::RecordNotFound
103 rescue ActiveRecord::RecordNotFound
104 render_404
104 render_404
105 end
105 end
106
106
107 def show
107 def show
108 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
108 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
109 @journals.each_with_index {|j,i| j.indice = i+1}
109 @journals.each_with_index {|j,i| j.indice = i+1}
110 @journals.reverse! if User.current.wants_comments_in_reverse_order?
110 @journals.reverse! if User.current.wants_comments_in_reverse_order?
111
111
112 @changesets = @issue.changesets.visible.all
112 @changesets = @issue.changesets.visible.all
113 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
113 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
114
114
115 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
115 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
116 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
116 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
117 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
117 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
118 @priorities = IssuePriority.active
118 @priorities = IssuePriority.active
119 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
119 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
120 respond_to do |format|
120 respond_to do |format|
121 format.html {
121 format.html {
122 retrieve_previous_and_next_issue_ids
122 retrieve_previous_and_next_issue_ids
123 render :template => 'issues/show'
123 render :template => 'issues/show'
124 }
124 }
125 format.api
125 format.api
126 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
126 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
127 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
127 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
128 end
128 end
129 end
129 end
130
130
131 # Add a new issue
131 # Add a new issue
132 # The new issue will be created from an existing one if copy_from parameter is given
132 # The new issue will be created from an existing one if copy_from parameter is given
133 def new
133 def new
134 respond_to do |format|
134 respond_to do |format|
135 format.html { render :action => 'new', :layout => !request.xhr? }
135 format.html { render :action => 'new', :layout => !request.xhr? }
136 format.js {
136 format.js {
137 render(:update) { |page|
137 render(:update) { |page|
138 if params[:project_change]
138 if params[:project_change]
139 page.replace_html 'all_attributes', :partial => 'form'
139 page.replace_html 'all_attributes', :partial => 'form'
140 else
140 else
141 page.replace_html 'attributes', :partial => 'attributes'
141 page.replace_html 'attributes', :partial => 'attributes'
142 end
142 end
143 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
143 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
144 page << "if ($('log_time')) {Element.#{m}('log_time');}"
144 page << "if ($('log_time')) {Element.#{m}('log_time');}"
145 }
145 }
146 }
146 }
147 end
147 end
148 end
148 end
149
149
150 def create
150 def create
151 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
151 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
152 if @issue.save
152 if @issue.save
153 attachments = Attachment.attach_files(@issue, params[:attachments])
153 attachments = Attachment.attach_files(@issue, params[:attachments])
154 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
154 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
155 respond_to do |format|
155 respond_to do |format|
156 format.html {
156 format.html {
157 render_attachment_warning_if_needed(@issue)
157 render_attachment_warning_if_needed(@issue)
158 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
158 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
159 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
159 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
160 { :action => 'show', :id => @issue })
160 { :action => 'show', :id => @issue })
161 }
161 }
162 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
162 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
163 end
163 end
164 return
164 return
165 else
165 else
166 respond_to do |format|
166 respond_to do |format|
167 format.html { render :action => 'new' }
167 format.html { render :action => 'new' }
168 format.api { render_validation_errors(@issue) }
168 format.api { render_validation_errors(@issue) }
169 end
169 end
170 end
170 end
171 end
171 end
172
172
173 def edit
173 def edit
174 return unless update_issue_from_params
174 return unless update_issue_from_params
175
175
176 respond_to do |format|
176 respond_to do |format|
177 format.html { }
177 format.html { }
178 format.xml { }
178 format.xml { }
179 end
179 end
180 end
180 end
181
181
182 def update
182 def update
183 return unless update_issue_from_params
183 return unless update_issue_from_params
184 saved = false
184 saved = false
185 begin
185 begin
186 saved = @issue.save_issue_with_child_records(params, @time_entry)
186 saved = @issue.save_issue_with_child_records(params, @time_entry)
187 rescue ActiveRecord::StaleObjectError
187 rescue ActiveRecord::StaleObjectError
188 @conflict = true
188 @conflict = true
189 if params[:last_journal_id]
189 if params[:last_journal_id]
190 if params[:last_journal_id].present?
190 if params[:last_journal_id].present?
191 last_journal_id = params[:last_journal_id].to_i
191 last_journal_id = params[:last_journal_id].to_i
192 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
192 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
193 else
193 else
194 @conflict_journals = @issue.journals.all
194 @conflict_journals = @issue.journals.all
195 end
195 end
196 end
196 end
197 end
197 end
198
198
199 if saved
199 if saved
200 render_attachment_warning_if_needed(@issue)
200 render_attachment_warning_if_needed(@issue)
201 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
201 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
202
202
203 respond_to do |format|
203 respond_to do |format|
204 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
204 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
205 format.api { head :ok }
205 format.api { head :ok }
206 end
206 end
207 else
207 else
208 respond_to do |format|
208 respond_to do |format|
209 format.html { render :action => 'edit' }
209 format.html { render :action => 'edit' }
210 format.api { render_validation_errors(@issue) }
210 format.api { render_validation_errors(@issue) }
211 end
211 end
212 end
212 end
213 end
213 end
214
214
215 # Bulk edit/copy a set of issues
215 # Bulk edit/copy a set of issues
216 def bulk_edit
216 def bulk_edit
217 @issues.sort!
217 @issues.sort!
218 @copy = params[:copy].present?
218 @copy = params[:copy].present?
219 @notes = params[:notes]
219 @notes = params[:notes]
220
220
221 if User.current.allowed_to?(:move_issues, @projects)
221 if User.current.allowed_to?(:move_issues, @projects)
222 @allowed_projects = Issue.allowed_target_projects_on_move
222 @allowed_projects = Issue.allowed_target_projects_on_move
223 if params[:issue]
223 if params[:issue]
224 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id]}
224 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id]}
225 if @target_project
225 if @target_project
226 target_projects = [@target_project]
226 target_projects = [@target_project]
227 end
227 end
228 end
228 end
229 end
229 end
230 target_projects ||= @projects
230 target_projects ||= @projects
231
231
232 @available_statuses = target_projects.map{|p|Workflow.available_statuses(p)}.inject{|memo,w|memo & w}
232 @available_statuses = target_projects.map{|p|Workflow.available_statuses(p)}.reduce(:&)
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.inject{|memo,c|memo & c}
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
234 @assignables = target_projects.map(&:assignable_users).inject{|memo,a| memo & a}
234 @assignables = target_projects.map(&:assignable_users).reduce(:&)
235 @trackers = target_projects.map(&:trackers).inject{|memo,t| memo & t}
235 @trackers = target_projects.map(&:trackers).reduce(:&)
236
236
237 @safe_attributes = @issues.map(&:safe_attribute_names).inject {|memo,attrs| memo & attrs}
237 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
238 render :layout => false if request.xhr?
238 render :layout => false if request.xhr?
239 end
239 end
240
240
241 def bulk_update
241 def bulk_update
242 @issues.sort!
242 @issues.sort!
243 @copy = params[:copy].present?
243 @copy = params[:copy].present?
244 attributes = parse_params_for_bulk_issue_attributes(params)
244 attributes = parse_params_for_bulk_issue_attributes(params)
245
245
246 unsaved_issue_ids = []
246 unsaved_issue_ids = []
247 moved_issues = []
247 moved_issues = []
248 @issues.each do |issue|
248 @issues.each do |issue|
249 issue.reload
249 issue.reload
250 if @copy
250 if @copy
251 issue = issue.copy
251 issue = issue.copy
252 end
252 end
253 journal = issue.init_journal(User.current, params[:notes])
253 journal = issue.init_journal(User.current, params[:notes])
254 issue.safe_attributes = attributes
254 issue.safe_attributes = attributes
255 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
255 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
256 if issue.save
256 if issue.save
257 moved_issues << issue
257 moved_issues << issue
258 else
258 else
259 # Keep unsaved issue ids to display them in flash error
259 # Keep unsaved issue ids to display them in flash error
260 unsaved_issue_ids << issue.id
260 unsaved_issue_ids << issue.id
261 end
261 end
262 end
262 end
263 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
263 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
264
264
265 if params[:follow]
265 if params[:follow]
266 if @issues.size == 1 && moved_issues.size == 1
266 if @issues.size == 1 && moved_issues.size == 1
267 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
267 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
268 elsif moved_issues.map(&:project).uniq.size == 1
268 elsif moved_issues.map(&:project).uniq.size == 1
269 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
269 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
270 end
270 end
271 else
271 else
272 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
272 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
273 end
273 end
274 end
274 end
275
275
276 verify :method => :delete, :only => :destroy, :render => { :nothing => true, :status => :method_not_allowed }
276 verify :method => :delete, :only => :destroy, :render => { :nothing => true, :status => :method_not_allowed }
277 def destroy
277 def destroy
278 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
278 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
279 if @hours > 0
279 if @hours > 0
280 case params[:todo]
280 case params[:todo]
281 when 'destroy'
281 when 'destroy'
282 # nothing to do
282 # nothing to do
283 when 'nullify'
283 when 'nullify'
284 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
284 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
285 when 'reassign'
285 when 'reassign'
286 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
286 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
287 if reassign_to.nil?
287 if reassign_to.nil?
288 flash.now[:error] = l(:error_issue_not_found_in_project)
288 flash.now[:error] = l(:error_issue_not_found_in_project)
289 return
289 return
290 else
290 else
291 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
291 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
292 end
292 end
293 else
293 else
294 # display the destroy form if it's a user request
294 # display the destroy form if it's a user request
295 return unless api_request?
295 return unless api_request?
296 end
296 end
297 end
297 end
298 @issues.each do |issue|
298 @issues.each do |issue|
299 begin
299 begin
300 issue.reload.destroy
300 issue.reload.destroy
301 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
301 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
302 # nothing to do, issue was already deleted (eg. by a parent)
302 # nothing to do, issue was already deleted (eg. by a parent)
303 end
303 end
304 end
304 end
305 respond_to do |format|
305 respond_to do |format|
306 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
306 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
307 format.api { head :ok }
307 format.api { head :ok }
308 end
308 end
309 end
309 end
310
310
311 private
311 private
312 def find_issue
312 def find_issue
313 # Issue.visible.find(...) can not be used to redirect user to the login form
313 # Issue.visible.find(...) can not be used to redirect user to the login form
314 # if the issue actually exists but requires authentication
314 # if the issue actually exists but requires authentication
315 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
315 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
316 unless @issue.visible?
316 unless @issue.visible?
317 deny_access
317 deny_access
318 return
318 return
319 end
319 end
320 @project = @issue.project
320 @project = @issue.project
321 rescue ActiveRecord::RecordNotFound
321 rescue ActiveRecord::RecordNotFound
322 render_404
322 render_404
323 end
323 end
324
324
325 def find_project
325 def find_project
326 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
326 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
327 @project = Project.find(project_id)
327 @project = Project.find(project_id)
328 rescue ActiveRecord::RecordNotFound
328 rescue ActiveRecord::RecordNotFound
329 render_404
329 render_404
330 end
330 end
331
331
332 def retrieve_previous_and_next_issue_ids
332 def retrieve_previous_and_next_issue_ids
333 retrieve_query_from_session
333 retrieve_query_from_session
334 if @query
334 if @query
335 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
335 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
336 sort_update(@query.sortable_columns, 'issues_index_sort')
336 sort_update(@query.sortable_columns, 'issues_index_sort')
337 limit = 500
337 limit = 500
338 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
338 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
339 if (idx = issue_ids.index(@issue.id)) && idx < limit
339 if (idx = issue_ids.index(@issue.id)) && idx < limit
340 if issue_ids.size < 500
340 if issue_ids.size < 500
341 @issue_position = idx + 1
341 @issue_position = idx + 1
342 @issue_count = issue_ids.size
342 @issue_count = issue_ids.size
343 end
343 end
344 @prev_issue_id = issue_ids[idx - 1] if idx > 0
344 @prev_issue_id = issue_ids[idx - 1] if idx > 0
345 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
345 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
346 end
346 end
347 end
347 end
348 end
348 end
349
349
350 # Used by #edit and #update to set some common instance variables
350 # Used by #edit and #update to set some common instance variables
351 # from the params
351 # from the params
352 # TODO: Refactor, not everything in here is needed by #edit
352 # TODO: Refactor, not everything in here is needed by #edit
353 def update_issue_from_params
353 def update_issue_from_params
354 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
354 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
355 @priorities = IssuePriority.active
355 @priorities = IssuePriority.active
356 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
356 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
357 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
357 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
358 @time_entry.attributes = params[:time_entry]
358 @time_entry.attributes = params[:time_entry]
359
359
360 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
360 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
361 @issue.init_journal(User.current, @notes)
361 @issue.init_journal(User.current, @notes)
362
362
363 issue_attributes = params[:issue]
363 issue_attributes = params[:issue]
364 if issue_attributes && params[:conflict_resolution]
364 if issue_attributes && params[:conflict_resolution]
365 case params[:conflict_resolution]
365 case params[:conflict_resolution]
366 when 'overwrite'
366 when 'overwrite'
367 issue_attributes = issue_attributes.dup
367 issue_attributes = issue_attributes.dup
368 issue_attributes.delete(:lock_version)
368 issue_attributes.delete(:lock_version)
369 when 'add_notes'
369 when 'add_notes'
370 issue_attributes = {}
370 issue_attributes = {}
371 when 'cancel'
371 when 'cancel'
372 redirect_to issue_path(@issue)
372 redirect_to issue_path(@issue)
373 return false
373 return false
374 end
374 end
375 end
375 end
376 @issue.safe_attributes = issue_attributes
376 @issue.safe_attributes = issue_attributes
377 true
377 true
378 end
378 end
379
379
380 # TODO: Refactor, lots of extra code in here
380 # TODO: Refactor, lots of extra code in here
381 # TODO: Changing tracker on an existing issue should not trigger this
381 # TODO: Changing tracker on an existing issue should not trigger this
382 def build_new_issue_from_params
382 def build_new_issue_from_params
383 if params[:id].blank?
383 if params[:id].blank?
384 @issue = Issue.new
384 @issue = Issue.new
385 if params[:copy_from]
385 if params[:copy_from]
386 begin
386 begin
387 @copy_from = Issue.visible.find(params[:copy_from])
387 @copy_from = Issue.visible.find(params[:copy_from])
388 @copy_attachments = params[:copy_attachments].present? || request.get?
388 @copy_attachments = params[:copy_attachments].present? || request.get?
389 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
389 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
390 rescue ActiveRecord::RecordNotFound
390 rescue ActiveRecord::RecordNotFound
391 render_404
391 render_404
392 return
392 return
393 end
393 end
394 end
394 end
395 @issue.project = @project
395 @issue.project = @project
396 else
396 else
397 @issue = @project.issues.visible.find(params[:id])
397 @issue = @project.issues.visible.find(params[:id])
398 end
398 end
399
399
400 @issue.project = @project
400 @issue.project = @project
401 @issue.author = User.current
401 @issue.author = User.current
402 # Tracker must be set before custom field values
402 # Tracker must be set before custom field values
403 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
403 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
404 if @issue.tracker.nil?
404 if @issue.tracker.nil?
405 render_error l(:error_no_tracker_in_project)
405 render_error l(:error_no_tracker_in_project)
406 return false
406 return false
407 end
407 end
408 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
408 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
409 @issue.safe_attributes = params[:issue]
409 @issue.safe_attributes = params[:issue]
410
410
411 @priorities = IssuePriority.active
411 @priorities = IssuePriority.active
412 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
412 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
413 end
413 end
414
414
415 def check_for_default_issue_status
415 def check_for_default_issue_status
416 if IssueStatus.default.nil?
416 if IssueStatus.default.nil?
417 render_error l(:error_no_default_issue_status)
417 render_error l(:error_no_default_issue_status)
418 return false
418 return false
419 end
419 end
420 end
420 end
421
421
422 def parse_params_for_bulk_issue_attributes(params)
422 def parse_params_for_bulk_issue_attributes(params)
423 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
423 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
424 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
424 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
425 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
425 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
426 attributes
426 attributes
427 end
427 end
428 end
428 end
@@ -1,221 +1,221
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class CustomField < ActiveRecord::Base
18 class CustomField < ActiveRecord::Base
19 include Redmine::SubclassFactory
19 include Redmine::SubclassFactory
20
20
21 has_many :custom_values, :dependent => :delete_all
21 has_many :custom_values, :dependent => :delete_all
22 acts_as_list :scope => 'type = \'#{self.class}\''
22 acts_as_list :scope => 'type = \'#{self.class}\''
23 serialize :possible_values
23 serialize :possible_values
24
24
25 validates_presence_of :name, :field_format
25 validates_presence_of :name, :field_format
26 validates_uniqueness_of :name, :scope => :type
26 validates_uniqueness_of :name, :scope => :type
27 validates_length_of :name, :maximum => 30
27 validates_length_of :name, :maximum => 30
28 validates_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats
28 validates_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats
29
29
30 validate :validate_custom_field
30 validate :validate_custom_field
31 before_validation :set_searchable
31 before_validation :set_searchable
32
32
33 def initialize(attributes=nil, *args)
33 def initialize(attributes=nil, *args)
34 super
34 super
35 self.possible_values ||= []
35 self.possible_values ||= []
36 end
36 end
37
37
38 def set_searchable
38 def set_searchable
39 # make sure these fields are not searchable
39 # make sure these fields are not searchable
40 self.searchable = false if %w(int float date bool).include?(field_format)
40 self.searchable = false if %w(int float date bool).include?(field_format)
41 # make sure only these fields can have multiple values
41 # make sure only these fields can have multiple values
42 self.multiple = false unless %w(list user version).include?(field_format)
42 self.multiple = false unless %w(list user version).include?(field_format)
43 true
43 true
44 end
44 end
45
45
46 def validate_custom_field
46 def validate_custom_field
47 if self.field_format == "list"
47 if self.field_format == "list"
48 errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty?
48 errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty?
49 errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array
49 errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array
50 end
50 end
51
51
52 if regexp.present?
52 if regexp.present?
53 begin
53 begin
54 Regexp.new(regexp)
54 Regexp.new(regexp)
55 rescue
55 rescue
56 errors.add(:regexp, :invalid)
56 errors.add(:regexp, :invalid)
57 end
57 end
58 end
58 end
59
59
60 if default_value.present? && !valid_field_value?(default_value)
60 if default_value.present? && !valid_field_value?(default_value)
61 errors.add(:default_value, :invalid)
61 errors.add(:default_value, :invalid)
62 end
62 end
63 end
63 end
64
64
65 def possible_values_options(obj=nil)
65 def possible_values_options(obj=nil)
66 case field_format
66 case field_format
67 when 'user', 'version'
67 when 'user', 'version'
68 if obj.respond_to?(:project) && obj.project
68 if obj.respond_to?(:project) && obj.project
69 case field_format
69 case field_format
70 when 'user'
70 when 'user'
71 obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]}
71 obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]}
72 when 'version'
72 when 'version'
73 obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]}
73 obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]}
74 end
74 end
75 elsif obj.is_a?(Array)
75 elsif obj.is_a?(Array)
76 obj.collect {|o| possible_values_options(o)}.inject {|memo, v| memo & v}
76 obj.collect {|o| possible_values_options(o)}.reduce(:&)
77 else
77 else
78 []
78 []
79 end
79 end
80 when 'bool'
80 when 'bool'
81 [[l(:general_text_Yes), '1'], [l(:general_text_No), '0']]
81 [[l(:general_text_Yes), '1'], [l(:general_text_No), '0']]
82 else
82 else
83 read_attribute(:possible_values) || []
83 read_attribute(:possible_values) || []
84 end
84 end
85 end
85 end
86
86
87 def possible_values(obj=nil)
87 def possible_values(obj=nil)
88 case field_format
88 case field_format
89 when 'user', 'version'
89 when 'user', 'version'
90 possible_values_options(obj).collect(&:last)
90 possible_values_options(obj).collect(&:last)
91 when 'bool'
91 when 'bool'
92 ['1', '0']
92 ['1', '0']
93 else
93 else
94 read_attribute :possible_values
94 read_attribute :possible_values
95 end
95 end
96 end
96 end
97
97
98 # Makes possible_values accept a multiline string
98 # Makes possible_values accept a multiline string
99 def possible_values=(arg)
99 def possible_values=(arg)
100 if arg.is_a?(Array)
100 if arg.is_a?(Array)
101 write_attribute(:possible_values, arg.compact.collect(&:strip).select {|v| !v.blank?})
101 write_attribute(:possible_values, arg.compact.collect(&:strip).select {|v| !v.blank?})
102 else
102 else
103 self.possible_values = arg.to_s.split(/[\n\r]+/)
103 self.possible_values = arg.to_s.split(/[\n\r]+/)
104 end
104 end
105 end
105 end
106
106
107 def cast_value(value)
107 def cast_value(value)
108 casted = nil
108 casted = nil
109 unless value.blank?
109 unless value.blank?
110 case field_format
110 case field_format
111 when 'string', 'text', 'list'
111 when 'string', 'text', 'list'
112 casted = value
112 casted = value
113 when 'date'
113 when 'date'
114 casted = begin; value.to_date; rescue; nil end
114 casted = begin; value.to_date; rescue; nil end
115 when 'bool'
115 when 'bool'
116 casted = (value == '1' ? true : false)
116 casted = (value == '1' ? true : false)
117 when 'int'
117 when 'int'
118 casted = value.to_i
118 casted = value.to_i
119 when 'float'
119 when 'float'
120 casted = value.to_f
120 casted = value.to_f
121 when 'user', 'version'
121 when 'user', 'version'
122 casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i))
122 casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i))
123 end
123 end
124 end
124 end
125 casted
125 casted
126 end
126 end
127
127
128 # Returns a ORDER BY clause that can used to sort customized
128 # Returns a ORDER BY clause that can used to sort customized
129 # objects by their value of the custom field.
129 # objects by their value of the custom field.
130 # Returns false, if the custom field can not be used for sorting.
130 # Returns false, if the custom field can not be used for sorting.
131 def order_statement
131 def order_statement
132 return nil if multiple?
132 return nil if multiple?
133 case field_format
133 case field_format
134 when 'string', 'text', 'list', 'date', 'bool'
134 when 'string', 'text', 'list', 'date', 'bool'
135 # COALESCE is here to make sure that blank and NULL values are sorted equally
135 # COALESCE is here to make sure that blank and NULL values are sorted equally
136 "COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
136 "COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
137 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
137 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
138 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
138 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
139 " AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
139 " AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
140 when 'int', 'float'
140 when 'int', 'float'
141 # Make the database cast values into numeric
141 # Make the database cast values into numeric
142 # Postgresql will raise an error if a value can not be casted!
142 # Postgresql will raise an error if a value can not be casted!
143 # CustomValue validations should ensure that it doesn't occur
143 # CustomValue validations should ensure that it doesn't occur
144 "(SELECT CAST(cv_sort.value AS decimal(60,3)) FROM #{CustomValue.table_name} cv_sort" +
144 "(SELECT CAST(cv_sort.value AS decimal(60,3)) FROM #{CustomValue.table_name} cv_sort" +
145 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
145 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
146 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
146 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
147 " AND cv_sort.custom_field_id=#{id} AND cv_sort.value <> '' AND cv_sort.value IS NOT NULL LIMIT 1)"
147 " AND cv_sort.custom_field_id=#{id} AND cv_sort.value <> '' AND cv_sort.value IS NOT NULL LIMIT 1)"
148 else
148 else
149 nil
149 nil
150 end
150 end
151 end
151 end
152
152
153 def <=>(field)
153 def <=>(field)
154 position <=> field.position
154 position <=> field.position
155 end
155 end
156
156
157 def self.customized_class
157 def self.customized_class
158 self.name =~ /^(.+)CustomField$/
158 self.name =~ /^(.+)CustomField$/
159 begin; $1.constantize; rescue nil; end
159 begin; $1.constantize; rescue nil; end
160 end
160 end
161
161
162 # to move in project_custom_field
162 # to move in project_custom_field
163 def self.for_all
163 def self.for_all
164 find(:all, :conditions => ["is_for_all=?", true], :order => 'position')
164 find(:all, :conditions => ["is_for_all=?", true], :order => 'position')
165 end
165 end
166
166
167 def type_name
167 def type_name
168 nil
168 nil
169 end
169 end
170
170
171 # Returns the error messages for the given value
171 # Returns the error messages for the given value
172 # or an empty array if value is a valid value for the custom field
172 # or an empty array if value is a valid value for the custom field
173 def validate_field_value(value)
173 def validate_field_value(value)
174 errs = []
174 errs = []
175 if value.is_a?(Array)
175 if value.is_a?(Array)
176 if !multiple?
176 if !multiple?
177 errs << ::I18n.t('activerecord.errors.messages.invalid')
177 errs << ::I18n.t('activerecord.errors.messages.invalid')
178 end
178 end
179 if is_required? && value.detect(&:present?).nil?
179 if is_required? && value.detect(&:present?).nil?
180 errs << ::I18n.t('activerecord.errors.messages.blank')
180 errs << ::I18n.t('activerecord.errors.messages.blank')
181 end
181 end
182 value.each {|v| errs += validate_field_value_format(v)}
182 value.each {|v| errs += validate_field_value_format(v)}
183 else
183 else
184 if is_required? && value.blank?
184 if is_required? && value.blank?
185 errs << ::I18n.t('activerecord.errors.messages.blank')
185 errs << ::I18n.t('activerecord.errors.messages.blank')
186 end
186 end
187 errs += validate_field_value_format(value)
187 errs += validate_field_value_format(value)
188 end
188 end
189 errs
189 errs
190 end
190 end
191
191
192 # Returns true if value is a valid value for the custom field
192 # Returns true if value is a valid value for the custom field
193 def valid_field_value?(value)
193 def valid_field_value?(value)
194 validate_field_value(value).empty?
194 validate_field_value(value).empty?
195 end
195 end
196
196
197 protected
197 protected
198
198
199 # Returns the error message for the given value regarding its format
199 # Returns the error message for the given value regarding its format
200 def validate_field_value_format(value)
200 def validate_field_value_format(value)
201 errs = []
201 errs = []
202 if value.present?
202 if value.present?
203 errs << ::I18n.t('activerecord.errors.messages.invalid') unless regexp.blank? or value =~ Regexp.new(regexp)
203 errs << ::I18n.t('activerecord.errors.messages.invalid') unless regexp.blank? or value =~ Regexp.new(regexp)
204 errs << ::I18n.t('activerecord.errors.messages.too_short', :count => min_length) if min_length > 0 and value.length < min_length
204 errs << ::I18n.t('activerecord.errors.messages.too_short', :count => min_length) if min_length > 0 and value.length < min_length
205 errs << ::I18n.t('activerecord.errors.messages.too_long', :count => max_length) if max_length > 0 and value.length > max_length
205 errs << ::I18n.t('activerecord.errors.messages.too_long', :count => max_length) if max_length > 0 and value.length > max_length
206
206
207 # Format specific validations
207 # Format specific validations
208 case field_format
208 case field_format
209 when 'int'
209 when 'int'
210 errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/
210 errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/
211 when 'float'
211 when 'float'
212 begin; Kernel.Float(value); rescue; errs << ::I18n.t('activerecord.errors.messages.invalid') end
212 begin; Kernel.Float(value); rescue; errs << ::I18n.t('activerecord.errors.messages.invalid') end
213 when 'date'
213 when 'date'
214 errs << ::I18n.t('activerecord.errors.messages.not_a_date') unless value =~ /^\d{4}-\d{2}-\d{2}$/ && begin; value.to_date; rescue; false end
214 errs << ::I18n.t('activerecord.errors.messages.not_a_date') unless value =~ /^\d{4}-\d{2}-\d{2}$/ && begin; value.to_date; rescue; false end
215 when 'list'
215 when 'list'
216 errs << ::I18n.t('activerecord.errors.messages.inclusion') unless possible_values.include?(value)
216 errs << ::I18n.t('activerecord.errors.messages.inclusion') unless possible_values.include?(value)
217 end
217 end
218 end
218 end
219 errs
219 errs
220 end
220 end
221 end
221 end
General Comments 0
You need to be logged in to leave comments. Login now