Search code examples
phpcode-snippetsmodx

Optimize my Modx snippet with getresources call inside my snippet instead of outside?


SO I have a getResources call giving me an integer value with this call:

[[!getResources? &parents=`[[*id]]` &totalVar=`totalLinks`]]

That outputs to [[+totalLinks]] and I use that to input in to my snippet

[[!ChangeNumberToWord? &input=`[[+totalLinks]]`]]

My Snippet:

$input = '';


function converttoword($total){
    if ($total=="1"){
        $word = "one";
    } elseif($total=="2") {
        $word = "two";
    } elseif($total=="3") {
        $word = "three";
    } elseif($total=="4") {
        $word = "four";
    } elseif($total=="5") {
        $word = "five";
    } elseif($total=="6") {
        $word= "six";
    } elseif($total=="7") {
        $word ="seven";
    } elseif($total=="8") {
        $word = "eight";
    } else{
        $word = "$total";
    }
return $word;                          
}

$output = converttoword($input);

return $output;

My question is how I glue these 2 together so I only need to call my snippet?


Solution

  • Get rid of the getResources call altogether, use: getChildIds in your snippet:

    http://rtfm.modx.com/revolution/2.x/developing-in-modx/other-development-resources/class-reference/modx/modx.getchildids

    something like:

    <?php
    // current resource ID
    $id = $modx->resource->get('id');
    
    // get all child ids
    $array_child_ids = $modx->getChildIds($id);
    
    //so you would count that array 
    $num_children = count($array_child_ids);
    
    // get rid of the ifs to find the word
    $words = array('zero','one','two','three','four','five','six');
    
    // do something if no results
    if ($num_children + 1 > count($words)){
    
        return 'out of range';
    
    }
    
    // return the string
    return $words[$num_children];
    

    so you have other problems you might need to look at depending on your application:

    • what if there are zero children?
    • what about resource status or type [published vs. unpublished, symlinks etc]
    • what happens if the number of children is 3033 [Three thousand, three hundred and thirty-three]?

    [hint: you can google "php convert a number to it's string name" and come up with several options]