Skip to content

Instantly share code, notes, and snippets.

@coonica
Last active September 6, 2022 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save coonica/7b89593e94c24013a259 to your computer and use it in GitHub Desktop.
Save coonica/7b89593e94c24013a259 to your computer and use it in GitHub Desktop.
MODX Revo snippet to divide resources into columns.
Call the snippet
[[multiCols?
&cols=`2`
&tvs=`{"image":1}`
&select=`pagetitle,introtext`
&where=`{"published":1, "deleted":0, "parent":2}`
&sortby=`publishedon`
&sortdir=`DESC`
&tpl=`tpl_article`
]]
And call columns. For example for 2-columned output it will be: [[+column1]] and [[+column2]]
Attention: you need to explicitly specify basePath for tvs with not default media source.
TV with name image will be available in tpl as [[+image]].
<?php
// move it to snippet parameters
$cols = 2;
$limit = 0;
$sortby = 'menuindex';
$sortdir = 'ASC';
//snippet start
$c = $modx->newQuery('modResource');
// init select array
if (isset($select)){
$select = explode(',',$select);
$select[] = 'modResource.id as id';
}
else{
$select = array('modResource.id', 'modResource.pagetitle', 'modResource.longtitle', 'modResource.publishedon'
,'modResource.alias','modResource.content','modResource.introtext');
}
//process tvs
if (isset($tvs)){
$tvs = json_decode($tvs,1);
}
else{
$tvs = array();
}
foreach ($tvs as $name=>$id){
$alias = 'tv_'.$name;
$c->leftJoin('modTemplateVarResource',$alias
, array($alias.'.contentid=modResource.id', $alias.'.tmplvarid' => $id));
$select[] = $alias.'.value as '.$name;
}
// where condition
if (!isset($where)){
$where = array('modResource.published' => 1, 'modResource.deleted' => 0);
}
else{
$where = json_decode($where,1);
}
//query
$c->where($where);
$c->select($select);
$c->sortby($sortby, $sortdir);
$c->limit($limit);
$collections = array();
if ($c->prepare() && $c->stmt->execute()) {
$collections = $c->stmt->fetchAll(PDO::FETCH_ASSOC);
}
//generate collumns
$n = count($collections);
$delta = floor($n/$cols);
$columns = array();
for ($i=0; $i < $cols; $i++){
$output = '';
//$output .= '<br/>col:'.($i+1).'<br/>';
$offset = $i*$delta;
if ($i == $cols-1){
$to = $n;
}
else{
$to = $offset + $delta;
}
for ($j=$offset; $j < $to; $j++){
if (!isset($tpl)){
$output .= '<pre>'. print_r($collections[$j],1) .'</pre>';
}
else{
$output .= $modx->getChunk($tpl, $collections[$j]);
}
}
$columns['column'.($i+1)] = $output;
}
$modx->setPlaceholders($columns);
return;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment