public function actionAutoComplete($term)
{
$crit = new \CDbCriteria();
// NOTE: have commented out the address eager loading here due to column ambiguity issues with the relation definitions.
// need to investigate if this can be solved with the cunning use of scopes on the Contact model or not.
$crit->with = array('contact' => array('alias' => 'service_contact'), 'commissioning_body', 'commissioning_body.contact', 'type' => array('alias' => 'service_type'), 'commissioning_body.type' => array('alias' => 'body_type'));
$crit->compare('LOWER(t.name)', strtolower($term), true);
$crit->compare('LOWER(commissioning_body.name)', strtolower($term), true, 'OR');
$crit->addColumnCondition(array('service_type.shortname' => 'SSD'));
$crit->addColumnCondition(array('body_type.shortname' => 'LA'));
$crit->order = 'commissioning_body.name, t.name';
$results = array();
$found_bodies = array();
foreach (\CommissioningBodyService::model()->findAll($crit) as $cbs) {
$body = $cbs->commissioning_body;
$found_bodies[] = $body->id;
$results[] = array('id' => 'service' . $cbs->id, 'value' => $cbs->name . " ({$body->name})", 'service' => array('id' => $cbs->id, 'name' => $cbs->name, 'address' => $cbs->getLetterAddress(array('delimiter' => ",\n")), 'telephone' => $cbs->contact->primary_phone), 'body' => array('id' => $body->id, 'name' => $body->name, 'address' => $body->getLetterAddress(array('delimiter' => ",\n")), 'telephone' => $body->contact->primary_phone));
}
$body_crit = new \CDbCriteria();
$body_crit->with = array('type', 'contact', 'contact.correspondAddress');
$body_crit->compare('LOWER(t.name)', strtolower($term), true);
$body_crit->addNotInCondition('t.id', $found_bodies);
$body_crit->addColumnCondition(array('type.shortname' => 'LA'));
foreach (\CommissioningBody::model()->findAll($body_crit) as $body) {
$results[] = array('id' => 'body' . $body->id, 'value' => $body->name, 'body' => array('id' => $body->id, 'name' => $body->name, 'address' => $body->getLetterAddress(array('delimiter' => ",\n")), 'telephone' => $body->contact->primary_phone));
}
echo json_encode($results);
}