There is a function helper

function all($offset = 0, $rowcount = 0, $sort = NULL, $includeContactIDs = FALSE, $justIDs = FALSE) {
  // delegate to $this->sql(), $this->select(), $this->from(), $this->where(), etc.
  return $this->sql($this->select(), $offset, $rowcount, $sort, $includeContactIDs, NULL);

But I'd like to set a sort order if not set. All the examples I found are writing directly their sql, as opposed to sql() that expect a CRM_Utils_Sort class (or that's what I understand based on the error messages)

So what I'd like to do is to add a

if (!$justIDs &&!sort)
   //how to initialise sort so it ends up like ORDER BY created_date)?

1 Answer 1


Custom searches inherit CRM_Contact_Form_Search_Custom_Base; check out the addSortOffset() function below (around line 177) to see how the sort is tacked onto the query:

public function addSortOffset(&$sql, $offset, $rowcount, $sort) {
    if (!empty($sort)) {
      if (is_string($sort)) {
        $sort = CRM_Utils_Type::escape($sort, 'String');
        $sql .= " ORDER BY $sort ";
      else {
        $sql .= " ORDER BY " . trim($sort->orderBy());
    if ($rowcount > 0 && $offset >= 0) {
      $offset = CRM_Utils_Type::escape($offset, 'Int');
      $rowcount = CRM_Utils_Type::escape($rowcount, 'Int');
      $sql .= " LIMIT $offset, $rowcount ";

If you want to use an array it will send it to CRM_Utils_Sort::orderby(). I think you can set your $sort like this:

if (!$justIDs &&!sort) {
  $sort = array (
    'name' => 'civicrm_created_date',
    'direction' => 1,

Would that work for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.