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
112 * Explicitly declare the form context.
114 public function getDefaultContext() {
119 * Explicitly declare the entity api name.
121 public function getDefaultEntity() {
122 return 'Relationship';
125 public function preProcess() {
126 //custom data related code
127 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
128 $this->assign('cdType', FALSE);
129 if ($this->_cdType
) {
130 $this->assign('cdType', TRUE);
131 return CRM_Custom_Form_CustomData
::preProcess($this);
134 $this->_contactId
= $this->get('contactId');
136 $this->_contactType
= CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId
, 'contact_type');
138 $this->_relationshipId
= $this->get('id');
140 $this->_rtype
= CRM_Utils_Request
::retrieve('rtype', 'String', $this);
142 $this->_rtypeId
= CRM_Utils_Request
::retrieve('relTypeId', 'String', $this);
144 $this->_display_name_a
= CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId
, 'display_name');
146 $this->assign('display_name_a', $this->_display_name_a
);
148 // Set page title based on action
149 switch ($this->_action
) {
150 case CRM_Core_Action
::VIEW
:
151 CRM_Utils_System
::setTitle(ts('View Relationship for %1', array(1 => $this->_display_name_a
)));
154 case CRM_Core_Action
::ADD
:
155 CRM_Utils_System
::setTitle(ts('Add Relationship for %1', array(1 => $this->_display_name_a
)));
158 case CRM_Core_Action
::UPDATE
:
159 CRM_Utils_System
::setTitle(ts('Edit Relationship for %1', array(1 => $this->_display_name_a
)));
162 case CRM_Core_Action
::DELETE
:
163 CRM_Utils_System
::setTitle(ts('Delete Relationship for %1', array(1 => $this->_display_name_a
)));
167 $this->_caseId
= CRM_Utils_Request
::retrieve('caseID', 'Integer', $this);
169 //get the relationship values.
170 $this->_values
= array();
171 if ($this->_relationshipId
) {
172 $params = array('id' => $this->_relationshipId
);
173 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Relationship', $params, $this->_values
);
176 if (!$this->_rtypeId
) {
177 $params = $this->controller
->exportValues($this->_name
);
178 if (isset($params['relationship_type_id'])) {
179 $this->_rtypeId
= $params['relationship_type_id'];
181 elseif (!empty($this->_values
)) {
182 $this->_rtypeId
= $this->_values
['relationship_type_id'] . '_' . $this->_rtype
;
186 //get the relationship type id
187 $this->_relationshipTypeId
= str_replace(array('_a_b', '_b_a'), array('', ''), $this->_rtypeId
);
189 //get the relationship type
190 if (!$this->_rtype
) {
191 $this->_rtype
= str_replace($this->_relationshipTypeId
. '_', '', $this->_rtypeId
);
194 //need to assign custom data type and subtype to the template - FIXME: explain why
195 $this->assign('customDataType', 'Relationship');
196 $this->assign('customDataSubType', $this->_relationshipTypeId
);
197 $this->assign('entityID', $this->_relationshipId
);
199 //use name as it remain constant, CRM-3336
200 $this->_allRelationshipNames
= CRM_Core_PseudoConstant
::relationshipType('name');
203 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
204 if ($this->_allRelationshipNames
[$this->_relationshipTypeId
]["name_a_b"] == 'Employee of') {
205 $this->_isCurrentEmployer
= $this->_values
['contact_id_b'] == CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_values
['contact_id_a'], 'employer_id');
209 // when custom data is included in this page
210 if (!empty($_POST['hidden_custom'])) {
211 CRM_Custom_Form_CustomData
::preProcess($this);
212 CRM_Custom_Form_CustomData
::buildQuickForm($this);
213 CRM_Custom_Form_CustomData
::setDefaultValues($this);
218 * Set default values for the form.
220 public function setDefaultValues() {
221 if ($this->_cdType
) {
222 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
227 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
228 if (!empty($this->_values
)) {
229 $defaults['relationship_type_id'] = $this->_rtypeId
;
230 if (!empty($this->_values
['start_date'])) {
231 list($defaults['start_date']) = CRM_Utils_Date
::setDateDefaults($this->_values
['start_date']);
233 if (!empty($this->_values
['end_date'])) {
234 list($defaults['end_date']) = CRM_Utils_Date
::setDateDefaults($this->_values
['end_date']);
236 $defaults['description'] = CRM_Utils_Array
::value('description', $this->_values
);
237 $defaults['is_active'] = CRM_Utils_Array
::value('is_active', $this->_values
);
239 // The javascript on the form will swap these fields if it is a b_a relationship, so we compensate here
240 $defaults['is_permission_a_b'] = CRM_Utils_Array
::value('is_permission_' . $this->_rtype
, $this->_values
);
241 $defaults['is_permission_b_a'] = CRM_Utils_Array
::value('is_permission_' . strrev($this->_rtype
), $this->_values
);
243 $defaults['is_current_employer'] = $this->_isCurrentEmployer
;
245 // Load info about the related contact
246 $contact = new CRM_Contact_DAO_Contact();
247 if ($this->_rtype
== 'a_b' && $this->_values
['contact_id_a'] == $this->_contactId
) {
248 $contact->id
= $this->_values
['contact_id_b'];
251 $contact->id
= $this->_values
['contact_id_a'];
253 if ($contact->find(TRUE)) {
254 $defaults['related_contact_id'] = $contact->id
;
255 $this->_display_name_b
= $contact->display_name
;
256 $this->assign('display_name_b', $this->_display_name_b
);
260 'entity_id' => $this->_relationshipId
,
261 'entity_table' => 'civicrm_relationship',
265 $note = civicrm_api('Note', 'getsingle', $noteParams);
266 $defaults['note'] = CRM_Utils_Array
::value('note', $note);
270 $defaults['is_active'] = $defaults['is_current_employer'] = 1;
271 $defaults['relationship_type_id'] = $this->_rtypeId
;
274 $this->_enabled
= $defaults['is_active'];
279 * Add the rules for form.
281 public function addRules() {
282 if ($this->_cdType
) {
286 if (!($this->_action
& CRM_Core_Action
::DELETE
)) {
287 $this->addFormRule(array('CRM_Contact_Form_Relationship', 'dateRule'));
292 * Build the form object.
294 public function buildQuickForm() {
295 if ($this->_cdType
) {
296 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
299 if ($this->_action
& CRM_Core_Action
::DELETE
) {
300 $this->addButtons(array(
303 'name' => ts('Delete'),
308 'name' => ts('Cancel'),
316 $relationshipList = CRM_Contact_BAO_Relationship
::getContactRelationshipType($this->_contactId
, $this->_rtype
, $this->_relationshipId
);
318 // Metadata needed on clientside
319 $contactTypes = CRM_Contact_BAO_ContactType
::contactTypeInfo(TRUE);
321 // Get just what we need to keep the dom small
322 $whatWeWant = array_flip(array('contact_type_a', 'contact_type_b', 'contact_sub_type_a', 'contact_sub_type_b'));
323 foreach ($this->_allRelationshipNames
as $id => $vals) {
324 if ($vals['name_a_b'] === 'Employee of') {
325 $this->assign('employmentRelationship', $id);
327 if (isset($relationshipList["{$id}_a_b"]) ||
isset($relationshipList["{$id}_b_a"])) {
328 $jsData[$id] = array_filter(array_intersect_key($this->_allRelationshipNames
[$id], $whatWeWant));
329 // Add user-friendly placeholder
330 foreach (array('a', 'b') as $x) {
331 $type = !empty($jsData[$id]["contact_sub_type_$x"]) ?
$jsData[$id]["contact_sub_type_$x"] : CRM_Utils_Array
::value("contact_type_$x", $jsData[$id]);
332 $jsData[$id]["placeholder_$x"] = $type ?
ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -');
336 $this->assign('relationshipData', $jsData);
338 $this->addField('relationship_type_id', array('options' => array('' => ts('- select -')) +
$relationshipList, 'class' => 'huge', 'placeholder' => '- select -'), TRUE);
340 $label = $this->_action
& CRM_Core_Action
::ADD ?
ts('Contact(s)') : ts('Contact');
341 $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE);
342 // This field cannot be updated
343 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
344 $contactField->freeze();
347 $this->add('advcheckbox', 'is_current_employer', $this->_contactType
== 'Organization' ?
ts('Current Employee') : ts('Current Employer'));
349 $this->addField('start_date', array('label' => ts('Start Date'), 'formatType' => 'searchDate'));
350 $this->addField('end_date', array('label' => ts('End Date'), 'formatType' => 'searchDate'));
352 $this->addField('is_active', array('label' => ts('Enabled?')));
354 $this->addField('is_permission_a_b');
355 $this->addField('is_permission_b_a');
357 $this->addField('description', array('label' => ts('Description')));
359 CRM_Contact_Form_Edit_Notes
::buildQuickForm($this);
361 if ($this->_action
& CRM_Core_Action
::VIEW
) {
362 $this->addButtons(array(
365 'name' => ts('Done'),
370 // make this form an upload since we don't know if the custom data injected dynamically is of type file etc.
371 $this->addButtons(array(
374 'name' => ts('Save Relationship'),
379 'name' => ts('Cancel'),
386 * This function is called when the form is submitted.
388 public function postProcess() {
389 // Store the submitted values in an array.
390 $params = $this->controller
->exportValues($this->_name
);
392 // CRM-14612 - Don't use adv-checkbox as it interferes with the form js
393 $params['is_permission_a_b'] = CRM_Utils_Array
::value('is_permission_a_b', $params, 0);
394 $params['is_permission_b_a'] = CRM_Utils_Array
::value('is_permission_b_a', $params, 0);
396 // action is taken depending upon the mode
397 if ($this->_action
& CRM_Core_Action
::DELETE
) {
398 CRM_Contact_BAO_Relationship
::del($this->_relationshipId
);
401 // 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.
402 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
407 $relationshipTypeParts = explode('_', $params['relationship_type_id']);
408 $params['relationship_type_id'] = $relationshipTypeParts[0];
409 if (!$this->_rtype
) {
410 // Do we need to wrap this in an if - when is rtype used & is relationship_type_id always set then?
411 $this->_rtype
= $params['relationship_type_id'];
413 $params['contact_id_' . $relationshipTypeParts[1]] = $this->_contactId
;
415 // Update mode (always single)
416 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
418 $params['id'] = $this->_relationshipId
;
419 $ids['relationship'] = $this->_relationshipId
;
420 $relation = CRM_Contact_BAO_Relationship
::getRelationshipByID($this->_relationshipId
);
421 if ($relation->contact_id_a
== $this->_contactId
) {
422 // I couldn't replicate this path in testing. See below.
423 $params['contact_id_a'] = $this->_contactId
;
424 $params['contact_id_b'] = array($params['related_contact_id']);
425 $outcome = CRM_Contact_BAO_Relationship
::createMultiple($params, $relationshipTypeParts[1]);
426 $relationshipIds = $outcome['relationship_ids'];
429 // The only reason we have changed this to use the api & not the above is that this was broken.
430 // Recommend extracting all of update into a function that uses the api
431 // and ensuring api / bao take care of 'other stuff' in this form
432 // the contact_id_a & b can't be changed on this form so don't really need setting.
433 $params['contact_id_b'] = $this->_contactId
;
434 $params['contact_id_a'] = $params['related_contact_id'];
435 $result = civicrm_api3('relationship', 'create', $params);
436 $relationshipIds = array($result['id']);
438 $ids['contactTarget'] = ($relation->contact_id_a
== $this->_contactId
) ?
$relation->contact_id_b
: $relation->contact_id_a
;
440 // @todo this belongs in the BAO.
441 if ($this->_isCurrentEmployer
) {
442 // if relationship type changes, relationship is disabled, or "current employer" is unchecked,
443 // clear the current employer. CRM-3235.
444 $relChanged = $params['relationship_type_id'] != $this->_values
['relationship_type_id'];
445 if (!$params['is_active'] ||
!$params['is_current_employer'] ||
$relChanged) {
448 // 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.
449 // 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.
450 if (!$params['is_active']) {
451 $params['is_current_employer'] = FALSE;
454 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($this->_values
['contact_id_a']);
455 // Refresh contact summary if in ajax mode
456 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
459 if (empty($outcome['saved']) && !empty($update)) {
460 $outcome['saved'] = $update;
462 $this->setMessage($outcome);
464 // Create mode (could be 1 or more relationships)
466 $params['contact_id_' . $relationshipTypeParts[2]] = explode(',', $params['related_contact_id']);
467 $outcome = CRM_Contact_BAO_Relationship
::createMultiple($params, $relationshipTypeParts[1]);
468 $relationshipIds = $outcome['relationship_ids'];
469 if (empty($outcome['saved']) && !empty($update)) {
470 $outcome['saved'] = $update;
472 $this->setMessage($outcome);
475 // if this is called from case view,
476 //create an activity for case role removal.CRM-4480
477 // @todo this belongs in the BAO.
478 if ($this->_caseId
) {
479 CRM_Case_BAO_Case
::createCaseRoleActivity($this->_caseId
, $relationshipIds, $params['contact_check'], $this->_contactId
);
483 // @todo this belongs in the BAO.
484 if ($this->_action
& CRM_Core_Action
::UPDATE ||
$params['note']) {
485 foreach ($relationshipIds as $id) {
488 'entity_table' => 'civicrm_relationship',
490 $existing = civicrm_api3('note', 'get', $noteParams);
491 if (!empty($existing['id'])) {
492 $noteParams['id'] = $existing['id'];
494 $noteParams['note'] = $params['note'];
495 $noteParams['contact_id'] = $this->_contactId
;
496 if (!empty($existing['id']) ||
$params['note']) {
497 $action = $params['note'] ?
'create' : 'delete';
498 civicrm_api3('note', $action, $noteParams);
503 $params['relationship_ids'] = $relationshipIds;
505 // Refresh contact tabs which might have been affected
506 $this->ajaxResponse
['updateTabs'] = array(
507 '#tab_member' => CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactId
),
508 '#tab_contribute' => CRM_Contact_BAO_Contact
::getCountComponent('contribution', $this->_contactId
),
511 // Set current employee/employer relationship, CRM-3532
512 if ($params['is_current_employer'] && $this->_allRelationshipNames
[$params['relationship_type_id']]["name_a_b"] ==
514 $employerParams = array();
515 foreach ($relationshipIds as $id) {
516 // Fixme this is dumb why do we have to look this up again?
517 $rel = CRM_Contact_BAO_Relationship
::getRelationshipByID($id);
518 $employerParams[$rel->contact_id_a
] = $rel->contact_id_b
;
520 // @todo this belongs in the BAO.
521 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($employerParams);
522 // Refresh contact summary if in ajax mode
523 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
530 * @param array $params
531 * (reference ) an assoc array of name/value pairs.
534 * mixed true or array of errors
536 public static function dateRule($params) {
539 // check start and end date
540 if (!empty($params['start_date']) && !empty($params['end_date'])) {
541 $start_date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('start_date', $params));
542 $end_date = CRM_Utils_Date
::format(CRM_Utils_Array
::value('end_date', $params));
543 if ($start_date && $end_date && (int ) $end_date < (int ) $start_date) {
544 $errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
548 return empty($errors) ?
TRUE : $errors;
552 * Set Status message to reflect outcome of the update action.
554 * @param array $outcome
555 * Outcome of save action - including
556 * - 'valid' : Number of valid relationships attempted.
557 * - 'invalid' : Number of invalid relationships attempted.
558 * - 'duplicate' : Number of duplicate relationships attempted.
559 * - 'saved' : boolean of whether save was successful
561 protected function setMessage($outcome) {
562 if (!empty($outcome['valid']) && empty($outcome['saved'])) {
563 CRM_Core_Session
::setStatus(ts('Relationship created.', array(
564 'count' => $outcome['valid'],
565 'plural' => '%count relationships created.',
566 )), ts('Saved'), 'success');
568 if (!empty($outcome['invalid'])) {
569 CRM_Core_Session
::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array(
570 'count' => $outcome['invalid'],
571 'plural' => '%count relationship records were not created due to invalid contact types.',
572 )), ts('%count invalid relationship record', array(
573 'count' => $outcome['invalid'],
574 'plural' => '%count invalid relationship records',
577 if (!empty($outcome['duplicate'])) {
578 CRM_Core_Session
::setStatus(ts('One relationship was not created because it already exists.', array(
579 'count' => $outcome['duplicate'],
580 'plural' => '%count relationships were not created because they already exist.',
581 )), ts('%count duplicate relationship', array(
582 'count' => $outcome['duplicate'],
583 'plural' => '%count duplicate relationships',
586 if (!empty($outcome['saved'])) {
587 CRM_Core_Session
::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success');