8d15bd9004452b0ec04858f18dc00477f7bf0121
[civicrm-core.git] / CRM / Custom / Form / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 * $Id$
33 *
34 */
35
36 /**
37 * form to process actions on the set aspect of Custom Data
38 */
39 class CRM_Custom_Form_Group extends CRM_Core_Form {
40
41 /**
42 * The set id saved to the session for an update.
43 *
44 * @var int
45 */
46 protected $_id;
47
48 /**
49 * set is empty or not.
50 *
51 * @var bool
52 */
53 protected $_isGroupEmpty = TRUE;
54
55 /**
56 * Array of existing subtypes set for a custom set.
57 *
58 * @var array
59 */
60 protected $_subtypes = array();
61
62 /**
63 * Set variables up before form is built.
64 *
65 *
66 * @return void
67 */
68 public function preProcess() {
69 // current set id
70 $this->_id = $this->get('id');
71
72 if ($this->_id && $isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_id, 'is_reserved', 'id')) {
73 CRM_Core_Error::fatal("You cannot edit the settings of a reserved custom field-set.");
74 }
75 // setting title for html page
76 if ($this->_action == CRM_Core_Action::UPDATE) {
77 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
78 CRM_Utils_System::setTitle(ts('Edit %1', array(1 => $title)));
79 }
80 elseif ($this->_action == CRM_Core_Action::VIEW) {
81 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
82 CRM_Utils_System::setTitle(ts('Preview %1', array(1 => $title)));
83 }
84 else {
85 CRM_Utils_System::setTitle(ts('New Custom Field Set'));
86 }
87
88 if (isset($this->_id)) {
89 $params = array('id' => $this->_id);
90 CRM_Core_BAO_CustomGroup::retrieve($params, $this->_defaults);
91
92 $subExtends = CRM_Utils_Array::value('extends_entity_column_value', $this->_defaults);
93 if (!empty($subExtends)) {
94 $this->_subtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subExtends, 1, -1));
95 }
96 }
97 }
98
99 /**
100 * Global form rule.
101 *
102 * @param array $fields
103 * The input form values.
104 * @param array $files
105 * The uploaded files if any.
106 * @param $self
107 *
108 *
109 * @return bool|array
110 * true if no errors, else array of errors
111 */
112 public static function formRule($fields, $files, $self) {
113 $errors = array();
114
115 //validate group title as well as name.
116 $title = $fields['title'];
117 $name = CRM_Utils_String::munge($title, '_', 64);
118 $query = 'select count(*) from civicrm_custom_group where ( name like %1) and id != %2';
119 $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
120 1 => array($name, 'String'),
121 2 => array((int) $self->_id, 'Integer'),
122 ));
123 if ($grpCnt) {
124 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
125 }
126
127 if (!empty($fields['extends'][1])) {
128 if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
129 $errors['extends'] = ts("Cannot combine other option with 'Any'.");
130 }
131 }
132
133 if (empty($fields['extends'][0])) {
134 $errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
135 }
136
137 $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
138 if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
139 $errors['style'] = ts("Display Style should be Inline for this Class");
140 $self->assign('showStyle', TRUE);
141 }
142
143 if (!empty($fields['is_multiple'])) {
144 $self->assign('showMultiple', TRUE);
145 }
146
147 if (empty($fields['is_multiple']) && $fields['style'] == 'Tab with table') {
148 $errors['style'] = ts("Display Style 'Tab with table' is only supported for multiple-record custom field sets.");
149 }
150
151 //checks the given custom set doesnot start with digit
152 $title = $fields['title'];
153 if (!empty($title)) {
154 // gives the ascii value
155 $asciiValue = ord($title{0});
156 if ($asciiValue >= 48 && $asciiValue <= 57) {
157 $errors['title'] = ts("Name cannot not start with a digit");
158 }
159 }
160
161 return empty($errors) ? TRUE : $errors;
162 }
163
164 /**
165 * add the rules (mainly global rules) for form.
166 * All local rules are added near the element
167 *
168 *
169 * @return void
170 * @see valid_date
171 */
172 public function addRules() {
173 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
174 }
175
176 /**
177 * Build the form object.
178 *
179 *
180 * @return void
181 */
182 public function buildQuickForm() {
183 $this->applyFilter('__ALL__', 'trim');
184
185 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomGroup');
186
187 //title
188 $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
189
190 //Fix for code alignment, CRM-3058
191 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
192 $this->assign('contactTypes', json_encode($contactTypes));
193
194 $sel1 = array("" => ts("- select -")) + CRM_Core_SelectValues::customGroupExtends();
195 $sel2 = array();
196 $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
197
198 $eventType = CRM_Core_OptionGroup::values('event_type');
199 $grantType = CRM_Core_OptionGroup::values('grant_type');
200 $campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
201 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
202 $participantRole = CRM_Core_OptionGroup::values('participant_role');
203
204 ksort($sel1);
205 asort($activityType);
206 asort($eventType);
207 asort($grantType);
208 asort($membershipType);
209 asort($participantRole);
210
211 $sel2['Event'] = $eventType;
212 $sel2['Grant'] = $grantType;
213 $sel2['Activity'] = $activityType;
214 $sel2['Campaign'] = $campaignTypes;
215 $sel2['Membership'] = $membershipType;
216 $sel2['ParticipantRole'] = $participantRole;
217 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
218 $sel2['ParticipantEventType'] = $eventType;
219 $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
220 $sel2['Relationship'] = self::getRelationshipTypes();
221
222 $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
223 $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
224 $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
225
226 CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
227
228 foreach ($sel2 as $main => $sub) {
229 if (!empty($sel2[$main])) {
230 $sel2[$main] = array(
231 '' => ts("- Any -"),
232 ) + $sel2[$main];
233 }
234 }
235
236 $cSubTypes = CRM_Core_Component::contactSubTypes();
237
238 if (!empty($cSubTypes)) {
239 $contactSubTypes = array();
240 foreach ($cSubTypes as $key => $value) {
241 $contactSubTypes[$key] = $key;
242 }
243 $sel2['Contact'] = array(
244 "" => ("- Any -"),
245 ) + $contactSubTypes;
246 }
247 else {
248 if (!isset($this->_id)) {
249 $formName = 'document.forms.' . $this->_name;
250
251 $js = "<script type='text/javascript'>\n";
252 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
253 $js .= "</script>";
254 $this->assign('initHideBlocks', $js);
255 }
256 }
257
258 $sel = &$this->add('hierselect',
259 'extends',
260 ts('Used For'),
261 array(
262 'name' => 'extends[0]',
263 'style' => 'vertical-align: top;',
264 ),
265 TRUE
266 );
267 $sel->setOptions(array($sel1, $sel2));
268 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
269 // make second selector a multi-select -
270 $sel->_elements[1]->setMultiple(TRUE);
271 $sel->_elements[1]->setSize(5);
272 }
273 if ($this->_action == CRM_Core_Action::UPDATE) {
274 $subName = CRM_Utils_Array::value('extends_entity_column_id', $this->_defaults);
275 if ($this->_defaults['extends'] == 'Participant') {
276 if ($subName == 1) {
277 $this->_defaults['extends'] = 'ParticipantRole';
278 }
279 elseif ($subName == 2) {
280 $this->_defaults['extends'] = 'ParticipantEventName';
281 }
282 elseif ($subName == 3) {
283 $this->_defaults['extends'] = 'ParticipantEventType';
284 }
285 }
286
287 //allow to edit settings if custom set is empty CRM-5258
288 $this->_isGroupEmpty = CRM_Core_BAO_CustomGroup::isGroupEmpty($this->_id);
289 if (!$this->_isGroupEmpty) {
290 if (!empty($this->_subtypes)) {
291 // we want to allow adding / updating subtypes for this case,
292 // and therefore freeze the first selector only.
293 $sel->_elements[0]->freeze();
294 }
295 else {
296 // freeze both the selectors
297 $sel->freeze();
298 }
299 }
300 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty);
301 $this->assign('gid', $this->_id);
302 }
303 $this->assign('defaultSubtypes', json_encode($this->_subtypes));
304
305 // help text
306 $this->add('wysiwyg', 'help_pre', ts('Pre-form Help'), $attributes['help_pre']);
307 $this->add('wysiwyg', 'help_post', ts('Post-form Help'), $attributes['help_post']);
308
309 // weight
310 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
311 $this->addRule('weight', ts('is a numeric field'), 'numeric');
312
313 // display style
314 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues::customGroupStyle());
315
316 // is this set collapsed or expanded ?
317 $this->addElement('advcheckbox', 'collapse_display', ts('Collapse this set on initial display'));
318
319 // is this set collapsed or expanded ? in advanced search
320 $this->addElement('advcheckbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
321
322 // is this set active ?
323 $this->addElement('advcheckbox', 'is_active', ts('Is this Custom Data Set active?'));
324
325 //Is this set visible on public pages?
326 $this->addElement('advcheckbox', 'is_public', ts('Is this Custom Data Set public?'));
327
328 // does this set have multiple record?
329 $multiple = $this->addElement('advcheckbox', 'is_multiple',
330 ts('Does this Custom Field Set allow multiple records?'), NULL);
331
332 // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
333 // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
334
335 $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
336 $this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
337
338 //allow to edit settings if custom set is empty CRM-5258
339 $this->assign('isGroupEmpty', $this->_isGroupEmpty);
340 if (!$this->_isGroupEmpty) {
341 $multiple->freeze();
342 //$min_multiple->freeze();
343 $max_multiple->freeze();
344 }
345
346 $this->assign('showStyle', FALSE);
347 $this->assign('showMultiple', FALSE);
348 $buttons = array(
349 array(
350 'type' => 'next',
351 'name' => ts('Save'),
352 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
353 'isDefault' => TRUE,
354 ),
355 array(
356 'type' => 'cancel',
357 'name' => ts('Cancel'),
358 ),
359 );
360 if (!$this->_isGroupEmpty && !empty($this->_subtypes)) {
361 $buttons[0]['class'] = 'crm-warnDataLoss';
362 }
363 $this->addButtons($buttons);
364
365 // TODO: Is this condition ever true? Can this code be removed?
366 if ($this->_action & CRM_Core_Action::VIEW) {
367 $this->freeze();
368 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
369 }
370 }
371
372 /**
373 * Set default values for the form. Note that in edit/view mode
374 * the default values are retrieved from the database
375 *
376 *
377 * @return array
378 * array of default values
379 */
380 public function setDefaultValues() {
381 $defaults = &$this->_defaults;
382 $this->assign('showMaxMultiple', TRUE);
383 if ($this->_action == CRM_Core_Action::ADD) {
384 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomGroup');
385
386 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
387 $defaults['is_active'] = $defaults['is_public'] = $defaults['collapse_display'] = 1;
388 $defaults['style'] = 'Inline';
389 }
390 elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty) {
391 $this->assign('showMaxMultiple', FALSE);
392 }
393
394 if (($this->_action & CRM_Core_Action::UPDATE) && !empty($defaults['is_multiple'])) {
395 $defaults['collapse_display'] = 0;
396 }
397
398 if (isset($defaults['extends'])) {
399 $extends = $defaults['extends'];
400 unset($defaults['extends']);
401
402 $defaults['extends'][0] = $extends;
403
404 if (!empty($this->_subtypes)) {
405 $defaults['extends'][1] = $this->_subtypes;
406 }
407 else {
408 $defaults['extends'][1] = array(0 => '');
409 }
410
411 if ($extends == 'Relationship' && !empty($this->_subtypes)) {
412 $relationshipDefaults = array();
413 foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
414 $relationshipDefaults[] = $rel_type_id;
415 }
416
417 $defaults['extends'][1] = $relationshipDefaults;
418 }
419 }
420
421 return $defaults;
422 }
423
424 /**
425 * Process the form.
426 *
427 *
428 * @return void
429 */
430 public function postProcess() {
431 // get the submitted form values.
432 $params = $this->controller->exportValues('Group');
433 $params['overrideFKConstraint'] = 0;
434 if ($this->_action & CRM_Core_Action::UPDATE) {
435 $params['id'] = $this->_id;
436 if ($this->_defaults['extends'][0] != $params['extends'][0]) {
437 $params['overrideFKConstraint'] = 1;
438 }
439
440 if (!empty($this->_subtypes)) {
441 $subtypesToBeRemoved = array();
442 $subtypesToPreserve = $params['extends'][1];
443 // Don't remove any value if group is extended to -any- subtype
444 if (!empty($subtypesToPreserve[0])) {
445 $subtypesToBeRemoved = array_diff($this->_subtypes, array_intersect($this->_subtypes, $subtypesToPreserve));
446 }
447 CRM_Contact_BAO_ContactType::deleteCustomRowsOfSubtype($this->_id, $subtypesToBeRemoved, $subtypesToPreserve);
448 }
449 }
450 elseif ($this->_action & CRM_Core_Action::ADD) {
451 //new custom set , so lets set the created_id
452 $session = CRM_Core_Session::singleton();
453 $params['created_id'] = $session->get('userID');
454 $params['created_date'] = date('YmdHis');
455 }
456
457 $group = CRM_Core_BAO_CustomGroup::create($params);
458
459 // reset the cache
460 CRM_Core_BAO_Cache::deleteGroup('contact fields');
461
462 if ($this->_action & CRM_Core_Action::UPDATE) {
463 CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title)), ts('Saved'), 'success');
464 }
465 else {
466 // Jump directly to adding a field if popups are disabled
467 $action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? '' : '/add';
468 $url = CRM_Utils_System::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id . '&action=' . ($action ? 'add' : 'browse'));
469 CRM_Core_Session::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
470 array(1 => $group->title)
471 ), ts('Saved'), 'success');
472 $session = CRM_Core_Session::singleton();
473 $session->replaceUserContext($url);
474 }
475
476 // prompt Drupal Views users to update $db_prefix in settings.php, if necessary
477 global $db_prefix;
478 $config = CRM_Core_Config::singleton();
479 if (is_array($db_prefix) && $config->userSystem->is_drupal && module_exists('views')) {
480 // get table_name for each custom group
481 $tables = array();
482 $sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
483 $result = CRM_Core_DAO::executeQuery($sql);
484 while ($result->fetch()) {
485 $tables[$result->table_name] = $result->table_name;
486 }
487
488 // find out which tables are missing from the $db_prefix array
489 $missingTableNames = array_diff_key($tables, $db_prefix);
490
491 if (!empty($missingTableNames)) {
492 CRM_Core_Session::setStatus(ts("To ensure that all of your custom data groups are available to Views, you may need to add the following key(s) to the db_prefix array in your settings.php file: '%1'.",
493 array(1 => implode(', ', $missingTableNames))
494 ), ts('Note'), 'info');
495 }
496 }
497 }
498
499 /**
500 * Return a formatted list of relationship labels.
501 *
502 * @return array
503 * Array (int $id => string $label).
504 */
505 public static function getRelationshipTypes() {
506 // Note: We include inactive reltypes because we don't want to break custom-data
507 // UI when a reltype is disabled.
508 return CRM_Core_DAO::executeQuery('
509 SELECT
510 id,
511 (CASE 1
512 WHEN label_a_b is not null AND label_b_a is not null AND label_a_b != label_b_a
513 THEN concat(label_a_b, \' / \', label_b_a)
514 WHEN label_a_b is not null
515 THEN label_a_b
516 WHEN label_b_a is not null
517 THEN label_b_a
518 ELSE concat("RelType #", id)
519 END) as label
520 FROM civicrm_relationship_type
521 '
522 )->fetchMap('id', 'label');
523 }
524
525 }