We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 18654
    • 191 Posts
    Is there anyway to get the value of a single TV associated with an object without looping through all of the TV’s associated with that object?

    Below is my attempt to get a single TV named "PDF" that was associated with a certain object. It didn’t work because I couldn’t access the value that was specific to the modResource object.
    <?php
    	if(isset($_GET['resID']) && isset($_GET['type'])){		
    		$tvType = strtoupper($_GET['type']);
    		$applicationType = strtolower('application/'.$_GET['type']);
    		$resourceID = $_GET['resID'];
    		
    		$resource = $modx->getObject('modResource', array('id' => $resourceID));
    		$relTVs = $resource->getMany('modTemplateVar', array('name' =>'PDF'));
    		
    		foreach ($relTVs as $relTV) {
    			$tvName = $relTV->get('name'); 
    			$tvValue = $relTV->get('value');
    			if ($tvName == $tvType){
    				echo $tvValue;
    				echo $relTV->get('description');
    			}
    		}
    			
    	}
    ?>
    

      God does not save those who are only imaginary sinners. Be a sinner, and let your sins be strong, but let your trust in Christ be stronger, and rejoice in Christ who is the victor over sin, death, and the world.
    • First, to get a processed TV value, you need to call modTemplateVar->getValue(), not ->get(’value’).

      Second, if you don’t need to use any of the resource properties, there is no reason to getObject(’modResource’). In fact this is a good way to use memory unnecessarily, reducing the efficiency of your code. Instead, it is much more efficient to do something like this, which will all reduce the number of queries involved:
      <?php
      if(isset($_GET['resID']) && isset($_GET['type'])){		
          $tvType = strtoupper($_GET['type']);
          $applicationType = strtolower('application/'.$_GET['type']);
          $resourceID = $_GET['resID'];
      
          $tvPDF = $modx->getObject('modTemplateVar', array('name' =>'PDF'));
          if ($tvPDF) {
              $value = $tvPDF->getValue($resourceID);
              /* Now do something with the value... */
          }
      }
      ?>
        • 18654
        • 191 Posts
        Thanks! That’s a ton more efficient. I knew there had to be a better way. I was just stuck on thinking that I had to work my way from the modResource to the TemplateVar as opposed to vice-versa.
          God does not save those who are only imaginary sinners. Be a sinner, and let your sins be strong, but let your trust in Christ be stronger, and rejoice in Christ who is the victor over sin, death, and the world.