Last active
December 8, 2017 05:21
-
-
Save esimonetti/8458d74a4a1f8d8106e603f718c9c125 to your computer and use it in GitHub Desktop.
Sample customised filter api to help find Notes that are related to multiple Contacts at the same time, with a custom many to many relationship
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 | |
// Enrico Simonetti | |
// enricosimonetti.com | |
// | |
// 2017-12-08 tested on Sugar 7.9.2.0 | |
// Sample customised filter api to help find Notes that are related to multiple Contacts at the same time, with a custom many to many relationship | |
// eg: {{url}}/rest/v10/Notes?contact_id[]=<first id>&contact_id[]=<second id> will only return Notes that are related to both contacts at the same time | |
// | |
// file: custom/modules/Notes/clients/base/api/CustomNotesFilterApi.php | |
class CustomNotesFilterApi extends FilterApi | |
{ | |
public function registerApiRest() | |
{ | |
return parent::registerApiRest(); | |
} | |
public function filterListSetup(ServiceBase $api, array $args, $acl = 'list') | |
{ | |
$original_output = parent::filterListSetup($api, $args, $acl); | |
if(!empty($args['contact_id'])) { | |
$contact_ids = array_unique($args['contact_id']); | |
$table_name = 'notes_contacts_1_c'; | |
$contacts_id_field_name = 'notes_contacts_1contacts_idb'; | |
$notes_id_field_name = 'notes_contacts_1notes_ida'; | |
$q = new SugarQuery(); | |
$q->from(BeanFactory::getBean('Notes')); | |
$q->select->field(array(array('notes.id', 'note_id'))); | |
$q->select->fieldRaw('cntct.'.$contacts_id_field_name, 'contact_id'); | |
$q->joinTable($table_name, | |
array( | |
'alias' => 'cntct', | |
'joinType' => 'inner', | |
) | |
)->on()->equalsField('cntct.'.$notes_id_field_name, 'notes.id')->equals('cntct.deleted', 0) | |
->in('cntct.'.$contacts_id_field_name, $contact_ids); | |
//$compiled = $q->compile(); | |
//$GLOBALS['log']->fatal($compiled->getSQL().' '.print_r($compiled->getParameters(), true)); | |
$records = $q->execute(); | |
$to_query = array(); | |
$grouped_records = array(); | |
if(!empty($records)) { | |
foreach($records as $record) { | |
$grouped_records[$record['note_id']][] = array($record['contact_id'] => $record['contact_id']); | |
} | |
if(!empty($grouped_records)) { | |
foreach($grouped_records as $key => $grouped_record) { | |
if(count($grouped_record) == count($contact_ids)) { | |
$to_query[$key] = $key; | |
} | |
} | |
} | |
} | |
// add my condition, even if empty (means no matches, and should show no records) | |
$original_output['1']->where->in('id', $to_query); | |
} | |
return $original_output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment