Welcome to the Cookbook

loading...

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',
    ),
  ),
);
  1. $results = array(
  2. 0 => array(
  3. 'ModelName' => array(
  4. 'field1' => 'value1',
  5. 'field2' => 'value2',
  6. ),
  7. ),
  8. );

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'
);
  1. $results = array(
  2. 'field_1' => 'value1',
  3. 'field_2' => 'value2'
  4. );

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));
}
  1. function afterFind($results) {
  2. foreach ($results as $key => $val) {
  3. if (isset($val['Event']['begindate'])) {
  4. $results[$key]['Event']['begindate'] = $this->dateFormatAfterFind($val['Event']['begindate']);
  5. }
  6. }
  7. return $results;
  8. }
  9. function dateFormatAfterFind($dateString) {
  10. return date('d-m-Y', strtotime($dateString));
  11. }