3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
107 * Explicitly declare the form context.
109 public function getDefaultContext() {
114 * Explicitly declare the entity api name.
116 public function getDefaultEntity() {
117 return 'Relationship';
120 public function preProcess() {
121 $this->_contactId
= $this->get('contactId');
123 $this->_contactType
= CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId
, 'contact_type');
125 $this->_relationshipId
= $this->get('id');
127 $this->_rtype
= CRM_Utils_Request
::retrieve('rtype', 'String', $this);
129 $this->_rtypeId
= CRM_Utils_Request
::retrieve('relTypeId', 'String', $this);
131 $this->_display_name_a
= CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId
, 'display_name');
133 $this->assign('display_name_a', $this->_display_name_a
);
134 //get the relationship values.
135 $this->_values
= array();
136 if ($this->_relationshipId
) {
137 $params = array('id' => $this->_relationshipId
);
138 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Relationship', $params, $this->_values
);
141 // Check for permissions
142 if (in_array($this->_action
, array(CRM_Core_Action
::ADD
, CRM_Core_Action
::UPDATE
, CRM_Core_Action
::DELETE
))) {
143 if (!CRM_Contact_BAO_Contact_Permission
::allow($this->_contactId
, CRM_Core_Permission
::EDIT
)
144 && !CRM_Contact_BAO_Contact_Permission
::allow($this->_values
['contact_id_b'], CRM_Core_Permission
::EDIT
)) {
145 CRM_Core_Error
::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
149 // Set page title based on action
150 switch ($this->_action
) {
151 case CRM_Core_Action
::VIEW
:
152 CRM_Utils_System
::setTitle(ts('View Relationship for %1', array(1 => $this->_display_name_a
)));
155 case CRM_Core_Action
::ADD
:
156 CRM_Utils_System
::setTitle(ts('Add Relationship for %1', array(1 => $this->_display_name_a
)));
159 case CRM_Core_Action
::UPDATE
:
160 CRM_Utils_System
::setTitle(ts('Edit Relationship for %1', array(1 => $this->_display_name_a
)));
163 case CRM_Core_Action
::DELETE
:
164 CRM_Utils_System
::setTitle(ts('Delete Relationship for %1', array(1 => $this->_display_name_a
)));
168 $this->_caseId
= CRM_Utils_Request
::retrieve('caseID', 'Integer', $this);
170 if (!$this->_rtypeId
) {
171 $params = CRM_Utils_Request
::exportValues();
172 if (isset($params['relationship_type_id'])) {
173 $this->_rtypeId
= $params['relationship_type_id'];
175 elseif (!empty($this->_values
)) {
176 $this->_rtypeId
= $this->_values
['relationship_type_id'] . '_' . $this->_rtype
;
180 //get the relationship type id
181 $this->_relationshipTypeId
= str_replace(array('_a_b', '_b_a'), array('', ''), $this->_rtypeId
);
183 //get the relationship type
184 if (!$this->_rtype
) {
185 $this->_rtype
= str_replace($this->_relationshipTypeId
. '_', '', $this->_rtypeId
);
188 //need to assign custom data type and subtype to the template - FIXME: explain why
189 $this->assign('customDataType', 'Relationship');
190 $this->assign('customDataSubType', $this->_relationshipTypeId
);
191 $this->assign('entityID', $this->_relationshipId
);
193 //use name as it remain constant, CRM-3336
194 $this->_allRelationshipNames
= CRM_Core_PseudoConstant
::relationshipType('name');
197 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
198 if ($this->_allRelationshipNames
[$this->_relationshipTypeId
]["name_a_b"] == 'Employee of') {
199 $this->_isCurrentEmployer
= $this->_values
['contact_id_b'] == CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_values
['contact_id_a'], 'employer_id');
203 // when custom data is included in this page
204 if (!empty($_POST['hidden_custom'])) {
205 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $this->_relationshipTypeId
, 1, 'Relationship', $this->_relationshipId
);
206 CRM_Custom_Form_CustomData
::buildQuickForm($this);
207 CRM_Custom_Form_CustomData
::setDefaultValues($this);
212 * Set default values for the form.
214 public function setDefaultValues() {
217 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
218 if (!empty($this->_values
)) {
219 $defaults['relationship_type_id'] = $this->_rtypeId
;
220 $defaults['start_date'] = CRM_Utils_Array
::value('start_date', $this->_values
);
221 $defaults['end_date'] = CRM_Utils_Array
::value('end_date', $this->_values
);
222 $defaults['description'] = CRM_Utils_Array
::value('description', $this->_values
);
223 $defaults['is_active'] = CRM_Utils_Array
::value('is_active', $this->_values
);
225 // The postprocess function 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
;
258 $defaults['is_permission_a_b'] = $defaults['is_permission_b_a'] = CRM_Contact_BAO_Relationship
::NONE
;
261 $this->_enabled
= $defaults['is_active'];
266 * Add the rules for form.
268 public function addRules() {
269 if (!($this->_action
& CRM_Core_Action
::DELETE
)) {
270 $this->addFormRule(array('CRM_Contact_Form_Relationship', 'dateRule'));
275 * Build the form object.
277 public function buildQuickForm() {
278 if ($this->_action
& CRM_Core_Action
::DELETE
) {
279 $this->addButtons(array(
282 'name' => ts('Delete'),
287 'name' => ts('Cancel'),
295 $relationshipList = CRM_Contact_BAO_Relationship
::getContactRelationshipType($this->_contactId
, $this->_rtype
, $this->_relationshipId
);
297 $this->assign('contactTypes', CRM_Contact_BAO_ContactType
::contactTypeInfo(TRUE));
299 foreach ($this->_allRelationshipNames
as $id => $vals) {
300 if ($vals['name_a_b'] === 'Employee of') {
301 $this->assign('employmentRelationship', $id);
307 'relationship_type_id',
309 'options' => array('' => ts('- select -')) +
$relationshipList,
311 'placeholder' => '- select -',
312 'option_url' => 'civicrm/admin/reltype',
313 'option_context' => array(
314 'contact_id' => $this->_contactId
,
315 'relationship_direction' => $this->_rtype
,
316 'relationship_id' => $this->_relationshipId
,
323 $label = $this->_action
& CRM_Core_Action
::ADD ?
ts('Contact(s)') : ts('Contact');
324 $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE);
325 // This field cannot be updated
326 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
327 $contactField->freeze();
330 $this->add('advcheckbox', 'is_current_employer', $this->_contactType
== 'Organization' ?
ts('Current Employee') : ts('Current Employer'));
332 $this->addField('start_date', array('label' => ts('Start Date')), FALSE, FALSE);
333 $this->addField('end_date', array('label' => ts('End Date')), FALSE, FALSE);
335 $this->addField('is_active', array('label' => ts('Enabled?'), 'type' => 'advcheckbox'));
337 $this->addField('is_permission_a_b', array(), TRUE);
338 $this->addField('is_permission_b_a', array(), TRUE);
340 $this->addField('description', array('label' => ts('Description')));
342 CRM_Contact_Form_Edit_Notes
::buildQuickForm($this);
344 if ($this->_action
& CRM_Core_Action
::VIEW
) {
345 $this->addButtons(array(
348 'name' => ts('Done'),
353 // make this form an upload since we don't know if the custom data injected dynamically is of type file etc.
354 $this->addButtons(array(
357 'name' => ts('Save Relationship'),
362 'name' => ts('Cancel'),
369 * This function is called when the form is submitted and also from unit test.
371 * @param array $params
374 * @throws \CRM_Core_Exception
376 public function submit($params) {
377 switch ($this->getAction()) {
378 case CRM_Core_Action
::DELETE
:
379 $this->deleteAction($this->_relationshipId
);
382 case CRM_Core_Action
::UPDATE
:
383 return $this->updateAction($params);
386 return $this->createAction($params);
391 * This function is called when the form is submitted.
393 public function postProcess() {
394 // Store the submitted values in an array.
395 $params = $this->controller
->exportValues($this->_name
);
397 $values = $this->submit($params);
398 if (empty($values)) {
401 list ($params, $relationshipIds) = $values;
403 // if this is called from case view,
404 //create an activity for case role removal.CRM-4480
405 // @todo this belongs in the BAO.
406 if ($this->_caseId
) {
407 CRM_Case_BAO_Case
::createCaseRoleActivity($this->_caseId
, $relationshipIds, $params['contact_check'], $this->_contactId
);
410 // @todo this belongs in the BAO.
411 $note = !empty($params['note']) ?
$params['note'] : '';
412 $this->saveRelationshipNotes($relationshipIds, $note);
414 $this->setEmploymentRelationship($params, $relationshipIds);
416 // Refresh contact tabs which might have been affected
417 $this->ajaxResponse
= array(
418 'reloadBlocks' => array('#crm-contactinfo-content'),
419 'updateTabs' => array(
420 '#tab_member' => CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactId
),
421 '#tab_contribute' => CRM_Contact_BAO_Contact
::getCountComponent('contribution', $this->_contactId
),
429 * @param array $params
430 * (reference ) an assoc array of name/value pairs.
433 * mixed true or array of errors
435 public static function dateRule($params) {
438 // check start and end date
439 if (!empty($params['start_date']) && !empty($params['end_date'])) {
440 if ($params['end_date'] < $params['start_date']) {
441 $errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
445 return empty($errors) ?
TRUE : $errors;
449 * Set Status message to reflect outcome of the update action.
451 * @param array $outcome
452 * Outcome of save action - including
453 * - 'valid' : Number of valid relationships attempted.
454 * - 'invalid' : Number of invalid relationships attempted.
455 * - 'duplicate' : Number of duplicate relationships attempted.
456 * - 'saved' : boolean of whether save was successful
458 protected function setMessage($outcome) {
459 if (!empty($outcome['valid']) && empty($outcome['saved'])) {
460 CRM_Core_Session
::setStatus(ts('Relationship created.', array(
461 'count' => $outcome['valid'],
462 'plural' => '%count relationships created.',
463 )), ts('Saved'), 'success');
465 if (!empty($outcome['invalid'])) {
466 CRM_Core_Session
::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array(
467 'count' => $outcome['invalid'],
468 'plural' => '%count relationship records were not created due to invalid contact types.',
469 )), ts('%count invalid relationship record', array(
470 'count' => $outcome['invalid'],
471 'plural' => '%count invalid relationship records',
474 if (!empty($outcome['duplicate'])) {
475 CRM_Core_Session
::setStatus(ts('One relationship was not created because it already exists.', array(
476 'count' => $outcome['duplicate'],
477 'plural' => '%count relationships were not created because they already exist.',
478 )), ts('%count duplicate relationship', array(
479 'count' => $outcome['duplicate'],
480 'plural' => '%count duplicate relationships',
483 if (!empty($outcome['saved'])) {
484 CRM_Core_Session
::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success');
489 * @param $relationshipList
493 public static function getRelationshipTypeMetadata($relationshipList) {
494 $contactTypes = CRM_Contact_BAO_ContactType
::contactTypeInfo(TRUE);
495 $allRelationshipNames = CRM_Core_PseudoConstant
::relationshipType('name');
497 // Get just what we need to keep the dom small
498 $whatWeWant = array_flip(array(
501 'contact_sub_type_a',
502 'contact_sub_type_b',
504 foreach ($allRelationshipNames as $id => $vals) {
505 if (isset($relationshipList["{$id}_a_b"]) ||
isset($relationshipList["{$id}_b_a"])) {
506 $jsData[$id] = array_filter(array_intersect_key($allRelationshipNames[$id], $whatWeWant));
507 // Add user-friendly placeholder
508 foreach (array('a', 'b') as $x) {
509 $type = !empty($jsData[$id]["contact_sub_type_$x"]) ?
$jsData[$id]["contact_sub_type_$x"] : CRM_Utils_Array
::value("contact_type_$x", $jsData[$id]);
510 $jsData[$id]["placeholder_$x"] = $type ?
ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -');
518 * Handling 'delete relationship' action
523 private function deleteAction($id) {
524 CRM_Contact_BAO_Relationship
::del($id);
526 // reload all blocks to reflect this change on the user interface.
527 $this->ajaxResponse
['reloadBlocks'] = array('#crm-contactinfo-content');
531 * Handling updating relationship action
533 * @param array $params
536 * @throws \CRM_Core_Exception
538 private function updateAction($params) {
539 list($params, $_) = $this->preparePostProcessParameters($params);
541 civicrm_api3('relationship', 'create', $params);
543 catch (CiviCRM_API3_Exception
$e) {
544 throw new CRM_Core_Exception('Relationship create error ' . $e->getMessage());
547 $this->setMessage(array('saved' => TRUE));
548 return array($params, array($this->_relationshipId
));
552 * Handling creating relationship action
554 * @param array $params
557 * @throws \CRM_Core_Exception
559 private function createAction($params) {
560 list($params, $primaryContactLetter) = $this->preparePostProcessParameters($params);
562 $outcome = CRM_Contact_BAO_Relationship
::createMultiple($params, $primaryContactLetter);
564 $relationshipIds = $outcome['relationship_ids'];
566 $this->setMessage($outcome);
568 return array($params, $relationshipIds);
573 * Prepares parameters to be used for create/update actions
575 * @param array $values
579 private function preparePostProcessParameters($values) {
581 list($relationshipTypeId, $a, $b) = explode('_', $params['relationship_type_id']);
583 $params['relationship_type_id'] = $relationshipTypeId;
584 $params['contact_id_' . $a] = $this->_contactId
;
586 if (empty($this->_relationshipId
)) {
587 $params['contact_id_' . $b] = explode(',', $params['related_contact_id']);
590 $params['id'] = $this->_relationshipId
;
591 $params['contact_id_' . $b] = $params['related_contact_id'];
594 // If this is a b_a relationship these form elements are flipped
595 $params['is_permission_a_b'] = CRM_Utils_Array
::value("is_permission_{$a}_{$b}", $values, 0);
596 $params['is_permission_b_a'] = CRM_Utils_Array
::value("is_permission_{$b}_{$a}", $values, 0);
598 return array($params, $a);
602 * Updates/Creates relationship notes
604 * @param array $relationshipIds
605 * @param string $note
607 * @throws \CiviCRM_API3_Exception
609 private function saveRelationshipNotes($relationshipIds, $note) {
610 foreach ($relationshipIds as $id) {
613 'entity_table' => 'civicrm_relationship',
616 $existing = civicrm_api3('note', 'get', $noteParams);
617 if (!empty($existing['id'])) {
618 $noteParams['id'] = $existing['id'];
624 $noteParams['note'] = $note;
625 $noteParams['contact_id'] = $this->_contactId
;
627 elseif (!empty($noteParams['id'])) {
631 if (!empty($action)) {
632 civicrm_api3('note', $action, $noteParams);
638 * Sets current employee/employer relationship
641 * @param array $relationshipIds
643 private function setEmploymentRelationship($params, $relationshipIds) {
644 $employerParams = array();
645 foreach ($relationshipIds as $id) {
646 if (!CRM_Contact_BAO_Relationship
::isCurrentEmployerNeedingToBeCleared($params, $id)
647 //don't think this is required to check again.
648 && $this->_allRelationshipNames
[$params['relationship_type_id']]["name_a_b"] == 'Employee of') {
649 // Fixme this is dumb why do we have to look this up again?
650 $rel = CRM_Contact_BAO_Relationship
::getRelationshipByID($id);
651 $employerParams[$rel->contact_id_a
] = $rel->contact_id_b
;
654 if (!empty($employerParams)) {
655 // @todo this belongs in the BAO.
656 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($employerParams);