Skip to content

Instantly share code, notes, and snippets.

@arturmamedov
Created October 13, 2017 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturmamedov/9460e0b54ac16730143dfda31e2d91cb to your computer and use it in GitHub Desktop.
Save arturmamedov/9460e0b54ac16730143dfda31e2d91cb to your computer and use it in GitHub Desktop.
CakePHP - beforeFind() callback with default conditions and possibility to disable it
<?php
public function beforeFind($event, $query, $options, $primary)
{
// if query builder have ->applyOptions(['default' => false]) not use default conditions and return query
if (isset($options['default']) && $options['default'] == false) {
return $query;
}
// default conditions
$query->where([ 'visible' => 1 ]);
$query->order([ 'sort' => 'ASC' ]);
return $query;
}
@arturmamedov
Copy link
Author

@arturmamedov
Copy link
Author

For disabel it from Controller on selecting use ->applyOptions(['default' => false]) example:

// beforeFind() will be apply: `visible = 1 ORDER BY sort ASC`
$tips = TableRegistry::get('Tips')->find()->where(['site_id' => $this->projectId])->limit(4)->all();

// beforeFind() will not be apply
$tips = TableRegistry::get('Tips')->find()->applyOptions(['default' => false])->where(['site_id' => $this->projectId])->limit(4)->all();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment