We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 41149
    • 43 Posts
    Hi there!

    Let's take this setup for example:

    - Parent
      -- Child
    - Parent
      -- Child
    - Parent
      -- Child
      -- Child
      -- Child
    - Parent
      -- Child


    Would I use getResources to add the number of children of each parent and output them as a string, or would that require a custom snippet?

    So for example the output would look like this:

    Total Children: (6)

    Any ideas?
    Thank you!
      The web is our sandbox, so let's develop a castle.
      • 4172
      • 5,888 Posts
      Not sure, if this will work.
      Create a snippet 'counter' with:

      $newvalue = !empty($value) ? $value+1 : 1;
      $modx->setPlaceholder('countervalue',$newvalue);
      


      put in your children-tpl-chunks (getResources or wayfinder)
      [[!counter? &value=`[[+countervalue]]`]]


      and at the end:

      [[+countervalue]]



      [ed. note: Bruno17 last edited this post 10 years, 10 months ago.]
        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!
        • 40045
        • 534 Posts
        I recently also needed exactly this functionality...here is the snippet that came out =), it's listening to the name of getChildCount

        commented out is actually a simpler version if you only need one level of children...

        <?php
        // use like [[!getChildCount? &id=`[[*id]]`]] or with getResources [[!getChildCount? &id=`[[+id]]`]]
        // returns the number of childs from a in $id specified resource
        // this was the simple version to only get imediate childs, replaced by more complex version that can also count subfolder children
        // $counter = 0;
        // $children = $modx->getCollection('modResource', array('parent' => $id, 'published' => 1));
        
        // foreach ($children as $child) {
        // 	++$counter;
        // }
        // return $counter;
        
        $count = 0;
        $parents = $modx->getChildIds($id, 1, array('context' => 'web'));
        
        foreach ($parents as $parent) {
        	if ( $res = $modx->getObject('modResource', array('id' => $parent, 'published' => 1, 'deleted' => 0)) ) {
        
        		$res = $res->toArray();
        
        		if ( !empty($res['isfolder']) ) {
        
        			$query = array(
        				'parent' => $parent,
        				'deleted' => 0,
        				'published' => 1,
        			);
        
        			$count += (int)$modx->getCount('modResource', $query);
        		} else {
        			$count++;
        		}
        	}
        }
        
        return $count;