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