3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
53 protected $_isGroupEmpty = TRUE;
56 * Array of existing subtypes set for a custom set
60 protected $_subtypes = array();
63 * Array of default params
67 protected $_defaults = array();
70 * Set variables up before form is built
75 public function preProcess() {
77 $this->_id
= $this->get('id');
79 if ($this->_id
&& $isReserved = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_id
, 'is_reserved', 'id')) {
80 CRM_Core_Error
::fatal("You cannot edit the settings of a reserved custom field-set.");
82 // setting title for html page
83 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
84 $title = CRM_Core_BAO_CustomGroup
::getTitle($this->_id
);
85 CRM_Utils_System
::setTitle(ts('Edit %1', array(1 => $title)));
87 elseif ($this->_action
== CRM_Core_Action
::VIEW
) {
88 $title = CRM_Core_BAO_CustomGroup
::getTitle($this->_id
);
89 CRM_Utils_System
::setTitle(ts('Preview %1', array(1 => $title)));
92 CRM_Utils_System
::setTitle(ts('New Custom Field Set'));
95 if (isset($this->_id
)) {
96 $params = array('id' => $this->_id
);
97 CRM_Core_BAO_CustomGroup
::retrieve($params, $this->_defaults
);
99 $subExtends = CRM_Utils_Array
::value('extends_entity_column_value', $this->_defaults
);
100 if (!empty($subExtends)) {
101 $this->_subtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($subExtends, 1, -1));
109 * @param array $fields
110 * The input form values.
111 * @param array $files
112 * The uploaded files if any.
117 * true if no errors, else array of errors
119 public static function formRule($fields, $files, $self) {
122 //validate group title as well as name.
123 $title = $fields['title'];
124 $name = CRM_Utils_String
::munge($title, '_', 64);
125 $query = 'select count(*) from civicrm_custom_group where ( name like %1 OR title like %2 ) and id != %3';
126 $grpCnt = CRM_Core_DAO
::singleValueQuery($query, array(
127 1 => array($name, 'String'),
128 2 => array($title, 'String'),
129 3 => array((int) $self->_id
, 'Integer'),
132 $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
135 if (!empty($fields['extends'][1])) {
136 if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
137 $errors['extends'] = ts("Cannot combine other option with 'Any'.");
141 if (empty($fields['extends'][0])) {
142 $errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
145 $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
146 if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
147 $errors['style'] = ts("Display Style should be Inline for this Class");
148 $self->assign('showStyle', TRUE);
151 if (!empty($fields['is_multiple'])) {
152 $self->assign('showMultiple', TRUE);
155 if (empty($fields['is_multiple']) && $fields['style'] == 'Tab with table') {
156 $errors['style'] = ts("Display Style 'Tab with table' is only supported for multiple-record custom field sets.");
159 //checks the given custom set doesnot start with digit
160 $title = $fields['title'];
161 if (!empty($title)) {
162 // gives the ascii value
163 $asciiValue = ord($title{0});
164 if ($asciiValue >= 48 && $asciiValue <= 57) {
165 $errors['title'] = ts("Name cannot not start with a digit");
169 return empty($errors) ?
TRUE : $errors;
173 * add the rules (mainly global rules) for form.
174 * All local rules are added near the element
180 public function addRules() {
181 $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
185 * Build the form object
190 public function buildQuickForm() {
191 $this->applyFilter('__ALL__', 'trim');
193 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomGroup');
196 $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
198 //Fix for code alignment, CRM-3058
199 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
200 $this->assign('contactTypes', json_encode($contactTypes));
202 $sel1 = array("" => "- select -") + CRM_Core_SelectValues
::customGroupExtends();
204 $activityType = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
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');
216 asort($activityType);
219 asort($membershipType);
220 asort($participantRole);
221 $allRelationshipType = array();
222 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
223 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
225 //adding subtype specific relationships CRM-5256
226 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
228 foreach ($subTypes as $subType => $val) {
229 $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
230 FALSE, 'label', TRUE, $subType
232 $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes);
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;
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);
250 CRM_Core_BAO_CustomGroup
::getExtendedObjectTypes($sel2);
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(
261 $sel2[$main] = array(
268 $cSubTypes = CRM_Core_Component
::contactSubTypes();
270 if (!empty($cSubTypes)) {
271 $contactSubTypes = array();
272 foreach ($cSubTypes as $key => $value) {
273 $contactSubTypes[$key] = $key;
275 $sel2['Contact'] = array(
277 ) +
$contactSubTypes;
280 if (!isset($this->_id
)) {
281 $formName = 'document.forms.' . $this->_name
;
283 $js = "<script type='text/javascript'>\n";
284 $js .= "{$formName}['extends_1'].style.display = 'none';\n";
286 $this->assign('initHideBlocks', $js);
290 $sel = &$this->add('hierselect',
294 'name' => 'extends[0]',
295 'style' => 'vertical-align: top;',
299 $sel->setOptions(array($sel1, $sel2));
300 if (is_a($sel->_elements
[1], 'HTML_QuickForm_select')) {
301 // make second selector a multi-select -
302 $sel->_elements
[1]->setMultiple(TRUE);
303 $sel->_elements
[1]->setSize(5);
305 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
306 $subName = CRM_Utils_Array
::value('extends_entity_column_id', $this->_defaults
);
307 if ($this->_defaults
['extends'] == 'Participant') {
309 $this->_defaults
['extends'] = 'ParticipantRole';
311 elseif ($subName == 2) {
312 $this->_defaults
['extends'] = 'ParticipantEventName';
314 elseif ($subName == 3) {
315 $this->_defaults
['extends'] = 'ParticipantEventType';
319 //allow to edit settings if custom set is empty CRM-5258
320 $this->_isGroupEmpty
= CRM_Core_BAO_CustomGroup
::isGroupEmpty($this->_id
);
321 if (!$this->_isGroupEmpty
) {
322 if (!empty($this->_subtypes
)) {
323 // we want to allow adding / updating subtypes for this case,
324 // and therefore freeze the first selector only.
325 $sel->_elements
[0]->freeze();
328 // freeze both the selectors
332 $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty
);
333 $this->assign('gid', $this->_id
);
335 $this->assign('defaultSubtypes', json_encode($this->_subtypes
));
338 $this->addWysiwyg('help_pre', ts('Pre-form Help'), $attributes['help_pre']);
339 $this->addWysiwyg('help_post', ts('Post-form Help'), $attributes['help_post']);
342 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
343 $this->addRule('weight', ts('is a numeric field'), 'numeric');
346 $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues
::customGroupStyle());
348 // is this set collapsed or expanded ?
349 $this->addElement('checkbox', 'collapse_display', ts('Collapse this set on initial display'));
351 // is this set collapsed or expanded ? in advanced search
352 $this->addElement('checkbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
354 // is this set active ?
355 $this->addElement('checkbox', 'is_active', ts('Is this Custom Data Set active?'));
357 // does this set have multiple record?
358 $multiple = $this->addElement('checkbox', 'is_multiple',
359 ts('Does this Custom Field Set allow multiple records?'), NULL);
361 // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
362 // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
364 $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
365 $this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
367 //allow to edit settings if custom set is empty CRM-5258
368 $this->assign('isGroupEmpty', $this->_isGroupEmpty
);
369 if (!$this->_isGroupEmpty
) {
371 //$min_multiple->freeze();
372 $max_multiple->freeze();
375 $this->assign('showStyle', FALSE);
376 $this->assign('showMultiple', FALSE);
380 'name' => ts('Save'),
381 'spacing' => ' ',
386 'name' => ts('Cancel'),
389 if (!$this->_isGroupEmpty
&& !empty($this->_subtypes
)) {
390 $buttons[0]['js'] = array('onclick' => "return warnDataLoss()");
392 $this->addButtons($buttons);
394 // views are implemented as frozen form
395 if ($this->_action
& CRM_Core_Action
::VIEW
) {
397 $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
402 * Set default values for the form. Note that in edit/view mode
403 * the default values are retrieved from the database
407 * array of default values
409 public function setDefaultValues() {
410 $defaults = &$this->_defaults
;
411 $this->assign('showMaxMultiple', TRUE);
412 if ($this->_action
== CRM_Core_Action
::ADD
) {
413 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_CustomGroup');
415 $defaults['is_multiple'] = $defaults['min_multiple'] = 0;
416 $defaults['is_active'] = $defaults['collapse_display'] = 1;
417 $defaults['style'] = 'Inline';
419 elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty
) {
420 $this->assign('showMaxMultiple', FALSE);
423 if (($this->_action
& CRM_Core_Action
::UPDATE
) && !empty($defaults['is_multiple'])) {
424 $defaults['collapse_display'] = 0;
427 if (isset($defaults['extends'])) {
428 $extends = $defaults['extends'];
429 unset($defaults['extends']);
431 $defaults['extends'][0] = $extends;
433 if (!empty($this->_subtypes
)) {
434 $defaults['extends'][1] = $this->_subtypes
;
437 $defaults['extends'][1] = array(0 => '');
440 if ($extends == 'Relationship' && !empty($this->_subtypes
)) {
441 $relationshipDefaults = array();
442 foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
443 $relationshipDefaults[] = $rel_type_id;
446 $defaults['extends'][1] = $relationshipDefaults;
459 public function postProcess() {
460 // get the submitted form values.
461 $params = $this->controller
->exportValues('Group');
462 $params['overrideFKConstraint'] = 0;
463 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
464 $params['id'] = $this->_id
;
465 if ($this->_defaults
['extends'][0] != $params['extends'][0]) {
466 $params['overrideFKConstraint'] = 1;
469 if (!empty($this->_subtypes
)) {
470 $subtypesToBeRemoved = array_diff($this->_subtypes
, array_intersect($this->_subtypes
, $params['extends'][1]));
471 CRM_Contact_BAO_ContactType
::deleteCustomRowsOfSubtype($this->_id
, $subtypesToBeRemoved);
474 elseif ($this->_action
& CRM_Core_Action
::ADD
) {
475 //new custom set , so lets set the created_id
476 $session = CRM_Core_Session
::singleton();
477 $params['created_id'] = $session->get('userID');
478 $params['created_date'] = date('YmdHis');
481 $group = CRM_Core_BAO_CustomGroup
::create($params);
484 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
486 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
487 CRM_Core_Session
::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title
)), ts('Saved'), 'success');
490 // Jump directly to adding a field if popups are disabled
491 $action = CRM_Core_Resources
::singleton()->ajaxPopupsEnabled ?
'' : '/add';
492 $url = CRM_Utils_System
::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id
. '&action=' . ($action ?
'add' : 'browse'));
493 CRM_Core_Session
::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
494 array(1 => $group->title
)
495 ), ts('Saved'), 'success');
496 $session = CRM_Core_Session
::singleton();
497 $session->replaceUserContext($url);
500 // prompt Drupal Views users to update $db_prefix in settings.php, if necessary
502 $config = CRM_Core_Config
::singleton();
503 if (is_array($db_prefix) && $config->userSystem
->is_drupal
&& module_exists('views')) {
504 // get table_name for each custom group
506 $sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
507 $result = CRM_Core_DAO
::executeQuery($sql);
508 while ($result->fetch()) {
509 $tables[$result->table_name
] = $result->table_name
;
512 // find out which tables are missing from the $db_prefix array
513 $missingTableNames = array_diff_key($tables, $db_prefix);
515 if (!empty($missingTableNames)) {
516 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'.",
517 array(1 => implode(', ', $missingTableNames))
518 ), ts('Note'), 'info');
524 * Return a formatted list of relationship name.
527 * Array of relationship name.
530 * Array of relationship name.
532 public static function getFormattedList(&$list) {
535 foreach ($list as $listItemKey => $itemValue) {
536 // Extract the relationship ID.
537 $key = substr($listItemKey, 0, strpos($listItemKey, '_'));
538 if (isset($list["{$key}_b_a"])) {
539 $relName["$key"] = $list["{$key}_a_b"];
540 // Are the two labels different?
541 if ($list["{$key}_a_b"] != $list["{$key}_b_a"]) {
542 $relName["$key"] = $list["{$key}_a_b"] . ' / ' . $list["{$key}_b_a"];
544 unset($list["{$key}_b_a"]);
545 unset($list["{$key}_a_b"]);
548 // If no '_b_a' label exists save the '_a_b' one and unset it from the list
549 $relName["{$key}"] = $list["{$key}_a_b"];
550 unset($list["{$key}_a_b"]);