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