APIv4 - Add Address::getCoordinates action
[civicrm-core.git] / CRM / Campaign / Form / Campaign.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
ce064e4f 19 * This class generates form components for processing a campaign.
6a488035
TO
20 */
21class CRM_Campaign_Form_Campaign extends CRM_Core_Form {
22
23 /**
100fef9d 24 * Action
6a488035
TO
25 *
26 * @var int
27 */
3a936dab 28 public $_action;
6a488035
TO
29
30 /**
100fef9d 31 * Context
6a488035
TO
32 *
33 * @var string
34 */
35 protected $_context;
36
37 /**
100fef9d 38 * Object values.
6a488035
TO
39 *
40 * @var array
41 */
42 protected $_values;
43
44 /**
100fef9d 45 * The id of the campaign we are proceessing
6a488035
TO
46 *
47 * @var int
6a488035
TO
48 */
49 protected $_campaignId;
d5965a37 50
6e62b28c
TM
51 /**
52 * Explicitly declare the entity api name.
53 */
54 public function getDefaultEntity() {
55 return 'Campaign';
56 }
6a488035
TO
57
58 public function preProcess() {
59 if (!CRM_Campaign_BAO_Campaign::accessCampaign()) {
60 CRM_Utils_System::permissionDenied();
61 }
62
edc80cda 63 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
6a488035
TO
64
65 $this->assign('context', $this->_context);
66
67 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);
484627ca 68 $this->_campaignId = CRM_Utils_Request::retrieve('id', 'Positive');
6a488035
TO
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) {
483cfbc4 78 $this->setTitle($title);
6a488035
TO
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)) {
be2fb01f 88 $this->_values = [];
6a488035
TO
89
90 // if we are editing
91 if (isset($this->_campaignId) && $this->_campaignId) {
be2fb01f 92 $params = ['id' => $this->_campaignId];
6a488035
TO
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.
a7488080 101 if (!empty($_POST['hidden_custom'])) {
c5366541 102 $campaignTypeId = empty($_POST['campaign_type_id']) ? NULL : $_POST['campaign_type_id'];
6a488035 103 $this->set('type', 'Campaign');
c5366541 104 $this->set('subType', $campaignTypeId);
6a488035
TO
105 $this->set('entityId', $this->_campaignId);
106
c5366541 107 CRM_Custom_Form_CustomData::preProcess($this, NULL, $campaignTypeId, 1, 'Campaign', $this->_campaignId);
6a488035
TO
108 CRM_Custom_Form_CustomData::buildQuickForm($this);
109 CRM_Custom_Form_CustomData::setDefaultValues($this);
110 }
111 }
112
113 /**
c490a46a 114 * Set default values for the form. Note that in edit/view mode
6a488035
TO
115 * the default values are retrieved from the database
116 *
6a488035 117 *
2221b3e3 118 * @return array
6a488035 119 */
00be9182 120 public function setDefaultValues() {
6a488035
TO
121 $defaults = $this->_values;
122
c38a7f6b
CW
123 if (empty($defaults['start_date'])) {
124 $defaults['start_date'] = date('Y-m-d H:i:s');
6a488035
TO
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
be2fb01f 137 $campaignGroups = [];
6a488035
TO
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() {
1107b319 152 $this->add('hidden', 'id', $this->_campaignId);
6a488035
TO
153 if ($this->_action & CRM_Core_Action::DELETE) {
154
be2fb01f 155 $this->addButtons([
5d4fcf54
TO
156 [
157 'type' => 'next',
158 'name' => ts('Delete'),
159 'isDefault' => TRUE,
160 ],
161 [
162 'type' => 'cancel',
163 'name' => ts('Cancel'),
164 ],
165 ]);
6a488035
TO
166 return;
167 }
168
169 $this->applyFilter('__ALL__', 'trim');
170
6a488035
TO
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
c38a7f6b 185 $this->add('datepicker', 'start_date', ts('Start Date'), [], TRUE);
6a488035
TO
186
187 // add campaign end date
c38a7f6b 188 $this->add('datepicker', 'end_date', ts('End Date'));
6a488035
TO
189
190 // add campaign type
37324be5 191 $this->addSelect('campaign_type_id', ['placeholder' => ts('- select type -'), 'onChange' => "CRM.buildCustomData( 'Campaign', this.value );"], TRUE);
6a488035
TO
192
193 // add campaign status
37324be5 194 $this->addSelect('status_id', ['placeholder' => ts('- select status -')]);
6a488035 195
7b99ead3
CW
196 // add External Identifier Element
197 $this->add('text', 'external_identifier', ts('External ID'),
6a488035
TO
198 CRM_Core_DAO::getAttribute('CRM_Campaign_DAO_Campaign', 'external_identifier'), FALSE
199 );
200
201 // add Campaign Parent Id
2221b3e3 202 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(CRM_Utils_Array::value('parent_id', $this->_values), $this->_campaignId);
6a488035 203 if (!empty($campaigns)) {
2221b3e3 204 $this->addElement('select', 'parent_id', ts('Parent ID'),
be2fb01f
CW
205 ['' => ts('- select Parent -')] + $campaigns,
206 ['class' => 'crm-select2']
6a488035
TO
207 );
208 }
2221b3e3 209 $groups = CRM_Core_PseudoConstant::nestedGroup();
6a488035 210 //get the campaign groups.
11cac306
CW
211 $this->add('select', 'includeGroups',
212 ts('Include Group(s)'),
6a488035 213 $groups,
11cac306 214 FALSE,
be2fb01f 215 [
11cac306
CW
216 'multiple' => TRUE,
217 'class' => 'crm-select2 huge',
218 'placeholder' => ts('- none -'),
be2fb01f 219 ]
6a488035 220 );
6a488035 221
be2fb01f
CW
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]);
6a488035 224 $this->addRule('goal_revenue', ts('Please enter a valid money value (e.g. %1).',
1777ab27 225 [1 => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency(99.99)]
353ffa53 226 ), 'money');
6a488035
TO
227
228 // is this Campaign active
229 $this->addElement('checkbox', 'is_active', ts('Is Active?'));
230
8dbd6052
CW
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);
95942234
JK
252
253 $this->addFormRule(['CRM_Campaign_Form_Campaign', 'formRule']);
6a488035
TO
254 }
255
256 /**
dc195289 257 * add the rules (mainly global rules) for form.
6a488035
TO
258 * All local rules are added near the element
259 *
fd31fa4c 260 * @param $fields
fd31fa4c 261 *
2221b3e3 262 * @return bool|array
6a488035 263 */
4347c49a 264 public static function formRule($fields) {
be2fb01f 265 $errors = [];
6a488035 266
95942234
JK
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
6a488035
TO
273 return empty($errors) ? TRUE : $errors;
274 }
275
276 /**
277 * Form submission of new/edit campaign is processed.
6a488035
TO
278 */
279 public function postProcess() {
280 // store the submitted values in an array
6a488035 281
484627ca
SL
282 $session = CRM_Core_Session::singleton();
283 $params = $this->controller->exportValues($this->_name);
1107b319
SL
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'])) {
6a488035 289 if ($this->_action & CRM_Core_Action::DELETE) {
1107b319 290 CRM_Campaign_BAO_Campaign::del($params['id']);
6a488035
TO
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 }
1107b319 295 $this->_campaignId = $params['id'];
6a488035
TO
296 }
297 else {
298 $params['created_id'] = $session->get('userID');
299 $params['created_date'] = date('YmdHis');
300 }
301 // format params
6a488035
TO
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');
484627ca
SL
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 }
6a488035 321
0efafdb0 322 public static function submit($params, $form) {
484627ca 323 $groups = [];
1107b319 324 if (!empty($params['includeGroups']) && is_array($params['includeGroups'])) {
6a488035
TO
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
353ffa53
TO
334 $groupTableName = CRM_Contact_BAO_Group::getTableName();
335 $dao = new CRM_Campaign_DAO_CampaignGroup();
484627ca 336 $dao->campaign_id = $form->_campaignId;
6a488035
TO
337 $dao->entity_table = $groupTableName;
338 $dao->find();
339 while ($dao->fetch()) {
340 $dao->delete();
341 }
342
343 //process custom data.
6a488035 344 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
484627ca 345 $form->_campaignId,
6a488035
TO
346 'Campaign'
347 );
1107b319 348
484627ca
SL
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;
6a488035 353 }
96025800 354
6a488035 355}