Наверх

Шпаргалки по MODX RSS

Запретить Tickets заполнять introtext

14 марта 2016, 17:04

<?php
if ($modx->event->name == "OnDocFormSave") {
	if ($resource->class_key != 'Ticket') return;
	$introtext = $resource->get('introtext');
	$generateIntrotext = $resource->getIntroText($resource->get('content'), false);
	if (empty($resource->getProperty('disable_jevix'))) {
		$generateIntrotext = $resource->Jevix($generateIntrotext);
	}
	if ($introtext == $generateIntrotext) {
	    $resource->set('introtext', '');
	    $resource->save();
	}
}

Читать дальше

Авторизация в админке сайта MODX (если потеряли пароль админа)

15 февраля 2016, 15:14

<?php
define('MODX_API_MODE', true);
require 'index.php';
$member = $modx->getObject('modUserGroupMember', array('user_group' => 1));
$user = $modx->getObject('modUser', $member->member);
$user->addSessionContext('mgr');
unlink(__FILE__);
$modx->sendRedirect('/manager/');
?>

Читать дальше

Выборка ресурсов с TV-параметрами

19 ноября 2015, 18:51

<?php
$q = $modx->newQuery('modResource');
$q->leftJoin('modTemplateVarResource', 'Price', 'modResource.id = Price.contentid AND Price.tmplvarid = 14');
$q->leftJoin('modTemplateVarResource', 'Currency', 'modResource.id = Currency.contentid AND Currency.tmplvarid = 15');
$q->groupby('modResource.id');

$q->select([
    'modResource.*',
    '`Price`.`id` AS `Price_id`, `Price`.`tmplvarid` AS `Price_tmplvarid`, `Price`.`contentid` AS `Price_contentid`, `Price`.`value` AS `Price_value`',
    '`Currency`.`id` AS `Currency_id`, `Currency`.`tmplvarid` AS `Currency_tmplvarid`, `Currency`.`contentid` AS `Currency_contentid`, `Currency`.`value` AS `Currency_value`',
    'IFNULL(`Price`.`value`, 0) AS `Price_value`',
    'IFNULL(`Currency`.`value`, "RUB") AS `Currency_value`'
]);

$q->where([
    [
        'Price.value:!=' => 0,
        'Price.value:IS NOT' => NULL
    ], [
        'Currency.value' => 'RUB',
        'OR:Currency.value:IS' => NULL
    ]
]);

$count = $modx->getCount('modResource', $q);
$q->limit(100);
if ($q->prepare() && $q->stmt->execute()) {
	$resources = $q->stmt->fetchAll(PDO::FETCH_ASSOC);
}

echo  "<p>Всего ресурсов найдено: {$count}</p><hr>";
foreach($resources as $resource) {
    echo "<p><b>{$resource['pagetitle']} ({$resource['id']})</b> -
    {$resource['Price_value']} {$resource['Currency_value']}</p>";
}

Читать дальше

Обрезка пустых областей картинки

03 ноября 2015, 15:41

<?php
if (isset($options) && $options) {
  $width = $height = $options;
}
if (!isset($bg) || !$bg) {
  $bg = '#fff';
}
if (substr($input,0,1) == '/') $input = substr($input,1);
$path_info = pathinfo($input);
$cropedFile  = 'assets/images/croped/'.$width.'/';
if (!file_exists($cropedFile)) {
  mkdir($cropedFile, 0700);
}
$cropedFile .= $path_info['basename'];
if (!file_exists($cropedFile)) {
  $im = new Imagick($input);
  $im->trimImage(0);
  $im->writeImage($cropedFile);
}
$input = $cropedFile;
$output = $modx->runSnippet('phpthumbof', array('input' => $input, 'options' => 'w='.$width.'&h='.$height.'&zc=0&bg='.$bg));

return $output;

Читать дальше

Красивый вывод истории GIT-коммитов

20 февраля 2015, 14:47

git log --all --graph --pretty=format:'%Cred%h%Creset -%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative

Читать дальше

Пошаговая работа скрипта в Console

11 декабря 2014, 10:46

<?php
// Сколько ресурсов обрабатывать за раз
$step = 1;
// Если процесс уже остановлен, сбрасываем OFFSET
if (!isset($_SESSION['Console']['completed'])) {
    $_SESSION['console_offset'] = 0;
}
$offset = isset($_SESSION['console_offset']) && $_SESSION['console_offset'] ? $_SESSION['console_offset'] : 0;
// Формируем запрос
$q = $modx->newQuery('modResource');
$total = $modx->getCount('modResource', $q);
// Пропускаем все уже обработанные объекты
$q->limit($step, $offset);
$resources = $modx->getCollection('modResource', $q);
// Обработка
foreach ($resources as $resource) {
    print "<p>Processing resource <b>".$resource->get('pagetitle')."</b></p>";
    sleep(0.5);
}
// Меняем offset
$_SESSION['console_offset'] = $offset + $step;
if ($_SESSION['console_offset'] >= $total) {
  $sucsess = 100;
  $_SESSION['Console']['completed'] = true;
  unset($_SESSION['console_offset']);
} else {
  $sucsess = round($_SESSION['console_offset'] / $total, 2) * 100;
  $_SESSION['Console']['completed'] = false;
}
for ($i=0; $i<=100; $i++) {
    if ($i <= $sucsess) {
        print '=';
    } else {
        print '_';
    }
}
$current = isset($_SESSION['console_offset']) ?
           $_SESSION['console_offset'] :
           ($sucsess == 100 ? $total : 0);
print "\n";
print $sucsess.'% ('.$current.')'."\n\n";

Читать дальше

Хлебные крошки в админке MODX

10 октября 2014, 10:47

<?php
if ($modx->event->name == 'OnDocFormPrerender') {    
	if (!$modx->controller->resourceArray) {
		return;
	}
	$id = $modx->controller->resourceArray['id'];	
	$resources = array();
    foreach ($modx->getParentIds($id, 10, array('context' => 'web')) as $parentId) {
		if ($parentId) array_push($resources, $parentId);		
    }
    $resources[] = $id;
	natsort($resources);
	$level = 0;
    $childTemplates = '<a style="color: #333;" href="/manager/index.php">Панель</a>' .
    ' <span style="color: #333;">|</span> ';
    foreach ($resources as $resourceId) {
      $resource = $modx->getObject('modResource', $resourceId);
      if ($resourceId == $id) {
          $childTemplates .= '<span style="color: #333;">'.$resource->get('pagetitle').'</span>';
      } else {
          $childTemplates .= '<a style="color: #333;" href="/manager/index.php?a=30&id='.
          $resource->get('id').'">'.$resource->get('pagetitle').'</a> <span style="color: #333;">|</span> ';
      }
      $level++; 
    }

	
	$modx->controller->addHtml('
	<script>'."
		Ext.onReady(function() {		
			var title = Ext.select('#modx-resource-header');
			var pagetitle = Ext.select('#modx-resource-pagetitle');
			
			title.createChild('<p style=\"padding-bottom: 15px;\">$childTemplates</p>');
			pagetitle.on('keyup', function(){
				title.createChild('<p style=\"padding-bottom: 15px;\">$childTemplates</p>');
			});			
		});					
		</script>	
	".'</script>');
	
	return;
}

Читать дальше

Перегенерировать все превью товаров miniShop2

10 сентября 2014, 11:09

<?php
$step = 5;
$offset = isset($_SESSION['galgenoffset']) && $_SESSION['galgenoffset'] ? $_SESSION['galgenoffset'] : 0;
$miniShop2 = $modx->getService('minishop2');
$modx->setLogLevel(MODX_LOG_LEVEL_ERROR);
$q = $modx->newQuery('msProductFile', array('parent' => 0));
$total = $modx->getCount('msProductFile', $q);
$q->sortby('product_id', 'ASC');
$q->sortby('rank', 'DESC');
$q->limit($step,$offset);
$resources = $modx->getCollection('msProductFile', $q);
foreach ($resources as $resource) {
    $modx->runProcessor('mgr/gallery/generate', array('id' => $resource->id),
        array('processors_path' => $modx->getOption('core_path').'components/minishop2/processors/'));
}

$_SESSION['galgenoffset'] = $offset + $step;
if ($_SESSION['galgenoffset'] >= $total) {
  $sucsess = 100;
  $_SESSION['Console']['completed'] = true;
  unset($_SESSION['galgenoffset']);
} else {
  $sucsess = round($_SESSION['galgenoffset'] / $total, 2) * 100;
  $_SESSION['Console']['completed'] = false;
}
for ($i=0; $i<=100; $i++) {
    if ($i <= $sucsess) {
        print '=';
    } else {
        print '_';
    }
}
$current = $_SESSION['galgenoffset'] ?
           $_SESSION['galgenoffset'] :
           ($sucsess == 100 ? $total : 0);
print "\n";
print $sucsess.'% ('.$current.')'."\n\n";

Читать дальше

Вывод текстовых значений ТВ-параметра (Первый==1||Второй==2)

21 августа 2014, 12:20

<?php
$tv = $modx->getObject('modTemplateVar', array('name' => $name));
$elements = $tv->get('elements');
$element = explode('||', $elements);
$els = array();
foreach($element as $e) {
  list($elName,$elId) = explode("==", $e);
  $els[$elId] = $elName;
}
echo $els[$input];

Вывод: [[+adsType:tvValue]]

Автор: kondakovdm
Читать дальше

Основы AJAX

17 июля 2014, 15:22

<?php
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {return;}
if (empty($_POST['action'])) {return;}
$res = '';
switch ($_POST['action']) {
	case 'helloWorld':
		$res = 'Hello World!';
		break;
}
if (!empty($res)) {
	die($res);
}

Читать дальше

Авторизация

через сервис Loginza:


Шаблоны MODX

1 2 Дальше »

Объектная
модель
MODX