Archive

Hi,
I would like to create an archive for blog posts using pdotools. I want to display the archives in the following format.

  • Year (Counts)
    • Months (Counts)
      • Blog Posts
      • Blog Posts


I need some guidelines regarding,
  • Which tools is best to achieve the above format pdoMenu or pdoResources?
  • How to filter the blog posts by year and month?


Thanks.
Charles Richard
19 ноября 2015, 06:21
modx.pro
8
3 901
+2

Комментарии: 11

Василий Наумкин
19 ноября 2015, 09:55
+2
pdoTools can`t do this out of the box. You need to write your own snippet for it.

1. Get all resources
2. Loop through them
3. Get their createdon, split to year and month, than and into such array
$resources = array(
	'2015' => array(
		'11' => array(
			0 => array(
				'id' => 15,
				'pagetitle' => 'Some title',
				...
			),
			1 => array(...)
		)
	)
)
4. Loop through this array and template it
5. Show on site
6. (optional) Cache results

Of course, you can use pdoTools methods for this snippet.
    Charles Richard
    19 ноября 2015, 10:02
    0
    Thanks, will try this.
      Василий Наумкин
      19 ноября 2015, 10:23
      10
      +7
      My quick example:
      <?php
      $tplWrapper = '@INLINE <ul>{{+output}}</ul>';
      $tplYear = '@INLINE <li>{{+year}}<sup>({{+count}})</sup><ul>{{+resources}}</ul></li>';
      $tplMonth = '@INLINE <li>{{+month}}<sup>({{+count}})</sup><ul>{{+resources}}</ul></li>';
      $tpl = '@INLINE <li><a href="{{+uri}}">{{+pagetitle}}</a></li>';
      
      $pdo = $modx->getService('pdoFetch');
      
      $resources = $pdo->getCollection(
      	'modResource',
      	array('published' => true, 'deleted' => false),
      	array('parents' => 0, 'sortby' => 'createdon', 'sortdir' => 'DESC')
      );
      $tree = array();
      foreach ($resources as $resource) {
      	$year = date('Y', $resource['createdon']);
      	$month = date('m', $resource['createdon']);
      	$tree[$year][$month][] = $resource;
      }
      
      $output = '';
      foreach ($tree as $year => $months) {
      	$tmp1 = '';
      	$count = 0;
      	foreach ($months as $month => $resources) {
      		$tmp2 = '';
      		foreach ($resources as $resource) {
      			$tmp2 .= $pdo->getChunk($tpl, $resource);
      			$count++;
      		}
      		$tmp1 .=  $pdo->getChunk($tplMonth, array(
      			'month' => $month,
      			'count' => count($resources),
      			'resources' => $tmp2,
      		));
      	}
      	$output .=  $pdo->getChunk($tplYear, array(
      		'year' => $year,
      		'count' => $count,
      		'resources' => $tmp1,
      	));
      }
      
      return $pdo->getChunk($tplWrapper, array('output' => $output));

      Result:
        Charles Richard
        19 ноября 2015, 16:21
        0
        It works except the year count. Could you please have a look?
        Григорий Коленько
        17 декабря 2015, 23:36
        0
        Василий, привет. Делал по твоему примеру. Но нужно к этому всему еще пагинацию прикрутить.
        Когда страница грузится из базы, то все окей, даже следующая страница прогружается. Если же из куша загрузка, то ничего не происходит. Просто выводится первая страница и все, без пагинации даже.
        Ниже вызов и сниппет.
        <div id="pdopage">
                    <div class="rows">
                        [[!+page.nav]]
        
                        [[!pdoPage?
                        &parents=`[[*id]]`
                        &depth=`3`
                        &limit=`12`
                        &element=`pdoNews`
                        &showLog=`1`
                        &tpl=`mainNewsRow`
                        &tvPrefix=``
                        &includeTVs=`mainNewsId`
                        &hideContainers=`1`
                        &ajaxMode=`scroll`
                        ]]
        
                    </div>
                </div>

        <?php
        $tplWrapper = '@INLINE <div>{{+output}}</div>';
        $tplYear    = '@INLINE <div>{{+year}}<div>{{+resources}}</div></div>';
        $tplMonth   = '@INLINE <div>{{+month}}<div>{{+resources}}</div></div>';
        $tplDay     = '@INLINE <div>{{+day}}<div>{{+resources}}</div></div>';
        $tpl        = $modx->getOption( 'tpl', $scriptProperties, '@INLINE <div><a href="{{+uri}}">{{+pagetitle}}</a></div>' );
        
        $limit  = $modx->getOption( 'limit', $scriptProperties, 10 );
        $offset = $modx->getOption( 'offset', $scriptProperties, 0 );
        
        
        $fqn = $modx->getOption( 'pdoFetch.class', null, 'pdotools.pdofetch', true );
        if ( $pdoClass = $modx->loadClass( $fqn, '', false, true ) ) {
        	$pdoFetch = new $pdoClass( $modx, $scriptProperties );
        } elseif ( $pdoClass = $modx->loadClass( $fqn, MODX_CORE_PATH . 'components/pdotools/model/', false, true ) ) {
        	$pdoFetch = new $pdoClass( $modx, $scriptProperties );
        } else {
        	$modx->log( modX::LOG_LEVEL_ERROR, 'Could not load pdoFetch from "MODX_CORE_PATH/components/pdotools/model/".' );
        
        	return false;
        }
        
        $parents = $modx->getOption( 'parents', $scriptProperties, $modx->resource->get( 'id' ) );
        
        $options   = array(
        	'parents' => $parents,
        	'sortby'  => 'createdon',
        	'sortdir' => 'DESC',
        	'limit'   => $limit,
        	'offset'  => $offset
        );
        $resources = $pdoFetch->getCollection( 'modResource', array( 'published' => true, 'deleted' => false ), $options );
        
        
        
        
        $pdoFetch->addTime( 'pdoTools загружен' );
        
        $tree = array();
        
        
        foreach ( $resources as $resource ) {
        	$year                      = date( 'Y', $resource['createdon'] );
        	$month                     = date( 'm', $resource['createdon'] );
        	$tree[ $year ][ $month ][] = $resource;
        }
        
        $output = '';
        foreach ( $tree as $year => $months ) {
        	$tmp1  = '';
        	$count = 0;
        	foreach ( $months as $month => $resources ) {
        		$tmp2 = '';
        		foreach ( $resources as $resource ) {
        			$tmp2 .= $pdoFetch->getChunk( $tpl, $resource );
        			$count ++;
        		}
        		$tmp1 .= $pdoFetch->getChunk( $tplMonth, array(
        			'month'     => $month,
        			'count'     => count( $resources ),
        			'resources' => $tmp2,
        		) );
        	}
        	$output .= $pdoFetch->getChunk( $tplYear, array(
        		'year'      => $year,
        		'count'     => $count,
        		'resources' => $tmp1,
        	) );
        }
        
        $pdoFetch->setTotal();
        
        return $pdoFetch->getChunk( $tplWrapper, array( 'output' => $output ) );
          lexikon
          15 апреля 2016, 23:24
          0
          удалось ли подружить с pdoPage?
            Григорий Коленько
            16 апреля 2016, 00:43
            +2
            Да, удалось. выложить код постараюсь на днях. Если забуду напиши во вторник. Пятница все-таки))
              lexikon
              17 апреля 2016, 11:54
              0
              у меня получилось путём добавления
              $output = $pdoFetch->run();
              но не могу подружить с &includeTVs ( всю голову сломал(
                Tanya
                17 августа 2016, 16:57
                0
                А можно увидеть ваше решение, с такой же проблемой столкнулась. И ещё, может подскажите, а как бы лучше реализовать ссылку по месяцам? Т.е. мне не заголовки новостей нужны, а достаточно месяца и кол-ва новостей в месяц, но сделать бы эти месяцы ссылкой… и открывать по фильтру/месяцам.
                Спасибо!
      Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
      11