3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 OR title like %2 ) and id != %3';
119 $grpCnt = CRM_Core_DAO
::singleValueQuery($query, array(
120 1 => array($name, 'String'),
121 2 => array($title, 'String'),
122 3 => array((int) $self->_id
, 'Integer'),
125 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
128 if (!empty($fields['extends'][1])) {
129 if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
130 $errors['extends'] = ts("Cannot combine other option with 'Any'.");
134 if (empty($fields['extends'][0])) {
135 $errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
138 $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
139 if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
140 $errors['style'] = ts("Display Style should be Inline for this Class");
141 $self->assign('showStyle', TRUE);
144 if (!empty($fields['is_multiple'])) {
145 $self->assign('showMultiple', TRUE);
148 if (empty($fields['is_multiple']) && $fields['style'] == 'Tab with table') {
149 $errors['style'] = ts("Display Style 'Tab with table' is only supported for multiple-record custom field sets.");
152 //checks the given custom set doesnot start with digit
153 $title = $fields['title'];
154 if (!empty($title)) {
155 // gives the ascii value
156 $asciiValue = ord($title{0});
157 if ($asciiValue >= 48 && $asciiValue <= 57) {
158 $errors['title'] = ts("Name cannot not start with a digit");
162 return empty($errors) ?
TRUE : $errors;
166 * add the rules (mainly global rules) for form.
167 * All local rules are added near the element
173 public function addRules() {
174 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
178 * Build the form object.
183 public function buildQuickForm() {
184 $this->applyFilter('__ALL__', 'trim');
186 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomGroup');
189 $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
191 //Fix for code alignment, CRM-3058
192 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
193 $this->assign('contactTypes', json_encode($contactTypes));
195 $sel1 = array("" => ts("- select -")) + CRM_Core_SelectValues
::customGroupExtends();
197 $activityType = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
199 $eventType = CRM_Core_OptionGroup
::values('event_type');
200 $grantType = CRM_Core_OptionGroup
::values('grant_type');
201 $campaignTypes = CRM_Campaign_PseudoConstant
::campaignType();
202 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypes(FALSE);
203 $participantRole = CRM_Core_OptionGroup
::values('participant_role');
206 asort($activityType);
209 asort($membershipType);
210 asort($participantRole);
212 $sel2['Event'] = $eventType;
213 $sel2['Grant'] = $grantType;
214 $sel2['Activity'] = $activityType;
215 $sel2['Campaign'] = $campaignTypes;
216 $sel2['Membership'] = $membershipType;
217 $sel2['ParticipantRole'] = $participantRole;
218 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
219 $sel2['ParticipantEventType'] = $eventType;
220 $sel2['Contribution'] = CRM_Contribute_PseudoConstant
::financialType();
221 $sel2['Relationship'] = self
::getRelationshipTypes();
223 $sel2['Individual'] = CRM_Contact_BAO_ContactType
::subTypePairs('Individual', FALSE, NULL);
224 $sel2['Household'] = CRM_Contact_BAO_ContactType
::subTypePairs('Household', FALSE, NULL);
225 $sel2['Organization'] = CRM_Contact_BAO_ContactType
::subTypePairs('Organization', FALSE, NULL);
227 CRM_Core_BAO_CustomGroup
::getExtendedObjectTypes($sel2);
229 foreach ($sel2 as $main => $sub) {
230 if (!empty($sel2[$main])) {
231 $sel2[$main] = array(
237 $cSubTypes = CRM_Core_Component
::contactSubTypes();
239 if (!empty($cSubTypes)) {
240 $contactSubTypes = array();
241 foreach ($cSubTypes as $key => $value) {
242 $contactSubTypes[$key] = $key;
244 $sel2['Contact'] = array(
246 ) +
$contactSubTypes;
249 if (!isset($this->_id
)) {
250 $formName = 'document.forms.' . $this->_name
;
252 $js = "<script type='text/javascript'>\n";
253 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
255 $this->assign('initHideBlocks', $js);
259 $sel = &$this->add('hierselect',
263 'name' => 'extends[0]',
264 'style' => 'vertical-align: top;',
268 $sel->setOptions(array($sel1, $sel2));
269 if (is_a($sel->_elements
[1], 'HTML_QuickForm_select')) {
270 // make second selector a multi-select -
271 $sel->_elements
[1]->setMultiple(TRUE);
272 $sel->_elements
[1]->setSize(5);
274 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
275 $subName = CRM_Utils_Array
::value('extends_entity_column_id', $this->_defaults
);
276 if ($this->_defaults
['extends'] == 'Participant') {
278 $this->_defaults
['extends'] = 'ParticipantRole';
280 elseif ($subName == 2) {
281 $this->_defaults
['extends'] = 'ParticipantEventName';
283 elseif ($subName == 3) {
284 $this->_defaults
['extends'] = 'ParticipantEventType';
288 //allow to edit settings if custom set is empty CRM-5258
289 $this->_isGroupEmpty
= CRM_Core_BAO_CustomGroup
::isGroupEmpty($this->_id
);
290 if (!$this->_isGroupEmpty
) {
291 if (!empty($this->_subtypes
)) {
292 // we want to allow adding / updating subtypes for this case,
293 // and therefore freeze the first selector only.
294 $sel->_elements
[0]->freeze();
297 // freeze both the selectors
301 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty
);
302 $this->assign('gid', $this->_id
);
304 $this->assign('defaultSubtypes', json_encode($this->_subtypes
));
307 $this->add('wysiwyg', 'help_pre', ts('Pre-form Help'), $attributes['help_pre']);
308 $this->add('wysiwyg', 'help_post', ts('Post-form Help'), $attributes['help_post']);
311 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
312 $this->addRule('weight', ts('is a numeric field'), 'numeric');
315 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues
::customGroupStyle());
317 // is this set collapsed or expanded ?
318 $this->addElement('advcheckbox', 'collapse_display', ts('Collapse this set on initial display'));
320 // is this set collapsed or expanded ? in advanced search
321 $this->addElement('advcheckbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
323 // is this set active ?
324 $this->addElement('advcheckbox', 'is_active', ts('Is this Custom Data Set active?'));
326 // does this set have multiple record?
327 $multiple = $this->addElement('advcheckbox', 'is_multiple',
328 ts('Does this Custom Field Set allow multiple records?'), NULL);
330 // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
331 // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
333 $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
334 $this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
336 //allow to edit settings if custom set is empty CRM-5258
337 $this->assign('isGroupEmpty', $this->_isGroupEmpty
);
338 if (!$this->_isGroupEmpty
) {
340 //$min_multiple->freeze();
341 $max_multiple->freeze();
344 $this->assign('showStyle', FALSE);
345 $this->assign('showMultiple', FALSE);
349 'name' => ts('Save'),
350 'spacing' => ' ',
355 'name' => ts('Cancel'),
358 if (!$this->_isGroupEmpty
&& !empty($this->_subtypes
)) {
359 $buttons[0]['class'] = 'crm-warnDataLoss';
361 $this->addButtons($buttons);
363 // TODO: Is this condition ever true? Can this code be removed?
364 if ($this->_action
& CRM_Core_Action
::VIEW
) {
366 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
371 * Set default values for the form. Note that in edit/view mode
372 * the default values are retrieved from the database
376 * array of default values
378 public function setDefaultValues() {
379 $defaults = &$this->_defaults
;
380 $this->assign('showMaxMultiple', TRUE);
381 if ($this->_action
== CRM_Core_Action
::ADD
) {
382 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_CustomGroup');
384 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
385 $defaults['is_active'] = $defaults['collapse_display'] = 1;
386 $defaults['style'] = 'Inline';
388 elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty
) {
389 $this->assign('showMaxMultiple', FALSE);
392 if (($this->_action
& CRM_Core_Action
::UPDATE
) && !empty($defaults['is_multiple'])) {
393 $defaults['collapse_display'] = 0;
396 if (isset($defaults['extends'])) {
397 $extends = $defaults['extends'];
398 unset($defaults['extends']);
400 $defaults['extends'][0] = $extends;
402 if (!empty($this->_subtypes
)) {
403 $defaults['extends'][1] = $this->_subtypes
;
406 $defaults['extends'][1] = array(0 => '');
409 if ($extends == 'Relationship' && !empty($this->_subtypes
)) {
410 $relationshipDefaults = array();
411 foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
412 $relationshipDefaults[] = $rel_type_id;
415 $defaults['extends'][1] = $relationshipDefaults;
428 public function postProcess() {
429 // get the submitted form values.
430 $params = $this->controller
->exportValues('Group');
431 $params['overrideFKConstraint'] = 0;
432 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
433 $params['id'] = $this->_id
;
434 if ($this->_defaults
['extends'][0] != $params['extends'][0]) {
435 $params['overrideFKConstraint'] = 1;
438 if (!empty($this->_subtypes
)) {
439 $subtypesToBeRemoved = array();
440 $subtypesToPreserve = $params['extends'][1];
441 // Don't remove any value if group is extended to -any- subtype
442 if (!empty($subtypesToPreserve[0])) {
443 $subtypesToBeRemoved = array_diff($this->_subtypes
, array_intersect($this->_subtypes
, $subtypesToPreserve));
445 CRM_Contact_BAO_ContactType
::deleteCustomRowsOfSubtype($this->_id
, $subtypesToBeRemoved, $subtypesToPreserve);
448 elseif ($this->_action
& CRM_Core_Action
::ADD
) {
449 //new custom set , so lets set the created_id
450 $session = CRM_Core_Session
::singleton();
451 $params['created_id'] = $session->get('userID');
452 $params['created_date'] = date('YmdHis');
455 $group = CRM_Core_BAO_CustomGroup
::create($params);
458 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
460 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
461 CRM_Core_Session
::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title
)), ts('Saved'), 'success');
464 // Jump directly to adding a field if popups are disabled
465 $action = CRM_Core_Resources
::singleton()->ajaxPopupsEnabled ?
'' : '/add';
466 $url = CRM_Utils_System
::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id
. '&action=' . ($action ?
'add' : 'browse'));
467 CRM_Core_Session
::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
468 array(1 => $group->title
)
469 ), ts('Saved'), 'success');
470 $session = CRM_Core_Session
::singleton();
471 $session->replaceUserContext($url);
474 // prompt Drupal Views users to update $db_prefix in settings.php, if necessary
476 $config = CRM_Core_Config
::singleton();
477 if (is_array($db_prefix) && $config->userSystem
->is_drupal
&& module_exists('views')) {
478 // get table_name for each custom group
480 $sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
481 $result = CRM_Core_DAO
::executeQuery($sql);
482 while ($result->fetch()) {
483 $tables[$result->table_name
] = $result->table_name
;
486 // find out which tables are missing from the $db_prefix array
487 $missingTableNames = array_diff_key($tables, $db_prefix);
489 if (!empty($missingTableNames)) {
490 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'.",
491 array(1 => implode(', ', $missingTableNames))
492 ), ts('Note'), 'info');
498 * Return a formatted list of relationship labels.
501 * Array (int $id => string $label).
503 public static function getRelationshipTypes() {
504 // Note: We include inactive reltypes because we don't want to break custom-data
505 // UI when a reltype is disabled.
506 return CRM_Core_DAO
::executeQuery('
510 WHEN label_a_b is not null AND label_b_a is not null AND label_a_b != label_b_a
511 THEN concat(label_a_b, \' / \', label_b_a)
512 WHEN label_a_b is not null
514 WHEN label_b_a is not null
516 ELSE concat("RelType #", id)
518 FROM civicrm_relationship_type
520 )->fetchMap('id', 'label');