Андрей Шевяков

Андрей Шевяков

С нами с 28 сентября 2016; Место в рейтинге пользователей: #108
Vladimir
08 апреля 2023, 18:56
1
0
Из того что написано в описании могу дать такой пример.
Будет конкретный пример, распишу по лучше, ниже создаст только 1 ресурс.
<?php

$newResourceParentId = 2;
$newResourceUrl = 'super-product-1337';
$newResourcePageTitle = 'Лучший продукт в своём роде';
$newResourceTemplate = 8;

$createNewResource = $modx->runProcessor('resource/create', array(
    'parent' => $newResourceParentId,
    'pagetitle' => $newResourcePageTitle,
    'alias' => $newResourceUrl,
    'template' => $newResourceTemplate,
    'published' => 1
));

if ($createNewResource->isError()) {
    echo "Не могу создать страницу с таким заголовком='$newResourcePageTitle'
";
    return;
}
Vladimir
08 апреля 2023, 13:53
2
0
[РЕШЕНО] Суть в том чтобы в админке появились только те характеристики у товара которые есть, это значит поставить все уникальные характеристики для категории, нужно было именно такое решение, сделал сам. А если не нужно их указывать в админке для редактирования, то да проще будет вывести их список через pdoResources указав класс msCategoryOption

Буду рад кто исправит это код(КОД РАБОЧИЙ), чтобы был чище, так как делался на быструю руку решить задачу, а так же не было знаний для реализации этой задачи.
<?php

function prepareSqlQuery($sqlQuery){
	global $modx;
	return $modx->query($sqlQuery);
}


function extractResultsFromQueryObject($sqlQueryResult, $itemsToRetreive, $multiDimensionRetreive=false){
	global $modx;
	$results = array();

	if (is_object($sqlQueryResult)) {
		while ($row = $sqlQueryResult->fetch(PDO::FETCH_ASSOC)) {
			if($multiDimensionRetreive){
				foreach($itemsToRetreive as $key => $value){
					array_push($results, $row[$key], $row[$value]);
				}	    		
			} else {
				foreach($itemsToRetreive as $itemToRetreive){
					array_push($results, $row[$itemToRetreive]);
				}
			}
		}
	}
	return $results;
}


$prepareSqlQueryOfRetreiveCategories = prepareSqlQuery('SELECT modx_site_content.id FROM `modx_site_content` WHERE modx_site_content.class_key = "msCategory"');
$categoriesIds = extractResultsFromQueryObject($prepareSqlQueryOfRetreiveCategories, array('id'));

if(count($categoriesIds) > 0){

	foreach($categoriesIds as $categoryId){

		$productsQueryObject = prepareSqlQuery('SELECT modx_site_content.id FROM `modx_site_content` WHERE modx_site_content.class_key = "msProduct" AND modx_site_content.parent = "'.$categoryId.'"');
		$productsIds = extractResultsFromQueryObject($productsQueryObject, array('id'));

		if(count($productsIds) > 0){
			$productsIds = implode(",", $productsIds);

			$distinctProductOptionsSqlQuery = prepareSqlQuery('SELECT DISTINCT modx_ms2_product_options.key FROM `modx_ms2_product_options` WHERE modx_ms2_product_options.product_id IN ('.$productsIds.")");
			$distinctProductOptions = extractResultsFromQueryObject($distinctProductOptionsSqlQuery, array('key'));

			$uniqueOptions = "";
			$uniqueOptionsLength = count($distinctProductOptions);
			foreach ($distinctProductOptions as $idx => $value) {
				if($idx >= $uniqueOptionsLength - 1){
					$uniqueOptions .= "'$value'";
				} else{
					$uniqueOptions .= "'$value',";
				}
			}


			$uniqueOptionsIdsSqlQuery = prepareSqlQuery('SELECT modx_ms2_options.id,modx_ms2_options.key FROM `modx_ms2_options` WHERE modx_ms2_options.key IN ('.$uniqueOptions.')');
			$uniqueOptionsIds = extractResultsFromQueryObject($uniqueOptionsIdsSqlQuery, array('id'));


			/* #################################### ##################################### */
			foreach($uniqueOptionsIds as $idx => $uniqueOptionId){
				if (!$cop = $modx->getObject('msCategoryOption', array('option_id' => $uniqueOptionId, 'category_id' => $categoryId))) {
					$table = $modx->getTableName('msCategoryOption');
					$sql = "INSERT INTO {$table} (`option_id`,`category_id`,`active`) VALUES ({$uniqueOptionId}, {$categoryId}, 1);";
					$stmt = $modx->prepare($sql);
					$stmt->execute();
				} else {
					$q = $modx->newQuery('msCategoryOption');
					$q->command('UPDATE');
					$q->where(array('option_id' => $uniqueOptionId, 'category_id' => $categoryId));
					$q->set(array('active' => 1));
					$q->prepare();
					$q->stmt->execute();
				}            
				
			}
			/* #################################### ##################################### */
			echo 'Done';
		}
	}
}
Константин Ильин
28 марта 2023, 08:35
1
0
Когда то помогло решение через плагин на событие msOnChangeOrderStatus.
вот пример
switch ($modx->event->name) {
    case 'msOnChangeOrderStatus':
    // тут нужно получить ваш плейсхолдер sd.email и присвоить emailManagers , вместо тестовой строки
    $emailManagers= 'test@test.ru,tst@ee.ru';
    
    // тут присваиваем новые емайлы
    $modx->setOption('ms2_email_manager', $emailManagers); 
    
    // так же можно учитывать статусы писать какую то логику если надо
    if ($status != 1) {
        $modx->setOption('ms2_email_manager', $emailManagers); 
    }
    break;
}
Alexey
21 февраля 2023, 16:48
1
0
Привет! Можно плагином решить:

<?php
if ($modx->context->key != 'mgr') {
    switch ($modx->event->name) {       
        case 'OnBeforeUserFormSave':
            if ($mode == 'new') {  // Событие перед регистрацией пользователя
                if (empty($_POST['register_agree'])) {
                    $modx->event->output('Вы должны согласиться с политикой конфиденциальности');
                }                
            }            
            break;
    }
}
Артур Шевченко
03 февраля 2023, 11:04
3
+3
Прям из коробки нельзя, надо немного поправить JS. Вот это
if (config.history) {
                if (typeof(jQuery().sticky) == 'undefined') {
                    $.getScript(config['assetsUrl'] + 'js/lib/jquery.sticky.min.js', function () {
                        pdoPage.initialize(config);
                    });
                    return;
                }
                pdoPage.stickyPagination(config);
            }
            else {
                $(config.pagination).hide();
            }
Заменить на это
$(document).on('click', config['link'], function (e) {
                e.preventDefault();
                var href = $(this).prop('href');
                var key = config['pageVarKey'];
                var match = href.match(new RegExp(key + '=(\\d+)'));
                var page = !match ? 1 : match[1];

                if (pdoPage.keys[key] != page) {
                    $(config['more']).find('button').attr('disabled', false);
                    if (config.history) {
                        if (page == 1) {
                            pdoPage.Hash.remove(key);
                        } else {
                            pdoPage.Hash.add(key, page);
                        }
                    }
                    $this.loadPage(href, config);
                }
            });

            if (config.history) {
                if (typeof(jQuery().sticky) == 'undefined') {
                    $.getScript(config['assetsUrl'] + 'js/lib/jquery.sticky.min.js', function () {
                        pdoPage.initialize(config);
                    });
                    return;
                }
                pdoPage.stickyPagination(config);

                $(window).on('popstate', function (e) {
                    if (e.originalEvent.state && e.originalEvent.state['pdoPage']) {
                        $this.loadPage(e.originalEvent.state['pdoPage'], config);
                    }
                });

                history.replaceState({pdoPage: window.location.href}, '');
            }
И в pdoPage параметру ajaxMode установить значение button.
Павел Романов
03 февраля 2023, 10:13
1
0
Так только цифры останутся:
foreach ($modx->getIterator('modUser') as $user) {
    $profile = $user->getOne('Profile');
    $phone = preg_replace("/[^,.0-9]/", '', $profile->get('phone'));
    $user->set('username', $phone);
    $user->save();
}
Артур Шевченко
08 декабря 2022, 13:59
1
+2
Не знаю откуда ты взял этот код, но вот такой плагин должен решить твою задачу.
switch ($modx->event->name) {
    case 'msOnGetOrderCustomer':
        $profile = $customer->getOne('Profile');
        $profile->set('mobilephone', $profile->get('phone'));
        $profile->save();
    break;
}
vectorserver
12 октября 2022, 08:43
2
0
В Fenom можно напрямую использовать условный тернарный оператор, не создавая чанк:
{'!getImageList' | snippet : [
    'tvname' => 'test',
    'tpl' => '@CODE: <input type="checkbox" {$check == 1 ? "checked" : ""} >'
    ]
}
Через обычный парсер, нужно создавать чанк и уже в нем прописывать условия
Snippet:
[[!getImageList?
        &tvname=`test`
        &tpl=`option_tpl`
]]
Chunk option_tpl:
<input type="checkbox" [[+check:is=`1`:then=`checked`:else=``]] >
Проверил у себя на тестовом сервере все работает!

Настройки MIGX:
Вкладки формы
[
  {
    "caption": "Заголовок",
    "fields": [
      {
        "field": "image",
        "caption": "Изображение",
        "inputTVtype": "text"
      },
      {
        "field": "check",
        "caption": "checkDATA",
        "inputTVtype": "listbox",
        "inputOptionValues": "Да==1||Нет==0"
      }
    ]
  }
]
Разметка колонок:
[{
  "header": "Изображение",
  "dataIndex": "image"
},{
  "header": "checkDATA",
  "dataIndex": "check"
}]
Артур Шевченко
03 октября 2022, 21:42
1
+3
Это конечно информация для избранных, но так и быть, поделюсь с тобой. Посмотри тут.
Артур Шевченко
05 сентября 2022, 21:01
1
0
В общем, я установил UsersOnline и он не работает. Я посмотрел ошибки и завёл его. Вот код сниппета getOnlineUsers.
<?php
    /** @var array $scriptProperties */
    /** @var UsersOnline $UsersOnline */
    if (!$UsersOnline = $modx->getService('usersonline', 'UsersOnline', $modx->getOption('usersonline_core_path', null,
            $modx->getOption('core_path') . 'components/usersonline/') . 'model/usersonline/', $scriptProperties)
    ) {
        return 'Could not load UsersOnline class!';
    }
    if (!$pdo = $modx->getService('pdoTools')) {
        return $modx->lexicon('no_pdo');
    }
    $interval = $modx->getOption('timeInterval', $scriptProperties, -1);
    if ($interval == -1) {
        $interval = $modx->getOption('usersonline_time_span');
    }
    $contexts = $modx->getOption('contexts', $scriptProperties, null);
    
    $innerJoin = array();
    /*$innerJoin = $modx->getOption('innerJoin', $scriptProperties, '');
    $innerJoin = $modx->fromJSON($innerJoin);*/
   
    $innerJoin['UsersOnline'] = array(
        'class' => 'userOnline',
        'on'    => 'modUser.id = UsersOnline.user_id',
    );
    $select = array();
    /*if($select = $modx->getOption('select', $scriptProperties, '')){
         $select = $modx->fromJSON($select);
    }*/    
    $select['UsersOnline'] = '*';
    $time = time();
    $startTime = $time - $interval;
    $where = array();
    /*if($where = $modx->getOption('where', $scriptProperties, '')){
        $where = $modx->fromJSON($where);
    }*/
    
    $where[] = array(
        'UsersOnline.lastvisit:>=' => $startTime,
        'UsersOnline.lastvisit:<=' => $time,
    );
    $contextsArray = array();
    if($contexts != null){
        $contextsArray = explode(',', $contexts);
    }
    if (!empty($contextsArray)) {
        $where[] = array(
            'UsersOnline.context_key:IN' => $contextsArray,
        );
    }
    $scriptProperties['where'] = $modx->toJSON($where);
    $scriptProperties['innerJoin'] = $modx->toJSON($innerJoin);
    $scriptProperties['select'] = $modx->toJSON($select);
    $output = $modx->runSnippet('pdoUsers', $scriptProperties);
    return $output;
Вот вызов.
[[!getOnlineUsers?
    &contexts=`web`
]]