3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
29 * This class generates form components for relationship.
31 class CRM_Contact_Form_Relationship
extends CRM_Core_Form
{
34 * The relationship id, used when editing the relationship
38 public $_relationshipId;
41 * The contact id, used when add/edit relationship
48 * This is a string which is either a_b or b_a used to determine the relationship between to contacts
53 * This is a string which is used to determine the relationship between to contacts
58 * Display name of contact a
60 public $_display_name_a;
63 * Display name of contact b
65 public $_display_name_b;
68 * The relationship type id
72 public $_relationshipTypeId;
75 * An array of all relationship names
79 public $_allRelationshipNames;
89 public $_isCurrentEmployer;
97 * The relationship values if Updating relationship
102 * Case id if it called from case context
111 public function preProcess() {
112 //custom data related code
113 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
114 $this->assign('cdType', FALSE);
115 if ($this->_cdType
) {
116 $this->assign('cdType', TRUE);
117 return CRM_Custom_Form_CustomData
::preProcess($this);
120 $this->_contactId
= $this->get('contactId');
122 $this->_contactType
= CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId
, 'contact_type');
124 $this->_relationshipId
= $this->get('id');
126 $this->_rtype
= CRM_Utils_Request
::retrieve('rtype', 'String', $this);
128 $this->_rtypeId
= CRM_Utils_Request
::retrieve('relTypeId', 'String', $this);
130 $this->_display_name_a
= CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId
, 'display_name');
132 $this->assign('display_name_a', $this->_display_name_a
);
134 // Set page title based on action
135 switch ($this->_action
) {
136 case CRM_Core_Action
::VIEW
:
137 CRM_Utils_System
::setTitle(ts('View Relationship for %1', array(1 => $this->_display_name_a
)));
140 case CRM_Core_Action
::ADD
:
141 CRM_Utils_System
::setTitle(ts('Add Relationship for %1', array(1 => $this->_display_name_a
)));
144 case CRM_Core_Action
::UPDATE
:
145 CRM_Utils_System
::setTitle(ts('Edit Relationship for %1', array(1 => $this->_display_name_a
)));
148 case CRM_Core_Action
::DELETE
:
149 CRM_Utils_System
::setTitle(ts('Delete Relationship for %1', array(1 => $this->_display_name_a
)));
153 $this->_caseId
= CRM_Utils_Request
::retrieve('caseID', 'Integer', $this);
155 //get the relationship values.
156 $this->_values
= array();
157 if ($this->_relationshipId
) {
158 $params = array('id' => $this->_relationshipId
);
159 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Relationship', $params, $this->_values
);
162 if (!$this->_rtypeId
) {
163 $params = $this->controller
->exportValues($this->_name
);
164 if (isset($params['relationship_type_id'])) {
165 $this->_rtypeId
= $params['relationship_type_id'];
167 elseif (!empty($this->_values
)) {
168 $this->_rtypeId
= $this->_values
['relationship_type_id'] . '_' . $this->_rtype
;
172 //get the relationship type id
173 $this->_relationshipTypeId
= str_replace(array('_a_b', '_b_a'), array('', ''), $this->_rtypeId
);
175 //get the relationship type
176 if (!$this->_rtype
) {
177 $this->_rtype
= str_replace($this->_relationshipTypeId
. '_', '', $this->_rtypeId
);
180 //need to assign custom data type and subtype to the template - FIXME: explain why
181 $this->assign('customDataType', 'Relationship');
182 $this->assign('customDataSubType', $this->_relationshipTypeId
);
183 $this->assign('entityID', $this->_relationshipId
);
185 //use name as it remain constant, CRM-3336
186 $this->_allRelationshipNames
= CRM_Core_PseudoConstant
::relationshipType('name');
189 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
190 if ($this->_allRelationshipNames
[$this->_relationshipTypeId
]["name_a_b"] == 'Employee of') {
191 $this->_isCurrentEmployer
= $this->_values
['contact_id_b'] == CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_values
['contact_id_a'], 'employer_id');
195 // when custom data is included in this page
196 if (!empty($_POST['hidden_custom'])) {
197 CRM_Custom_Form_CustomData
::preProcess($this);
198 CRM_Custom_Form_CustomData
::buildQuickForm($this);
199 CRM_Custom_Form_CustomData
::setDefaultValues($this);
204 * Set default values for the form.
206 public function setDefaultValues() {
207 if ($this->_cdType
) {
208 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
213 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
214 if (!empty($this->_values
)) {
215 $defaults['relationship_type_id'] = $this->_rtypeId
;
216 if (!empty($this->_values
['start_date'])) {
217 list($defaults['start_date']) = CRM_Utils_Date
::setDateDefaults($this->_values
['start_date']);
219 if (!empty($this->_values
['end_date'])) {
220 list($defaults['end_date']) = CRM_Utils_Date
::setDateDefaults($this->_values
['end_date']);
222 $defaults['description'] = CRM_Utils_Array
::value('description', $this->_values
);
223 $defaults['is_active'] = CRM_Utils_Array
::value('is_active', $this->_values
);
225 // The javascript on the form will swap these fields if it is a b_a relationship, so we compensate here
226 $defaults['is_permission_a_b'] = CRM_Utils_Array
::value('is_permission_' . $this->_rtype
, $this->_values
);
227 $defaults['is_permission_b_a'] = CRM_Utils_Array
::value('is_permission_' . strrev($this->_rtype
), $this->_values
);
229 $defaults['is_current_employer'] = $this->_isCurrentEmployer
;
231 // Load info about the related contact
232 $contact = new CRM_Contact_DAO_Contact();
233 if ($this->_rtype
== 'a_b' && $this->_values
['contact_id_a'] == $this->_contactId
) {
234 $contact->id
= $this->_values
['contact_id_b'];
237 $contact->id
= $this->_values
['contact_id_a'];
239 if ($contact->find(TRUE)) {
240 $defaults['related_contact_id'] = $contact->id
;
241 $this->_display_name_b
= $contact->display_name
;
242 $this->assign('display_name_b', $this->_display_name_b
);
246 'entity_id' => $this->_relationshipId
,
247 'entity_table' => 'civicrm_relationship',
251 $note = civicrm_api('Note', 'getsingle', $noteParams);
252 $defaults['note'] = CRM_Utils_Array
::value('note', $note);
256 $defaults['is_active'] = $defaults['is_current_employer'] = 1;
257 $defaults['relationship_type_id'] = $this->_rtypeId
;
260 $this->_enabled
= $defaults['is_active'];
265 * Add the rules for form.
267 public function addRules() {
268 if ($this->_cdType
) {
272 if (!($this->_action
& CRM_Core_Action
::DELETE
)) {
273 $this->addFormRule(array('CRM_Contact_Form_Relationship', 'dateRule'));
278 * Build the form object.
280 public function buildQuickForm() {
281 if ($this->_cdType
) {
282 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
285 if ($this->_action
& CRM_Core_Action
::DELETE
) {
286 $this->addButtons(array(
289 'name' => ts('Delete'),
294 'name' => ts('Cancel'),
300 // Just in case custom data includes a rich text field
301 $this->assign('includeWysiwygEditor', TRUE);
304 $relationshipList = CRM_Contact_BAO_Relationship
::getContactRelationshipType($this->_contactId
, $this->_rtype
, $this->_relationshipId
);
306 // Metadata needed on clientside
307 $contactTypes = CRM_Contact_BAO_ContactType
::contactTypeInfo(TRUE);
309 // Get just what we need to keep the dom small
310 $whatWeWant = array_flip(array('contact_type_a', 'contact_type_b', 'contact_sub_type_a', 'contact_sub_type_b'));
311 foreach ($this->_allRelationshipNames
as $id => $vals) {
312 if ($vals['name_a_b'] === 'Employee of') {
313 $this->assign('employmentRelationship', $id);
315 if (isset($relationshipList["{$id}_a_b"]) ||
isset($relationshipList["{$id}_b_a"])) {
316 $jsData[$id] = array_filter(array_intersect_key($this->_allRelationshipNames
[$id], $whatWeWant));
317 // Add user-friendly placeholder
318 foreach (array('a', 'b') as $x) {
319 $type = !empty($jsData[$id]["contact_sub_type_$x"]) ?
$jsData[$id]["contact_sub_type_$x"] : CRM_Utils_Array
::value("contact_type_$x", $jsData[$id]);
320 $jsData[$id]["placeholder_$x"] = $type ?
ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -');
324 $this->assign('relationshipData', $jsData);
328 'relationship_type_id',
329 ts('Relationship Type'),
330 array('' => ts('- select -')) +
$relationshipList,
332 array('class' => 'crm-select2 huge')
335 $label = $this->_action
& CRM_Core_Action
::ADD ?
ts('Contact(s)') : ts('Contact');
336 $contactField = $this->addEntityRef('related_contact_id', $label, array(
340 // This field cannot be updated
341 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
342 $contactField->freeze();
345 $this->add('advcheckbox', 'is_current_employer', $this->_contactType
== 'Organization' ?
ts('Current Employee') : ts('Current Employer'));
347 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'searchDate'));
348 $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'searchDate'));
350 $this->add('advcheckbox', 'is_active', ts('Enabled?'));
352 // CRM-14612 - Don't use adv-checkbox as it interferes with the form js
353 $this->add('checkbox', 'is_permission_a_b');
354 $this->add('checkbox', 'is_permission_b_a');
356 $this->add('text', 'description', ts('Description'), CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Relationship', 'description'));
358 CRM_Contact_Form_Edit_Notes
::buildQuickForm($this);
360 if ($this->_action
& CRM_Core_Action
::VIEW
) {
361 $this->addButtons(array(
364 'name' => ts('Done'),
369 // make this form an upload since we don't know if the custom data injected dynamically is of type file etc.
370 $this->addButtons(array(
373 'name' => ts('Save Relationship'),
378 'name' => ts('Cancel'),
385 * This function is called when the form is submitted.
387 public function postProcess() {
388 // Store the submitted values in an array.
389 $params = $this->controller
->exportValues($this->_name
);
391 // CRM-14612 - Don't use adv-checkbox as it interferes with the form js
392 $params['is_permission_a_b'] = CRM_Utils_Array
::value('is_permission_a_b', $params, 0);
393 $params['is_permission_b_a'] = CRM_Utils_Array
::value('is_permission_b_a', $params, 0);
395 // action is taken depending upon the mode
396 if ($this->_action
& CRM_Core_Action
::DELETE
) {
397 CRM_Contact_BAO_Relationship
::del($this->_relationshipId
);
400 // Since the line above nullifies the organization_name and employer_id fiels in the contact record, we need to reload all blocks to reflect this chage on the user interface.
401 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
406 $relationshipTypeParts = explode('_', $params['relationship_type_id']);
407 $params['relationship_type_id'] = $relationshipTypeParts[0];
408 if (!$this->_rtype
) {
409 // Do we need to wrap this in an if - when is rtype used & is relationship_type_id always set then?
410 $this->_rtype
= $params['relationship_type_id'];
412 $params['contact_id_' . $relationshipTypeParts[1]] = $this->_contactId
;
414 // Update mode (always single)
415 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
417 $params['id'] = $this->_relationshipId
;
418 $ids['relationship'] = $this->_relationshipId
;
419 $relation = CRM_Contact_BAO_Relationship
::getRelationshipByID($this->_relationshipId
);
420 if ($relation->contact_id_a
== $this->_contactId
) {
421 // I couldn't replicate this path in testing. See below.
422 $params['contact_id_a'] = $this->_contactId
;
423 $params['contact_id_b'] = array($params['related_contact_id']);
424 $outcome = CRM_Contact_BAO_Relationship
::createMultiple($params, $relationshipTypeParts[1]);
425 $relationshipIds = $outcome['relationship_ids'];
428 // The only reason we have changed this to use the api & not the above is that this was broken.
429 // Recommend extracting all of update into a function that uses the api
430 // and ensuring api / bao take care of 'other stuff' in this form
431 // the contact_id_a & b can't be changed on this form so don't really need setting.
432 $params['contact_id_b'] = $this->_contactId
;
433 $params['contact_id_a'] = $params['related_contact_id'];
434 $result = civicrm_api3('relationship', 'create', $params);
435 $relationshipIds = array($result['id']);
437 $ids['contactTarget'] = ($relation->contact_id_a
== $this->_contactId
) ?
$relation->contact_id_b
: $relation->contact_id_a
;
439 // @todo this belongs in the BAO.
440 if ($this->_isCurrentEmployer
) {
441 // if relationship type changes, relationship is disabled, or "current employer" is unchecked,
442 // clear the current employer. CRM-3235.
443 $relChanged = $params['relationship_type_id'] != $this->_values
['relationship_type_id'];
444 if (!$params['is_active'] ||
!$params['is_current_employer'] ||
$relChanged) {
447 // If not is_active then is_current_employer needs to be set false as well! Logically a contact cannot be a current employee of a disabled employer relationship.
448 // If this is not done, then the below process will go ahead and disable the organization_name and employer_id fields in the contact record (which is what is wanted) but then further down will be re-enabled becuase is_current_employer is not false, therefore undoing what was done correctly.
449 if (!$params['is_active']) {
450 $params['is_current_employer'] = FALSE;
453 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($this->_values
['contact_id_a']);
454 // Refresh contact summary if in ajax mode
455 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
458 if (empty($outcome['saved']) && !empty($update)) {
459 $outcome['saved'] = $update;
461 $this->setMessage($outcome);
463 // Create mode (could be 1 or more relationships)
465 $params['contact_id_' . $relationshipTypeParts[2]] = explode(',', $params['related_contact_id']);
466 $outcome = CRM_Contact_BAO_Relationship
::createMultiple($params, $relationshipTypeParts[1]);
467 $relationshipIds = $outcome['relationship_ids'];
468 if (empty($outcome['saved']) && !empty($update)) {
469 $outcome['saved'] = $update;
471 $this->setMessage($outcome);
474 // if this is called from case view,
475 //create an activity for case role removal.CRM-4480
476 // @todo this belongs in the BAO.
477 if ($this->_caseId
) {
478 CRM_Case_BAO_Case
::createCaseRoleActivity($this->_caseId
, $relationshipIds, $params['contact_check'], $this->_contactId
);
482 // @todo this belongs in the BAO.
483 if ($this->_action
& CRM_Core_Action
::UPDATE ||
$params['note']) {
484 foreach ($relationshipIds as $id) {
487 'entity_table' => 'civicrm_relationship',
489 $existing = civicrm_api3('note', 'get', $noteParams);
490 if (!empty($existing['id'])) {
491 $noteParams['id'] = $existing['id'];
493 $noteParams['note'] = $params['note'];
494 $noteParams['contact_id'] = $this->_contactId
;
495 if (!empty($existing['id']) ||
$params['note']) {
496 $action = $params['note'] ?
'create' : 'delete';
497 civicrm_api3('note', $action, $noteParams);
502 $params['relationship_ids'] = $relationshipIds;
504 // Refresh contact tabs which might have been affected
505 $this->ajaxResponse
['updateTabs'] = array(
506 '#tab_member' => CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactId
),
507 '#tab_contribute' => CRM_Contact_BAO_Contact
::getCountComponent('contribution', $this->_contactId
),
510 // Set current employee/employer relationship, CRM-3532
511 if ($params['is_current_employer'] && $this->_allRelationshipNames
[$params['relationship_type_id']]["name_a_b"] ==
513 $employerParams = array();
514 foreach ($relationshipIds as $id) {
515 // Fixme this is dumb why do we have to look this up again?
516 $rel = CRM_Contact_BAO_Relationship
::getRelationshipByID($id);
517 $employerParams[$rel->contact_id_a
] = $rel->contact_id_b
;
519 // @todo this belongs in the BAO.
520 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($employerParams);
521 // Refresh contact summary if in ajax mode
522 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
529 * @param array $params
530 * (reference ) an assoc array of name/value pairs.
533 * mixed true or array of errors
535 public static function dateRule($params) {
538 // check start and end date
539 if (!empty($params['start_date']) && !empty($params['end_date'])) {
540 $start_date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('start_date', $params));
541 $end_date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('end_date', $params));
542 if ($start_date && $end_date && (int ) $end_date < (int ) $start_date) {
543 $errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
547 return empty($errors) ?
TRUE : $errors;
551 * Set Status message to reflect outcome of the update action.
553 * @param array $outcome
554 * Outcome of save action - including
555 * - 'valid' : Number of valid relationships attempted.
556 * - 'invalid' : Number of invalid relationships attempted.
557 * - 'duplicate' : Number of duplicate relationships attempted.
558 * - 'saved' : boolean of whether save was successful
560 protected function setMessage($outcome) {
561 if (!empty($outcome['valid']) && empty($outcome['saved'])) {
562 CRM_Core_Session
::setStatus(ts('Relationship created.', array(
563 'count' => $outcome['valid'],
564 'plural' => '%count relationships created.',
565 )), ts('Saved'), 'success');
567 if (!empty($outcome['invalid'])) {
568 CRM_Core_Session
::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array(
569 'count' => $outcome['invalid'],
570 'plural' => '%count relationship records were not created due to invalid contact types.',
571 )), ts('%count invalid relationship record', array(
572 'count' => $outcome['invalid'],
573 'plural' => '%count invalid relationship records',
576 if (!empty($outcome['duplicate'])) {
577 CRM_Core_Session
::setStatus(ts('One relationship was not created because it already exists.', array(
578 'count' => $outcome['duplicate'],
579 'plural' => '%count relationships were not created because they already exist.',
580 )), ts('%count duplicate relationship', array(
581 'count' => $outcome['duplicate'],
582 'plural' => '%count duplicate relationships',
585 if (!empty($outcome['saved'])) {
586 CRM_Core_Session
::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success');