We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
  • Ok, for accurate pagination, you need to count the # of records matching a given criteria... so there’s the getCount() method: http://rtfm.modx.com/display/xPDO20/xPDO.getCount

    e.g.
    $total = $my_xpdo->getCount();


    But how do we pass it criteria, especially if we’ve built it up using separate clauses, e.g.

    $query = $my_xpdo->newQuery('Vendors');
    $query->where(array(  
        'name:LIKE' => "%$search_term%",  
        'OR:city:LIKE' => "%$search_term%"
        )
    );
    $query->andCondition(array('is_published' => '1') ); # Little safety valve


    How would I count the number of vendors there? I never had the full criteria in an array, so I can’t very well pass it to getCount()... any ideas here? Thanks!
      • 3749
      • 24,544 Posts
      Have you tried $modx->getCount($className, $query) ?

      The second parameter is described this way in the code:

      @param mixed $criteria Any valid xPDOCriteria object or expression.

      If not, and the query returns an array, you could always use plain old PHP:

      count($resultingArray);


        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
      • I ran into a similar problem not so long ago, here is the answer from Jason :

        You are doing a GROUP BY model, so it looks like you want to select("COUNT(DISTINCT model)") here (don’t select id OR your sum() expression, or add the group by until you are actually getting the rows because grouping by model is the same as returning a single row per model); you’ll have to find the proper COUNT() expression to match the rows you are returning in the actual query, i.e.:

        <?php
        //Retreive the count
        $c = $modx->newQuery($table);
        $c->select("COUNT(DISTINCT model)");
        if ($c->prepare() && $c->stmt->execute()) {
            $rows = $c->stmt->fetchAll(PDO::FETCH_COLUMN);
            $count = (integer) reset($rows);
        
            //Do the actual query only if there is a count
            if ($count > 0) {
                $c = $modx->newQuery($table);
                $c->select('id, model, SUM(failures) as failures');
                $c->groupBy('model');
                $c->sortby($sort,$dir);
                $c->limit($limit, $start);
                $fields = $modx->getCollection($table, $c);
            }
        }


        Maybe that can be useful for you too.
          • 37286
          • 160 Posts
          Another method that works:
          $count= 0;
          if($c->prepare() && $c->stmt->execute()){
              $count= $c->stmt->rowCount();
          }

          I don't know which is faster...