3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 * form to process actions on the set aspect of Custom Data
39 class CRM_Custom_Form_Group
extends CRM_Core_Form
{
42 * The set id saved to the session for an update.
49 * set is empty or not.
53 protected $_isGroupEmpty = TRUE;
56 * Array of existing subtypes set for a custom set.
60 protected $_subtypes = array();
63 * Set variables up before form is built.
68 public function preProcess() {
70 $this->_id
= $this->get('id');
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.");
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)));
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)));
85 CRM_Utils_System
::setTitle(ts('New Custom Field Set'));
88 if (isset($this->_id
)) {
89 $params = array('id' => $this->_id
);
90 CRM_Core_BAO_CustomGroup
::retrieve($params, $this->_defaults
);
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));
102 * @param array $fields
103 * The input form values.
104 * @param array $files
105 * The uploaded files if any.
110 * true if no errors, else array of errors
112 public static function formRule($fields, $files, $self) {
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'),
124 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
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'.");
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.");
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);
143 if (!empty($fields['is_multiple'])) {
144 $self->assign('showMultiple', TRUE);
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.");
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");
161 return empty($errors) ?
TRUE : $errors;
165 * add the rules (mainly global rules) for form.
166 * All local rules are added near the element
172 public function addRules() {
173 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
177 * Build the form object.
182 public function buildQuickForm() {
183 $this->applyFilter('__ALL__', 'trim');
185 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomGroup');
188 $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
190 //Fix for code alignment, CRM-3058
191 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
192 $this->assign('contactTypes', json_encode($contactTypes));
194 $sel1 = array("" => ts("- select -")) + CRM_Core_SelectValues
::customGroupExtends();
196 $activityType = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
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');
205 asort($activityType);
208 asort($membershipType);
209 asort($participantRole);
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();
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);
226 CRM_Core_BAO_CustomGroup
::getExtendedObjectTypes($sel2);
228 foreach ($sel2 as $main => $sub) {
229 if (!empty($sel2[$main])) {
230 $sel2[$main] = array(
236 $cSubTypes = CRM_Core_Component
::contactSubTypes();
238 if (!empty($cSubTypes)) {
239 $contactSubTypes = array();
240 foreach ($cSubTypes as $key => $value) {
241 $contactSubTypes[$key] = $key;
243 $sel2['Contact'] = array(
245 ) +
$contactSubTypes;
248 if (!isset($this->_id
)) {
249 $formName = 'document.forms.' . $this->_name
;
251 $js = "<script type='text/javascript'>\n";
252 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
254 $this->assign('initHideBlocks', $js);
258 $sel = &$this->add('hierselect',
262 'name' => 'extends[0]',
263 'style' => 'vertical-align: top;',
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);
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') {
277 $this->_defaults
['extends'] = 'ParticipantRole';
279 elseif ($subName == 2) {
280 $this->_defaults
['extends'] = 'ParticipantEventName';
282 elseif ($subName == 3) {
283 $this->_defaults
['extends'] = 'ParticipantEventType';
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();
296 // freeze both the selectors
300 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty
);
301 $this->assign('gid', $this->_id
);
303 $this->assign('defaultSubtypes', json_encode($this->_subtypes
));
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']);
310 $this->add('number', 'weight', ts('Order'), $attributes['weight'], TRUE);
311 $this->addRule('weight', ts('is a numeric field'), 'numeric');
314 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues
::customGroupStyle());
316 // is this set collapsed or expanded ?
317 $this->addElement('advcheckbox', 'collapse_display', ts('Collapse this set on initial display'));
319 // is this set collapsed or expanded ? in advanced search
320 $this->addElement('advcheckbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
322 // is this set active ?
323 $this->addElement('advcheckbox', 'is_active', ts('Is this Custom Data Set active?'));
325 //Is this set visible on public pages?
326 $this->addElement('advcheckbox', 'is_public', ts('Is this Custom Data Set public?'));
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);
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');
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');
338 //allow to edit settings if custom set is empty CRM-5258
339 $this->assign('isGroupEmpty', $this->_isGroupEmpty
);
340 if (!$this->_isGroupEmpty
) {
342 //$min_multiple->freeze();
343 $max_multiple->freeze();
346 $this->assign('showStyle', FALSE);
347 $this->assign('showMultiple', FALSE);
351 'name' => ts('Save'),
352 'spacing' => ' ',
357 'name' => ts('Cancel'),
360 if (!$this->_isGroupEmpty
&& !empty($this->_subtypes
)) {
361 $buttons[0]['class'] = 'crm-warnDataLoss';
363 $this->addButtons($buttons);
365 // TODO: Is this condition ever true? Can this code be removed?
366 if ($this->_action
& CRM_Core_Action
::VIEW
) {
368 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
373 * Set default values for the form. Note that in edit/view mode
374 * the default values are retrieved from the database
378 * array of default values
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');
386 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
387 $defaults['is_active'] = $defaults['is_public'] = $defaults['collapse_display'] = 1;
388 $defaults['style'] = 'Inline';
390 elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty
) {
391 $this->assign('showMaxMultiple', FALSE);
394 if (($this->_action
& CRM_Core_Action
::UPDATE
) && !empty($defaults['is_multiple'])) {
395 $defaults['collapse_display'] = 0;
398 if (isset($defaults['extends'])) {
399 $extends = $defaults['extends'];
400 unset($defaults['extends']);
402 $defaults['extends'][0] = $extends;
404 if (!empty($this->_subtypes
)) {
405 $defaults['extends'][1] = $this->_subtypes
;
408 $defaults['extends'][1] = array(0 => '');
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;
417 $defaults['extends'][1] = $relationshipDefaults;
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;
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));
447 CRM_Contact_BAO_ContactType
::deleteCustomRowsOfSubtype($this->_id
, $subtypesToBeRemoved, $subtypesToPreserve);
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');
457 $group = CRM_Core_BAO_CustomGroup
::create($params);
460 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
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');
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);
476 // prompt Drupal Views users to update $db_prefix in settings.php, if necessary
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
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
;
488 // find out which tables are missing from the $db_prefix array
489 $missingTableNames = array_diff_key($tables, $db_prefix);
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');
500 * Return a formatted list of relationship labels.
503 * Array (int $id => string $label).
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('
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
516 WHEN label_b_a is not null
518 ELSE concat("RelType #", id)
520 FROM civicrm_relationship_type
522 )->fetchMap('id', 'label');