Friday, January 30, 2009

CakePHP : AfterFind()

Rather than hacking the view to check if the number in my Inbox or Outbox table tally with my Contacts number, I use the afterModel() hack.

The Inbox Model


class Inbox extends AppModel {
var $name = 'Inbox';
var $useTable = 'inbox';
var $order = 'Inbox.id DESC';

function afterFind($results) {

// load Contact model here
App::import('Model','Contact');
$this->Contact = new Contact();

// For any results returned from the 'Inbox' model, take 'number' and check with Contact model
foreach ($results as $key => $val) {
if(!empty( $val['Inbox']['number'] )) {
if ( $contact_id = $this->Contact->findByMobileNumber($val['Inbox']['number'],array('id','name')) ){
$results[$key]['Inbox']['contact_id'] = $contact_id['Contact']['id'];
$results[$key]['Inbox']['contact_name'] = $contact_id['Contact']['name'];
}
}
}
return $results;
}

}


Try the output in view


Array
(
[Inbox] => Array
(
[id] => 266
[number] => +60146412911
[smsdate] => 2009-01-30 15:02:06
[insertdate] => 2009-01-30 15:02:25
[text] => test1243
[phone] =>
[processed] => 0
[read] => 1
[contact_id] => 14
[contact_name] => Bazet
)


Clean hack

)

No comments:

Post a Comment