Skip to content

CakePHP2.x Snippets

Mark edited this page Jan 25, 2014 · 7 revisions

Useful snippets for CakePHP 2.x

Model/Behavior afterFind()

/**
 * Unify array structure to make afterFind code easier to write and maintain.
 *
 * @see https://github.com/cakephp/cakephp/issues/2529
 *
 * @param mixed $results
 * @param bool $primary
 * @return mixed $results
 */
public function afterFind($results, $primary = false) {
	$results = parent::afterFind($results, $primary);
	
	// check for the primaryKey field
	if (!isset($results[$this->primaryKey])) {
		// standard format, use the array directly
		$resultsArray = &$results;
	} else {
		// stupid format, create a dummy array
		$resultsArray = array(array());
		// and push a reference to the single value into our array
		$resultsArray[0][$this->alias] = &$results;
	}

	// iterate through $resultsArray
	foreach ($resultsArray as &$result) {
		// operate on $result[$this->alias]['fieldname']
		// one piece of code for both cases. yay!
	}

	return $results;
}
Clone this wiki locally