Skip to content

Instantly share code, notes, and snippets.

@SugarCRMExamples
Last active August 29, 2015 13:57
Show Gist options
  • Save SugarCRMExamples/9655908 to your computer and use it in GitHub Desktop.
Save SugarCRMExamples/9655908 to your computer and use it in GitHub Desktop.
<?php
class DemoHook
{
// Called from our definition in the logic_hooks file
public function processQuery($bean, $event, $args)
{
if (!empty($args['fields']) && !in_array('top_opp',$args['fields'])) {
// They don't want the top_opp, don't process the query
return;
}
if (empty($args['beans'])) {
// There are no results to this query, don't need to process it
return;
}
// Same fields as formatForApi
static $oppFields = array(
'id',
'name',
'currency_id',
'amount',
'date_closed',
);
// The beans array is keyed by the bean id
$beanIds = array_keys($args['beans']);
// 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');
// Make sure to select the contact ID, so we can sort it out later
$q->select(array(array($contactJoin->joinName().'.id','contacts__id')));
// Fetch them by the bean id's
$q->where()->in($contactJoin->joinName().'.id', $beanIds);
$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->groupBy($contactJoin->joinName().'.id');
// Use fetchFromQuery and pass in the fields we care about
$opps = $oppSeed->fetchFromQuery($q, $oppFields, array('returnRawRows' => true));
// Raw rows are returned keyed by _rows, but we don't want to try and process
// that as a bean, so let's set them aside for later
$rows = $opps['_rows'];
unset($opps['_rows']);
// Loop through the opportunities and with the help of the raw rows link them to their contacts
foreach ($opps as $oppId => $opp) {
$contactId = $rows[$oppId]['contacts__id'];
$args['beans'][$contactId]->top_opp = $opp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment