pepebe
5/21/2014 - 11:24 AM

Populate select TVs with a list of resource.

Populate select TVs with a list of resource.

/*
  The idea is to populate a (multi-)select list with a list of resources, 
  returning the id(s) in templates, snippetrs and chunks.
  
  This approach is much more flexible as the one offered by the resource TV.

  Important: This is not a snippet or a plugin. Use @EVEL or @SELECT code as input value for a TV.
*/

/* Example 1 
  Return a simple list with pagetitles filtered by parent and id and ordered by menuindex:
*/

  @SELECT pagetitle, id FROM [[+PREFIX]]site_content WHERE (parent=899 AND id<>1058) ORDER BY menuindex

/* Example 2a
  Add the resource id behind the pagetitle 
  
  This one is using @EVAL and getResources.
  
  Source: http://forums.modx.com/thread/79645/sorting-tv-resourcelist-by-title-instead-by-id#dis-post-442004
  Credits: http://forums.modx.com/u/Bruno17
*/

  @EVAL $output = $modx->runSnippet(
    'getResources'
    ,array(
       'parents'=>'99'
      ,'tpl'=>'@INLINE [[+pagetitle]]([[+id]])==[[+id]]'
      ,'outputSeparator'=>'||'
      ,'sortby'=>'pagetitle'
      ,'sortdir'=>'ASC'
      ,'limit'=>'0'
      )
    );
    return 'choose one==||' . $output;
  
/* Example 2b: 
  You can achieve the same thing with @SELECT using this code
  
  Source: https://gist.github.com/silentworks/3608022
  Credits: https://gist.github.com/justinkv  
*/
  
  @SELECT CONCAT(`pagetitle`,' (',`id`, ')') AS `name`,`id` FROM `[[+PREFIX]]site_content` WHERE `published` = 1 AND `deleted` = 0
  
  /* Much shorter: */
  
/* Example 3
   Create resource list filtered by a Tv value and a template id using JOIN.
   
   Credits: http://forums.modx.com/u/Dimmy
   Source: http://forums.modx.com/thread/20044/tuturial---use-select-and-checkbox-tv-to-populate-pulldown-listmenu-tv
*/

  @SELECT pagetitle,contentid FROM `[[+PREFIX]]site_content` AS c JOIN `[[+PREFIX]]site_tmplvar_contentvalues` AS t ON c.id=t.contentid WHERE tmplvarid = 4 AND value = 'ja' AND template = 8