We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 14883 ☆ A M B ☆
    • 450 Posts
    I have a TV named ’x’, with a default value of ’default’.

    And it only is accessible via template ’y’.

    If I write a snippet like this:
    $tv = $modx->getObject('modTemplateVar', array('name'=>'x'));
    if ($menu = $tv->getValue($id)) { 
         return $menu;
    }
    


    I expect a value to be returned only if $id represents a resource that uses template ’y’.

    Instead I get ’default’ returned in all of the following situations:

    • $id = any valid resource regardless of what template it uses
    • $id = a bogus number that doesn’t correspond to any resource
    • $id = false
    • $id = ’any freaking thing I make up’

    Is my expectation wrong? If so, can someone please explain to me why this is the desired/expected behavior?
      • 22303 MODX Staff
      • 10,725 Posts
      This is because the behavior of modTemplateVar::getValue() is such that it will always return the default_value unless a valid integer value is passed, and there is no check for a relation between the TV and the Resource template when the object is accessed directly. It’s also the cause of this bug which I have yet to figure out how to fix, but thanks for reminding me of the problem. wink

      Will think on it some more overnight, and see if we can start coming up with a sane solution to this.
        • 14883 ☆ A M B ☆
        • 450 Posts
        Some bad coding on my part, plus this bug/feature, really kicked my ass yesterday for about 3+ hours.

        I guess the best practice if you are expecting this to work as I was expecting it to work is to first ensure that $id represents a resource that uses template ’y’.


        
        $res = $modx->getObject('modResource', $id);
        
        if ($res->get('template') == $y) { // $y represents the ID of the template I'm looking for that uses TV 'x'
            $tv = $modx->getObject('modTemplateVar', array('name'=>'x'));
            return $tv->getValue($id);
        }
        else 
            { return false; }
        
        


        ... or something like that.