Отключение пагинации для макроса blogs20 postList — различия между версиями

Материал из Umicms
Перейти к:навигация, поиск
Строка 17: Строка 17:
  
 
if ($page > 0) { $page = 1; }
 
if ($page > 0) { $page = 1; }
if ($page === 0) {
+
if ($page == 0) {
 
$page = (int)getRequest('p');
 
$page = (int)getRequest('p');
}else{
 
$page = 0;
 
 
}
 
}
 
 

Версия 13:37, 8 октября 2013

Актуально для версии 2.9.1

Задача

Требуется выводить список блогов на всех страницах сайта и отключить зависимость от пагинации, что бы все время выводились например только последние добавленные статьи или блоги.

Решение

Для решения данного вопроса необходимо будет создать кастомный макрос, назовем его postsListCustom. В файл \classes\modules\blogs20\__custom.php копируем макрос postsList из файла \classes\modules\blogs20\class.php и переименовывае в postListCustom. Теперь главный момент, надо сделать два изменения, сначала добавить в первой строке, что это расширение класса blogs20 и заменить все обращения в макросе к классу self:: на def_module::. В конечном итоге у нас должен получиться следующий код:

<?php
abstract class __custom_blogs20 extends blogs20 {
	//TODO: Write here your own macroses
	public function postsListCustom($blogId = false, $template = 'default', $limit = false, $page) {
		list($sTemplateBlock, $sTemplateLine, $sTemplateEmpty) =
				def_module::loadTemplates('blogs20/'.$template, 'posts_list_block', 'posts_list_line', 'posts_list_block_empty');

		if ($page > 0) { $page = 1; }
		if ($page == 0) {
			$page = (int)getRequest('p');
		}
		
		$oBlog = null;

		$oHierarchy = umiHierarchy::getInstance();
		if($blogId == false) {
			$iTmp = (int)getRequest('param0');
			if($iTmp) $blogId = $iTmp;
		}

		$hierarchy_type_id = umiHierarchyTypesCollection::getInstance()->getTypeByName("blogs20", "post")->getId();

		$sel = new selector('pages');
		$sel->types('hierarchy-type')->id($hierarchy_type_id);
		$sel->where('is_spam')->notequals(1);

		$typesCollection = umiObjectTypesCollection::getInstance();
		$typeId   = $typesCollection->getTypeByHierarchyTypeId($hierarchy_type_id);
		$postType = $typesCollection->getType($typeId);

		if($blogId) {
			$oBlog = $oHierarchy->getElement($blogId);
			if(!$oBlog) {
				throw new publicException(getLabel('error-page-does-not-exist', null, $blogId));
			}
		}

		if($blogId != false) {
			$userId        = cmsController::getInstance()->getModule('users')->user_id;
			$aFriendList   = $oBlog->getValue('friendlist');
				$aFriendList[] = umiObjectsCollection::getInstance()->getObjectIdByGUID('system-supervisor');
			if($aFriendList === NULL) {
				$aFriendList = Array();
			}

			$aAuthorList   = permissionsCollection::getInstance()->getUsersByElementPermissions($blogId, 2);
			$aAuthorList[] = $oBlog->getObject()->getOwnerId();
			$sel->where('hierarchy')->page($blogId)->childs(1);
			if(!in_array($userId, $aFriendList) && !in_array($userId, $aAuthorList)) {
				$sel->where('only_for_friends')->notequals(1);
			}
		} else {
			$sel->where('only_for_friends')->notequals(1);
		}

		def_module::applyTimeRange($sel, $postType);

		$sel->order('publish_time')->desc();

		if($limit) {
			$sel->limit($page * $limit, $limit);
		} else {
			$sel->limit($page * $this->posts_per_page, $this->posts_per_page);
		}

		$result = $sel->result();
		$total  = $sel->length();
		if(!empty($result)) {
			$aLines = array();
			foreach($result as $oPost) {
				$iPostId = $oPost->getId();
				if(!$oPost) continue;
				if(!$blogId) {
					$oBlog = $oHierarchy->getElement( $oPost->getRel() );
				}
				$sPostLink  = $oHierarchy->getPathById($iPostId, true);
				$sBlogLink  = $oHierarchy->getPathById($oBlog->getId(), true);
				$aLineParam = array();
				$aLineParam['attribute:id'] = $iPostId;
				$aLineParam['attribute:author_id'] = $oPost->getObject()->getOwnerId();
				$aLineParam['name']			= $oPost->getName();
				$aLineParam['post_link']    = $sPostLink;
				$aLineParam['blog_link']    = $sBlogLink;
				$aLineParam['bid']   		= $oBlog->getId();
				$aLineParam['blog_name']    = $oBlog->getName();
				$aLineParam['blog_title']   = $oBlog->getValue('title');
				$aLineParam['title']		= $oPost->getValue('title');
				$aLineParam['cut'] = system_parse_short_calls($this->prepareCut($oPost->getValue('content'),
 $sPostLink, $template), $iPostId);
				$aLineParam['subnodes:tags'] = $this->prepareTags($oPost->getValue('tags'), $template);
				$aLineParam['comments_count'] = $this->getCommentsCount($iPostId);
					 $aLineParam['publish_time']   = ($t = $oPost->getValue('publish_time')) ? $t->getFormattedDate('U') : '';
				$aLines[] = def_module::parseTemplate($sTemplateLine, $aLineParam, $iPostId);
				$this->pushEditable("blogs20", "post", $iPostId);
			}

			$aBlockParam 		  = array();
			$aBlockParam['void:lines'] = $aBlockParam['subnodes:items'] = $aLines;
			$aBlockParam['bid']	  = $blogId;
			$aBlockParam['per_page'] = $limit ? $limit : $this->posts_per_page;
			$aBlockParam['total']    = $total;

			return def_module::parseTemplate($sTemplateBlock, $aBlockParam);
		} else {
			return def_module::parseTemplate($sTemplateEmpty, array('bid'=>$blogId));
		}
	}
};
?>

Помимо всего выше перечисленного мы добавили четвертую передаваемую переменную $page от значения которой будет включаться или выключаться пагинация. Мы видим, что при передаваемом значении больше нуля пагинация будет отключена. Теперь мы можем добавить макрос вывода блогов или статей блога макросом blogs20 postListCustom и для отключения пагинации добавить четвертым передаваемым значением число 1.