3.7.7.2 afterFind
afterFind(array $results, bool $primary)
Use this callback to modify results that have been returned from a find operation, or to perform any other post-find logic. The $results parameter passed to this callback contains the returned results from the model's find operation, i.e. something like:
$results = array(
0 => array(
'ModelName' => array(
'field1' => 'value1',
'field2' => 'value2',
),
),
);
$results = array(0 => array('ModelName' => array('field1' => 'value1','field2' => 'value2',),),);
The return value for this callback should be the (possibly modified) results for the find operation that triggered this callback.
The $primary parameter indicates whether or not the current model was the model that the query originated on or whether or not this model was queried as an association. If a model is queried as an association the format of $results can differ; instead of the result you would normally get from a find
operation, you may get this:
$results = array( 'field_1' => 'value1', 'field_2' => 'value2' );
$results = array('field_1' => 'value1','field_2' => 'value2');
Code expecting $primary to be true will probably get a "Cannot use string offset as
an array" fatal error from PHP if a recursive find is used.
Below is an example of how afterfind can be used for date formating.
function afterFind($results) {
foreach ($results as $key => $val) {
if (isset($val['Event']['begindate'])) {
$results[$key]['Event']['begindate'] = $this->dateFormatAfterFind($val['Event']['begindate']);
}
}
return $results;
}
function dateFormatAfterFind($dateString) {
return date('d-m-Y', strtotime($dateString));
}
function afterFind($results) {foreach ($results as $key => $val) {if (isset($val['Event']['begindate'])) {$results[$key]['Event']['begindate'] = $this->dateFormatAfterFind($val['Event']['begindate']);}}return $results;}function dateFormatAfterFind($dateString) {return date('d-m-Y', strtotime($dateString));}


























