Merge pull request #23326 from civicrm/5.49
[civicrm-core.git] / CRM / Campaign / Form / Campaign.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for processing a campaign.
20 */
21 class CRM_Campaign_Form_Campaign extends CRM_Core_Form {
22
23 /**
24 * Action
25 *
26 * @var int
27 */
28 public $_action;
29
30 /**
31 * Context
32 *
33 * @var string
34 */
35 protected $_context;
36
37 /**
38 * Object values.
39 *
40 * @var array
41 */
42 protected $_values;
43
44 /**
45 * The id of the campaign we are proceessing
46 *
47 * @var int
48 */
49 protected $_campaignId;
50
51 /**
52 * Explicitly declare the entity api name.
53 */
54 public function getDefaultEntity() {
55 return 'Campaign';
56 }
57
58 public function preProcess() {
59 if (!CRM_Campaign_BAO_Campaign::accessCampaign()) {
60 CRM_Utils_System::permissionDenied();
61 }
62
63 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
64
65 $this->assign('context', $this->_context);
66
67 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);
68 $this->_campaignId = CRM_Utils_Request::retrieve('id', 'Positive');
69
70 $title = NULL;
71 if ($this->_action & CRM_Core_Action::UPDATE) {
72 $title = ts('Edit Campaign');
73 }
74 if ($this->_action & CRM_Core_Action::DELETE) {
75 $title = ts('Delete Campaign');
76 }
77 if ($title) {
78 $this->setTitle($title);
79 }
80
81 $session = CRM_Core_Session::singleton();
82 $session->pushUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=campaign'));
83 $this->assign('action', $this->_action);
84
85 //load the values;
86 $this->_values = $this->get('values');
87 if (!is_array($this->_values)) {
88 $this->_values = [];
89
90 // if we are editing
91 if (isset($this->_campaignId) && $this->_campaignId) {
92 $params = ['id' => $this->_campaignId];
93 CRM_Campaign_BAO_Campaign::retrieve($params, $this->_values);
94 }
95
96 //lets use current object session.
97 $this->set('values', $this->_values);
98 }
99
100 // when custom data is included in form.
101 if (!empty($_POST['hidden_custom'])) {
102 $campaignTypeId = empty($_POST['campaign_type_id']) ? NULL : $_POST['campaign_type_id'];
103 $this->set('type', 'Campaign');
104 $this->set('subType', $campaignTypeId);
105 $this->set('entityId', $this->_campaignId);
106
107 CRM_Custom_Form_CustomData::preProcess($this, NULL, $campaignTypeId, 1, 'Campaign', $this->_campaignId);
108 CRM_Custom_Form_CustomData::buildQuickForm($this);
109 CRM_Custom_Form_CustomData::setDefaultValues($this);
110 }
111 }
112
113 /**
114 * Set default values for the form. Note that in edit/view mode
115 * the default values are retrieved from the database
116 *
117 *
118 * @return array
119 */
120 public function setDefaultValues() {
121 $defaults = $this->_values;
122
123 if (empty($defaults['start_date'])) {
124 $defaults['start_date'] = date('Y-m-d H:i:s');
125 }
126
127 if (!isset($defaults['is_active'])) {
128 $defaults['is_active'] = 1;
129 }
130
131 if (!$this->_campaignId) {
132 return $defaults;
133 }
134
135 $dao = new CRM_Campaign_DAO_CampaignGroup();
136
137 $campaignGroups = [];
138 $dao->campaign_id = $this->_campaignId;
139 $dao->find();
140
141 while ($dao->fetch()) {
142 $campaignGroups[$dao->entity_table][$dao->group_type][] = $dao->entity_id;
143 }
144
145 if (!empty($campaignGroups)) {
146 $defaults['includeGroups'] = $campaignGroups['civicrm_group']['Include'];
147 }
148 return $defaults;
149 }
150
151 public function buildQuickForm() {
152 $this->add('hidden', 'id', $this->_campaignId);
153 if ($this->_action & CRM_Core_Action::DELETE) {
154
155 $this->addButtons([
156 [
157 'type' => 'next',
158 'name' => ts('Delete'),
159 'isDefault' => TRUE,
160 ],
161 [
162 'type' => 'cancel',
163 'name' => ts('Cancel'),
164 ],
165 ]);
166 return;
167 }
168
169 $this->applyFilter('__ALL__', 'trim');
170
171 //lets assign custom data type and subtype.
172 $this->assign('customDataType', 'Campaign');
173 $this->assign('entityID', $this->_campaignId);
174 $this->assign('customDataSubType', CRM_Utils_Array::value('campaign_type_id', $this->_values));
175
176 $attributes = CRM_Core_DAO::getAttribute('CRM_Campaign_DAO_Campaign');
177
178 // add comaign title.
179 $this->add('text', 'title', ts('Title'), $attributes['title'], TRUE);
180
181 // add description
182 $this->add('textarea', 'description', ts('Description'), $attributes['description']);
183
184 // add campaign start date
185 $this->add('datepicker', 'start_date', ts('Start Date'), [], TRUE);
186
187 // add campaign end date
188 $this->add('datepicker', 'end_date', ts('End Date'));
189
190 // add campaign type
191 $this->addSelect('campaign_type_id', ['placeholder' => ts('- select type -'), 'onChange' => "CRM.buildCustomData( 'Campaign', this.value );"], TRUE);
192
193 // add campaign status
194 $this->addSelect('status_id', ['placeholder' => ts('- select status -')]);
195
196 // add External Identifier Element
197 $this->add('text', 'external_identifier', ts('External ID'),
198 CRM_Core_DAO::getAttribute('CRM_Campaign_DAO_Campaign', 'external_identifier'), FALSE
199 );
200
201 // add Campaign Parent Id
202 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(CRM_Utils_Array::value('parent_id', $this->_values), $this->_campaignId);
203 if (!empty($campaigns)) {
204 $this->addElement('select', 'parent_id', ts('Parent ID'),
205 ['' => ts('- select Parent -')] + $campaigns,
206 ['class' => 'crm-select2']
207 );
208 }
209 $groups = CRM_Core_PseudoConstant::nestedGroup();
210 //get the campaign groups.
211 $this->add('select', 'includeGroups',
212 ts('Include Group(s)'),
213 $groups,
214 FALSE,
215 [
216 'multiple' => TRUE,
217 'class' => 'crm-select2 huge',
218 'placeholder' => ts('- none -'),
219 ]
220 );
221
222 $this->add('wysiwyg', 'goal_general', ts('Campaign Goals'), ['rows' => 2, 'cols' => 40]);
223 $this->add('text', 'goal_revenue', ts('Revenue Goal'), ['size' => 8, 'maxlength' => 12]);
224 $this->addRule('goal_revenue', ts('Please enter a valid money value (e.g. %1).',
225 [1 => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency(99.99)]
226 ), 'money');
227
228 // is this Campaign active
229 $this->addElement('checkbox', 'is_active', ts('Is Active?'));
230
231 $buttons = [
232 [
233 'type' => 'upload',
234 'name' => ts('Save'),
235 'isDefault' => TRUE,
236 ],
237 ];
238 // Skip this button when adding a new campaign from an entityRef
239 if (empty($_GET['snippet']) || empty($_GET['returnExtra'])) {
240 $buttons[] = [
241 'type' => 'upload',
242 'name' => ts('Save and New'),
243 'subName' => 'new',
244 ];
245 }
246 $buttons[] = [
247 'type' => 'cancel',
248 'name' => ts('Cancel'),
249 ];
250
251 $this->addButtons($buttons);
252
253 $this->addFormRule(['CRM_Campaign_Form_Campaign', 'formRule']);
254 }
255
256 /**
257 * add the rules (mainly global rules) for form.
258 * All local rules are added near the element
259 *
260 * @param $fields
261 *
262 * @return bool|array
263 */
264 public static function formRule($fields) {
265 $errors = [];
266
267 // Validate start/end date inputs
268 $validateDates = \CRM_Utils_Date::validateStartEndDatepickerInputs('start_date', $fields['start_date'], 'end_date', $fields['end_date']);
269 if ($validateDates !== TRUE) {
270 $errors[$validateDates['key']] = $validateDates['message'];
271 }
272
273 return empty($errors) ? TRUE : $errors;
274 }
275
276 /**
277 * Form submission of new/edit campaign is processed.
278 */
279 public function postProcess() {
280 // store the submitted values in an array
281
282 $session = CRM_Core_Session::singleton();
283 $params = $this->controller->exportValues($this->_name);
284 // To properly save the DAO we need to ensure we don't have a blank id key passed through.
285 if (empty($params['id'])) {
286 unset($params['id']);
287 }
288 if (!empty($params['id'])) {
289 if ($this->_action & CRM_Core_Action::DELETE) {
290 CRM_Campaign_BAO_Campaign::del($params['id']);
291 CRM_Core_Session::setStatus(ts('Campaign has been deleted.'), ts('Record Deleted'), 'success');
292 $session->replaceUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=campaign'));
293 return;
294 }
295 $this->_campaignId = $params['id'];
296 }
297 else {
298 $params['created_id'] = $session->get('userID');
299 $params['created_date'] = date('YmdHis');
300 }
301 // format params
302 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
303 $params['last_modified_id'] = $session->get('userID');
304 $params['last_modified_date'] = date('YmdHis');
305 $result = self::submit($params, $this);
306 if (!$result['is_error']) {
307 CRM_Core_Session::setStatus(ts('Campaign %1 has been saved.', [1 => $result['values'][$result['id']]['title']]), ts('Saved'), 'success');
308 $session->pushUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=campaign'));
309 $this->ajaxResponse['id'] = $result['id'];
310 $this->ajaxResponse['label'] = $result['values'][$result['id']]['title'];
311 }
312 $buttonName = $this->controller->getButtonName();
313 if ($buttonName == $this->getButtonName('upload', 'new')) {
314 CRM_Core_Session::setStatus(ts(' You can add another Campaign.'), '', 'info');
315 $session->replaceUserContext(CRM_Utils_System::url('civicrm/campaign/add', 'reset=1&action=add'));
316 }
317 else {
318 $session->replaceUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=campaign'));
319 }
320 }
321
322 public static function submit($params, $form) {
323 $groups = [];
324 if (!empty($params['includeGroups']) && is_array($params['includeGroups'])) {
325 foreach ($params['includeGroups'] as $key => $id) {
326 if ($id) {
327 $groups['include'][] = $id;
328 }
329 }
330 }
331 $params['groups'] = $groups;
332
333 // delete previous includes/excludes, if campaign already existed
334 $groupTableName = CRM_Contact_BAO_Group::getTableName();
335 $dao = new CRM_Campaign_DAO_CampaignGroup();
336 $dao->campaign_id = $form->_campaignId;
337 $dao->entity_table = $groupTableName;
338 $dao->find();
339 while ($dao->fetch()) {
340 $dao->delete();
341 }
342
343 //process custom data.
344 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
345 $form->_campaignId,
346 'Campaign'
347 );
348
349 // dev/core#1067 Clean Money before passing onto BAO to do the create.
350 $params['goal_revenue'] = CRM_Utils_Rule::cleanMoney($params['goal_revenue']);
351 $result = civicrm_api3('Campaign', 'create', $params);
352 return $result;
353 }
354
355 }