How to get a full count/entities displayed while using elgg_list_entities()

elgg_list_entities wraps up a very handy process for both querying and displaying a list of entities, but what if you need access to the full count (without pagination) or the actual ElggEntity objects displayed?

Nicely, elgg_list_entities uses a viewer function, elgg_view_entity_list, to render the queried list, so you can provide your own viewer that wraps elgg_view_entity_list to capture the info you want:

$viewer = function ($entities, $options) {
    return elgg_view_entity_list($entities, $options);
};
$html = elgg_list_entities($options, 'elgg_get_entities', $viewer);

At this point we have the default behavior, but notice we have access to the parameters passed to the viewer. No we just need to capture what we need:

$full_count = null;
$entities_displayed = null;
$viewer = function ($entities, $options) use (&$full_count, &$entities_displayed) {
    $entities_displayed = $entities;
    $full_count = $options['count'];
    return elgg_view_entity_list($entities, $options);
};
$html = elgg_list_entities($options, 'elgg_get_entities', $viewer);

Now we've pulled the variables $full_count and $entities_displayed into the scope of our viewer function, and after the elgg_list_entities is executed, those vars will be populated.

Navigation