Last active
August 29, 2015 13:57
-
-
Save SugarCRMExamples/9624096 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once('modules/Contacts/ContactsApiHelper.php'); | |
// Since the ContactsApiHelper exists, we'll extend it | |
// If it didn't we would just extend the SugarBeanApiHelper | |
class CustomContactsApiHelper extends ContactsApiHelper | |
{ | |
// Mimic the SugarBeanApiHelper->formatForApi() class | |
public function formatForApi(SugarBean $bean, array $fieldList = array(), array $options = array()) | |
{ | |
// First off, call the parent class | |
$data = parent::formatForApi($bean, $fieldList, $options); | |
// Make sure they requested the top_opp field, or no field restriction at all | |
if (empty($fieldList) || in_array('top_opp', $fieldList) ) { | |
// Build a list of the fields we care about | |
static $oppFields = array( | |
'id', | |
'name', | |
'currency_id', | |
'amount', | |
'date_closed', | |
); | |
// Make sure we don't populate this some other way | |
if (!isset($bean->top_opp) && !empty($bean->id)) { | |
// Get a seed for Opportunities | |
$oppSeed = BeanFactory::newBean('Opportunities'); | |
$q = new SugarQuery(); | |
// Set the from bean | |
$q->from($oppSeed); | |
// Join in using the 'contacts' link field | |
$contactJoin = $q->join('contacts'); | |
// Limit our join to just the contact we care about | |
$q->where()->equals($contactJoin->joinName().'.id', $bean->id); | |
$q->where()->notIn('sales_stage', array('Closed Lost', 'Closed Won')); | |
// Sort by the "usdollar" amount, the normal amount field could be in | |
// different currencies and so the sorting will be all wrong. | |
$q->orderBy('amount_usdollar DESC'); | |
// Just get the top opportunity | |
$q->limit(1); | |
// Use fetchFromQuery and pass in the fields we care about | |
$beans = $oppSeed->fetchFromQuery($q, $oppFields); | |
if (count($beans) > 0) { | |
// Even though we had a limit of 1, fetchFromQuery still returns an array | |
// They are indexed by ID, so let's just fetch the first and only one | |
$bean->top_opp = array_pop($beans); | |
} else { | |
// Flag it so we know we tried to set it, there just wasn't anything there | |
$bean->top_opp = null; | |
} | |
} | |
$data['top_opp'] = array(); | |
if ($bean->top_opp != null) { | |
// getHelper will get us the helper we want | |
$data['top_opp'] = ApiHelper::getHelper($GLOBALS['service'], $bean->top_opp) | |
->formatForApi($bean->top_opp, $oppFields); | |
} | |
} | |
// formatForApi returns the bean formatted as a hash in API format | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment