Merge pull request #4820 from kurund/CRM-15705
[civicrm-core.git] / CRM / Custom / Form / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * Array of default params
64 *
65 * @var array
66 */
67 protected $_defaults = array();
68
69 /**
70 * Set variables up before form is built
71 *
72 * @param null
73 *
74 * @return void
75 */
76 public function preProcess() {
77 // current set id
78 $this->_id = $this->get('id');
79
80 if ($this->_id && $isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_id, 'is_reserved', 'id')) {
81 CRM_Core_Error::fatal("You cannot edit the settings of a reserved custom field-set.");
82 }
83 // setting title for html page
84 if ($this->_action == CRM_Core_Action::UPDATE) {
85 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
86 CRM_Utils_System::setTitle(ts('Edit %1', array(1 => $title)));
87 }
88 elseif ($this->_action == CRM_Core_Action::VIEW) {
89 $title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
90 CRM_Utils_System::setTitle(ts('Preview %1', array(1 => $title)));
91 }
92 else {
93 CRM_Utils_System::setTitle(ts('New Custom Field Set'));
94 }
95
96 if (isset($this->_id)) {
97 $params = array('id' => $this->_id);
98 CRM_Core_BAO_CustomGroup::retrieve($params, $this->_defaults);
99
100 $subExtends = CRM_Utils_Array::value('extends_entity_column_value', $this->_defaults);
101 if (!empty($subExtends)) {
102 $this->_subtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subExtends, 1, -1));
103 }
104 }
105 }
106
107 /**
108 * Global form rule
109 *
110 * @param array $fields the input form values
111 * @param array $files the uploaded files if any
112 * @param $self
113 *
114 *
115 * @return true if no errors, else array of errors
116 * @static
117 */
118 public static function formRule($fields, $files, $self) {
119 $errors = array();
120
121 //validate group title as well as name.
122 $title = $fields['title'];
123 $name = CRM_Utils_String::munge($title, '_', 64);
124 $query = 'select count(*) from civicrm_custom_group where ( name like %1 OR title like %2 ) and id != %3';
125 $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(1 => array($name, 'String'),
126 2 => array($title, 'String'),
127 3 => array((int)$self->_id, 'Integer'),
128 ));
129 if ($grpCnt) {
130 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
131 }
132
133 if (!empty($fields['extends'][1])) {
134 if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
135 $errors['extends'] = ts("Cannot combine other option with 'Any'.");
136 }
137 }
138
139 if (empty($fields['extends'][0])) {
140 $errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
141 }
142
143 $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
144 if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
145 $errors['style'] = ts("Display Style should be Inline for this Class");
146 $self->assign('showStyle', TRUE);
147 }
148
149 if (!empty($fields['is_multiple'])) {
150 $self->assign('showMultiple', TRUE);
151 }
152
153 if (empty($fields['is_multiple']) && $fields['style'] == 'Tab with table') {
154 $errors['style'] = ts("Display Style 'Tab with table' is only supported for multiple-record custom field sets.");
155 }
156
157 //checks the given custom set doesnot start with digit
158 $title = $fields['title'];
159 if (!empty($title)) {
160 // gives the ascii value
161 $asciiValue = ord($title{0});
162 if ($asciiValue >= 48 && $asciiValue <= 57) {
163 $errors['title'] = ts("Name cannot not start with a digit");
164 }
165 }
166
167 return empty($errors) ? TRUE : $errors;
168 }
169
170 /**
171 * This function is used to add the rules (mainly global rules) for form.
172 * All local rules are added near the element
173 *
174 * @param null
175 *
176 * @return void
177 * @see valid_date
178 */
179 public function addRules() {
180 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
181 }
182
183 /**
184 * Build the form object
185 *
186 * @param null
187 *
188 * @return void
189 */
190 public function buildQuickForm() {
191 $this->applyFilter('__ALL__', 'trim');
192
193 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomGroup');
194
195 //title
196 $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
197
198 //Fix for code alignment, CRM-3058
199 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
200 $this->assign('contactTypes', json_encode($contactTypes));
201
202 $sel1 = array("" => "- select -") + CRM_Core_SelectValues::customGroupExtends();
203 $sel2 = array();
204 $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
205
206 $eventType = CRM_Core_OptionGroup::values('event_type');
207 $grantType = CRM_Core_OptionGroup::values('grant_type');
208 $campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
209 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
210 $participantRole = CRM_Core_OptionGroup::values('participant_role');
211 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
212 $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
213 $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
214
215 ksort($sel1);
216 asort($activityType);
217 asort($eventType);
218 asort($grantType);
219 asort($membershipType);
220 asort($participantRole);
221 $allRelationshipType = array();
222 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
223 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
224
225 //adding subtype specific relationships CRM-5256
226 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
227
228 foreach ($subTypes as $subType => $val) {
229 $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
230 FALSE, 'label', TRUE, $subType
231 );
232 $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes);
233 }
234
235 $sel2['Event'] = $eventType;
236 $sel2['Grant'] = $grantType;
237 $sel2['Activity'] = $activityType;
238 $sel2['Campaign'] = $campaignTypes;
239 $sel2['Membership'] = $membershipType;
240 $sel2['ParticipantRole'] = $participantRole;
241 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
242 $sel2['ParticipantEventType'] = $eventType;
243 $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
244 $sel2['Relationship'] = $allRelationshipType;
245
246 $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
247 $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
248 $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
249
250 CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
251
252 foreach ($sel2 as $main => $sub) {
253 if (!empty($sel2[$main])) {
254 if ($main == 'Relationship') {
255 $relName = self::getFormattedList($sel2[$main]);
256 $sel2[$main] = array(
257 '' => ts("- Any -")) + $relName;
258 }
259 else {
260 $sel2[$main] = array(
261 '' => ts("- Any -")) + $sel2[$main];
262 }
263 }
264 }
265
266 $cSubTypes = CRM_Core_Component::contactSubTypes();
267
268 if (!empty($cSubTypes)) {
269 $contactSubTypes = array();
270 foreach ($cSubTypes as $key => $value) {
271 $contactSubTypes[$key] = $key;
272 }
273 $sel2['Contact'] = array(
274 "" => "-- Any --") + $contactSubTypes;
275 }
276 else {
277 if (!isset($this->_id)) {
278 $formName = 'document.forms.' . $this->_name;
279
280 $js = "<script type='text/javascript'>\n";
281 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
282 $js .= "</script>";
283 $this->assign('initHideBlocks', $js);
284 }
285 }
286
287 $sel = &$this->add('hierselect',
288 'extends',
289 ts('Used For'),
290 array(
291 'name' => 'extends[0]',
292 'style' => 'vertical-align: top;'
293 ),
294 TRUE
295 );
296 $sel->setOptions(array($sel1, $sel2));
297 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
298 // make second selector a multi-select -
299 $sel->_elements[1]->setMultiple(TRUE);
300 $sel->_elements[1]->setSize(5);
301 }
302 if ($this->_action == CRM_Core_Action::UPDATE) {
303 $subName = CRM_Utils_Array::value('extends_entity_column_id', $this->_defaults);
304 if ($this->_defaults['extends'] == 'Participant') {
305 if ($subName == 1) {
306 $this->_defaults['extends'] = 'ParticipantRole';
307 }
308 elseif ($subName == 2) {
309 $this->_defaults['extends'] = 'ParticipantEventName';
310 }
311 elseif ($subName == 3) {
312 $this->_defaults['extends'] = 'ParticipantEventType';
313 }
314 }
315
316 //allow to edit settings if custom set is empty CRM-5258
317 $this->_isGroupEmpty = CRM_Core_BAO_CustomGroup::isGroupEmpty($this->_id);
318 if (!$this->_isGroupEmpty) {
319 if (!empty($this->_subtypes)) {
320 // we want to allow adding / updating subtypes for this case,
321 // and therefore freeze the first selector only.
322 $sel->_elements[0]->freeze();
323 }
324 else {
325 // freeze both the selectors
326 $sel->freeze();
327 }
328 }
329 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty);
330 $this->assign('gid', $this->_id);
331 }
332 $this->assign('defaultSubtypes', json_encode($this->_subtypes));
333
334 // help text
335 $this->addWysiwyg('help_pre', ts('Pre-form Help'), $attributes['help_pre']);
336 $this->addWysiwyg('help_post', ts('Post-form Help'), $attributes['help_post']);
337
338 // weight
339 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
340 $this->addRule('weight', ts('is a numeric field'), 'numeric');
341
342 // display style
343 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues::customGroupStyle());
344
345 // is this set collapsed or expanded ?
346 $this->addElement('checkbox', 'collapse_display', ts('Collapse this set on initial display'));
347
348 // is this set collapsed or expanded ? in advanced search
349 $this->addElement('checkbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
350
351 // is this set active ?
352 $this->addElement('checkbox', 'is_active', ts('Is this Custom Data Set active?'));
353
354 // does this set have multiple record?
355 $multiple = $this->addElement('checkbox', 'is_multiple',
356 ts('Does this Custom Field Set allow multiple records?'), NULL);
357
358 // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
359 // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
360
361 $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
362 $this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
363
364 //allow to edit settings if custom set is empty CRM-5258
365 $this->assign('isGroupEmpty', $this->_isGroupEmpty);
366 if (!$this->_isGroupEmpty) {
367 $multiple->freeze();
368 //$min_multiple->freeze();
369 $max_multiple->freeze();
370 }
371
372 $this->assign('showStyle', FALSE);
373 $this->assign('showMultiple', FALSE);
374 $buttons = array(
375 array(
376 'type' => 'next',
377 'name' => ts('Save'),
378 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
379 'isDefault' => TRUE,
380 ),
381 array(
382 'type' => 'cancel',
383 'name' => ts('Cancel'),
384 ),
385 );
386 if (!$this->_isGroupEmpty && !empty($this->_subtypes)) {
387 $buttons[0]['js'] = array('onclick' => "return warnDataLoss()");
388 }
389 $this->addButtons($buttons);
390
391 // views are implemented as frozen form
392 if ($this->_action & CRM_Core_Action::VIEW) {
393 $this->freeze();
394 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
395 }
396 }
397
398 /**
399 * Set default values for the form. Note that in edit/view mode
400 * the default values are retrieved from the database
401 *
402 * @param null
403 *
404 * @return array array of default values
405 */
406 public function setDefaultValues() {
407 $defaults = &$this->_defaults;
408 $this->assign('showMaxMultiple', TRUE);
409 if ($this->_action == CRM_Core_Action::ADD) {
410 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomGroup');
411
412 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
413 $defaults['is_active'] = $defaults['collapse_display'] = 1;
414 $defaults['style'] = 'Inline';
415 }
416 elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty) {
417 $this->assign('showMaxMultiple', FALSE);
418 }
419
420 if (($this->_action & CRM_Core_Action::UPDATE) && !empty($defaults['is_multiple'])) {
421 $defaults['collapse_display'] = 0;
422 }
423
424 if (isset($defaults['extends'])) {
425 $extends = $defaults['extends'];
426 unset($defaults['extends']);
427
428 $defaults['extends'][0] = $extends;
429
430 if (!empty($this->_subtypes)) {
431 $defaults['extends'][1] = $this->_subtypes;
432 }
433 else {
434 $defaults['extends'][1] = array(0 => '');
435 }
436
437 if ($extends == 'Relationship' && !empty($this->_subtypes)) {
438 $relationshipDefaults = array();
439 foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
440 $relationshipDefaults[] = $rel_type_id;
441 }
442
443 $defaults['extends'][1] = $relationshipDefaults;
444 }
445 }
446
447 return $defaults;
448 }
449
450 /**
451 * Process the form
452 *
453 * @param null
454 *
455 * @return void
456 */
457 public function postProcess() {
458 // get the submitted form values.
459 $params = $this->controller->exportValues('Group');
460 $params['overrideFKConstraint'] = 0;
461 if ($this->_action & CRM_Core_Action::UPDATE) {
462 $params['id'] = $this->_id;
463 if ($this->_defaults['extends'][0] != $params['extends'][0]) {
464 $params['overrideFKConstraint'] = 1;
465 }
466
467 if (!empty($this->_subtypes)) {
468 $subtypesToBeRemoved = array_diff($this->_subtypes, array_intersect($this->_subtypes, $params['extends'][1]));
469 CRM_Contact_BAO_ContactType::deleteCustomRowsOfSubtype($this->_id, $subtypesToBeRemoved);
470 }
471 }
472 elseif ($this->_action & CRM_Core_Action::ADD) {
473 //new custom set , so lets set the created_id
474 $session = CRM_Core_Session::singleton();
475 $params['created_id'] = $session->get('userID');
476 $params['created_date'] = date('YmdHis');
477 }
478
479 $group = CRM_Core_BAO_CustomGroup::create($params);
480
481 // reset the cache
482 CRM_Core_BAO_Cache::deleteGroup('contact fields');
483
484 if ($this->_action & CRM_Core_Action::UPDATE) {
485 CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title)), ts('Saved'), 'success');
486 }
487 else {
488 // Jump directly to adding a field if popups are disabled
489 $action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? '' : '/add';
490 $url = CRM_Utils_System::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id . '&action=' . ($action ? 'add' : 'browse'));
491 CRM_Core_Session::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
492 array(1 => $group->title)
493 ), ts('Saved'), 'success');
494 $session = CRM_Core_Session::singleton();
495 $session->replaceUserContext($url);
496 }
497
498 // prompt Drupal Views users to update $db_prefix in settings.php, if necessary
499 global $db_prefix;
500 $config = CRM_Core_Config::singleton();
501 if (is_array($db_prefix) && $config->userSystem->is_drupal && module_exists('views')) {
502 // get table_name for each custom group
503 $tables = array();
504 $sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
505 $result = CRM_Core_DAO::executeQuery($sql);
506 while ($result->fetch()) {
507 $tables[$result->table_name] = $result->table_name;
508 }
509
510 // find out which tables are missing from the $db_prefix array
511 $missingTableNames = array_diff_key($tables, $db_prefix);
512
513 if (!empty($missingTableNames)) {
514 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'.",
515 array(1 => implode(', ', $missingTableNames))
516 ), ts('Note'), 'info');
517 }
518 }
519 }
520
521 /**
522 * Return a formatted list of relationship name.
523 *
524 * @param array $list array of relationship name.
525 *
526 * @return array of relationship name.
527 */
528 public static function getFormattedList(&$list) {
529 $relName = array();
530
531 foreach ($list as $listItemKey => $itemValue) {
532 // Extract the relationship ID.
533 $key = substr($listItemKey, 0, strpos($listItemKey, '_'));
534 if (isset($list["{$key}_b_a"])) {
535 $relName["$key"] = $list["{$key}_a_b"];
536 // Are the two labels different?
537 if ($list["{$key}_a_b"] != $list["{$key}_b_a"]) {
538 $relName["$key"] = $list["{$key}_a_b"] . ' / ' . $list["{$key}_b_a"];
539 }
540 unset($list["{$key}_b_a"]);
541 unset($list["{$key}_a_b"]);
542 }
543 else {
544 // If no '_b_a' label exists save the '_a_b' one and unset it from the list
545 $relName["{$key}"] = $list["{$key}_a_b"];
546 unset($list["{$key}_a_b"]);
547 }
548 }
549 return $relName;
550 }
551 }