Всего 125 937 комментариев

Роман
02 августа 2022, 13:47
0
Ну это новая версия, для modx3, нажмите удалить, и поставьте предыдущую версию.
Евгений Дубровин
02 августа 2022, 12:16
0
ну т.е. вопрос сводится к тому, как переменную (js или php) в json передать видимо)
R2m0x94 (Vasily)
01 августа 2022, 21:21
0
Ну я в плагин добавил на событие OnUserFormPrerender и всё хорошо.
alex
01 августа 2022, 21:14
+1
Подскажи пожалуйста, куда именно добавить в js список значений?
Ilya
01 августа 2022, 12:30
0
Павел, огромное вам спасибо! Задача решена.
Павел Романов
01 августа 2022, 12:25
1
+1
К строке приведите:
// .............
foreach($content_currency->Record as $currency) {
    $items .= $modx->getChunk($tpl, array(
        'date' => (string)$currency->attributes()->Date,
        'value' => (string)$currency->Value,
    ));
}
// .............
Ilya
01 августа 2022, 12:11
0
Да, задача вывести этим сниппетом только курсы доллара по дням.
Поэтому использовал второй вариант без функции.
Но не могу понять, почему-то [[+date]] и [[+value]] возвращаются пустыми.
Роман
01 августа 2022, 12:09
0
Ну вам там выше писали. В чем проблема. Можете, просто выводить картинки из thumb, если нужны medium:
{$thumb | replace: "/small/" : "/medium/"}
Павел Романов
01 августа 2022, 12:00
1
+1
Да, добавьте точку с запятой, я опечатался.

Если Вы используете функцию, то нужно в ней объявить глобальную переменную $modx:
function get_currency_td($currency_code = 'R01235') {
    global $modx;
    $out = '';
    $date_start = date('d/m/Y', strtotime('-30 days')); // Дата начала выборки
    $date = date('d/m/Y'); // Текущая дата (используется для кэша и для конца выборки)
    $cache_time_out = 86400; // Время жизни кэша в секундах
    $file_currency_cache = './currency.xml'; // Файл кэша
    if(!is_file($file_currency_cache) || filemtime($file_currency_cache) < (time() - $cache_time_out)) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://www.cbr.ru/scripts/XML_dynamic.asp?date_req1='.$date_start.'&date_req2='.$date.'&VAL_NM_RQ='.$currency_code);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $out = curl_exec($ch);
        curl_close($ch);
        file_put_contents($file_currency_cache, $out);
    }
    $content_currency = simplexml_load_file($file_currency_cache);
    $content_currency_result = ''; // Переменная для объединения всех дней в одну группу
    
    foreach($content_currency->Record as $currency) {
        $items .= $modx->getChunk($tpl, array(
            'date' => $currency->attributes()->Date,
            'value' => $currency->Value,
        ));
    }	
    if($items != '') $out = $modx->getChunk($tplWrapper, array('items' => $items));
    return $out;
}
Но потом, естественно, в сниппете где-то нужно эту функцию вызывать.

Но если у Вас задача вывести этим сниппетом только курсы доллара, функция не нужна, но надо непосредственно указать код валюты (в 9 строке):
<?php
$out = '';
$date_start = date('d/m/Y', strtotime('-30 days')); // Дата начала выборки
$date = date('d/m/Y'); // Текущая дата (используется для кэша и для конца выборки)
$cache_time_out = 86400; // Время жизни кэша в секундах
$file_currency_cache = './currency.xml'; // Файл кэша
if(!is_file($file_currency_cache) || filemtime($file_currency_cache) < (time() - $cache_time_out)) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.cbr.ru/scripts/XML_dynamic.asp?date_req1='.$date_start.'&date_req2='.$date.'&VAL_NM_RQ=R01235');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $out = curl_exec($ch);
    curl_close($ch);
    file_put_contents($file_currency_cache, $out);
}
$content_currency = simplexml_load_file($file_currency_cache);
$content_currency_result = ''; // Переменная для объединения всех дней в одну группу

foreach($content_currency->Record as $currency) {
    $items .= $modx->getChunk($tpl, array(
        'date' => $currency->attributes()->Date,
        'value' => $currency->Value,
    ));
}	
if($items != '') $out = $modx->getChunk($tplWrapper, array('items' => $items));
return $out;
Константин
01 августа 2022, 11:53
0
Убрал 'includeThumbs' => 'medium' — дубли пропали. Как так?
Роман
01 августа 2022, 11:50
0
Ответить даже если предположить, что проблема в этом: AND `msProduct`.`id` IN (4,4,4,4,4,27,28)
Запрос выводит 7 строк, хотя долен 3.
Попробуйте уберите: 'includeThumbs' => 'medium'
Константин
01 августа 2022, 11:47
0
Спасибо, помогло. А в чем была проблема? На других сайтах такого не наблюдается.
Alexey
01 августа 2022, 11:32
0
mFilter2 тут не при чем! Речь идет про msProducts
Константин
01 августа 2022, 11:32
0
0.0000961: pdoTools loaded.
0.0001519: Conditions prepared
0.0000250: xPDO query object created
0.0003450: Included list of tvs: available
0.0001450: leftJoined msProductData as Data
0.0000710: leftJoined msVendor as Vendor
0.0000811: leftJoined msProductFile as medium
0.0000720: leftJoined modTemplateVarResource as TVavailable
0.0000021: Grouped by msProduct.id, `medium`.url
0.0001230: Added selection of msProduct: SQL_CALC_FOUND_ROWS `id`, `type`, `contentType`, `pagetitle`, `longtitle`, `description`, `alias`, `alias_visible`, `link_attributes`, `published`, `pub_date`, `unpub_date`, `parent`, `isfolder`, `introtext`, `richtext`, `template`, `menuindex`, `searchable`, `cacheable`, `createdby`, `createdon`, `editedby`, `editedon`, `deleted`, `deletedon`, `deletedby`, `publishedon`, `publishedby`, `menutitle`, `donthit`, `privateweb`, `privatemgr`, `content_dispo`, `hidemenu`, `class_key`, `context_key`, `content_type`, `uri`, `uri_override`, `hide_children_in_tree`, `show_in_tree`, `properties`, `seotabs_searchable`
0.0000441: Added selection of msProductData: `article`, `price`, `old_price`, `weight`, `image`, `thumb`, `vendor`, `made_in`, `new`, `popular`, `favorite`, `tags`, `color`, `size`, `source`
0.0000432: Added selection of msVendor: `name` AS `vendor.name`, `resource` AS `vendor.resource`, `country` AS `vendor.country`, `logo` AS `vendor.logo`, `address` AS `vendor.address`, `phone` AS `vendor.phone`, `fax` AS `vendor.fax`, `email` AS `vendor.email`, `description` AS `vendor.description`, `properties` AS `vendor.properties`
0.0000269: Added selection of msProductFile: url as `medium`
0.0000069: Added selection of modTemplateVarResource: IFNULL(`value`, '') AS `available`
0.0000100: Replaced TV conditions
0.0000260: Processed additional conditions
0.0001669: Added where condition: class_key=msProduct, msProduct.id:IN(4,4,4,4,4,27,28), msProduct.published=1, msProduct.deleted=0
0.0000062: Replaced TV conditions
0.0000670: Sorted by msProduct.parent, ASC
0.0000851: Sorted by msProduct.menuindex, ASC
0.0000029: Limited to 12, offset 0
0.0002210: SQL prepared «SELECT SQL_CALC_FOUND_ROWS `msProduct`.`id`, `msProduct`.`type`, `msProduct`.`contentType`, `msProduct`.`pagetitle`, `msProduct`.`longtitle`, `msProduct`.`description`, `msProduct`.`alias`, `msProduct`.`alias_visible`, `msProduct`.`link_attributes`, `msProduct`.`published`, `msProduct`.`pub_date`, `msProduct`.`unpub_date`, `msProduct`.`parent`, `msProduct`.`isfolder`, `msProduct`.`introtext`, `msProduct`.`richtext`, `msProduct`.`template`, `msProduct`.`menuindex`, `msProduct`.`searchable`, `msProduct`.`cacheable`, `msProduct`.`createdby`, `msProduct`.`createdon`, `msProduct`.`editedby`, `msProduct`.`editedon`, `msProduct`.`deleted`, `msProduct`.`deletedon`, `msProduct`.`deletedby`, `msProduct`.`publishedon`, `msProduct`.`publishedby`, `msProduct`.`menutitle`, `msProduct`.`donthit`, `msProduct`.`privateweb`, `msProduct`.`privatemgr`, `msProduct`.`content_dispo`, `msProduct`.`hidemenu`, `msProduct`.`class_key`, `msProduct`.`context_key`, `msProduct`.`content_type`, `msProduct`.`uri`, `msProduct`.`uri_override`, `msProduct`.`hide_children_in_tree`, `msProduct`.`show_in_tree`, `msProduct`.`properties`, `msProduct`.`seotabs_searchable`, `Data`.`article`, `Data`.`price`, `Data`.`old_price`, `Data`.`weight`, `Data`.`image`, `Data`.`thumb`, `Data`.`vendor`, `Data`.`made_in`, `Data`.`new`, `Data`.`popular`, `Data`.`favorite`, `Data`.`tags`, `Data`.`color`, `Data`.`size`, `Data`.`source`, `Vendor`.`name` AS `vendor.name`, `Vendor`.`resource` AS `vendor.resource`, `Vendor`.`country` AS `vendor.country`, `Vendor`.`logo` AS `vendor.logo`, `Vendor`.`address` AS `vendor.address`, `Vendor`.`phone` AS `vendor.phone`, `Vendor`.`fax` AS `vendor.fax`, `Vendor`.`email` AS `vendor.email`, `Vendor`.`description` AS `vendor.description`, `Vendor`.`properties` AS `vendor.properties`, `medium`.url as `medium`, IFNULL(`TVavailable`.`value`, '') AS `available` FROM `modx_site_content` AS `msProduct` LEFT JOIN `modx_ms2_products` `Data` ON `msProduct`.`id` = `Data`.`id` LEFT JOIN `modx_ms2_vendors` `Vendor` ON Data.vendor=Vendor.id LEFT JOIN `modx_ms2_product_files` `medium` ON `medium`.product_id = msProduct.id AND `medium`.`rank` = 0 AND `medium`.path LIKE '%/medium/%' LEFT JOIN `modx_site_tmplvar_contentvalues` `TVavailable` ON `TVavailable`.`contentid` = `msProduct`.`id` AND `TVavailable`.`tmplvarid` = 3 WHERE ( `msProduct`.`class_key` = 'msProduct' AND `msProduct`.`id` IN (4,4,4,4,4,27,28) AND `msProduct`.`published` = 1 AND `msProduct`.`deleted` = 0 ) GROUP BY msProduct.id, `medium`.url ORDER BY msProduct.parent ASC, msProduct.menuindex ASC LIMIT 12 „
0.0016711: SQL executed
0.0001159: Total rows: 7
0.0000899: Rows fetched
0.0001149: Returning raw data
0.0008242: Checked the active modifiers
0.0021989: Loaded “modChunk» with name «gridProductTpl»
0.0020950: Compiled Fenom chunk with name «modchunk/54»
0.0014119: Loaded «modSnippet» with name «msGallery»
0.0044742: Time to load products options
0.1365609: Total time
6 291 456: Memory usage
Константин
01 августа 2022, 11:30
0
Вывод:

{$_modx->runSnippet('!mFilter2', [
	'element' => 'msProducts',
	'class' => 'msProduct',
	'limit' => 12,
	'tplOuter' => 'mFilter2OuterTpl',
	'tpl' => 'gridProductTpl',
	'includeTVs' => 'available',
	'includeThumbs' => 'medium',
	'sortby' => '{ "parent":"ASC","menuindex":"ASC" }',
	'tplPagePrev' => '@INLINE <li><a class="" href="{$href}"><i class="fa fa-angle-left" aria-hidden="true"></i></a></li>',
	'tplPageNext' => '@INLINE <li><a class="" href="{$href}"><i class="fa fa-angle-right" aria-hidden="true"></i></a></li>',
	'tplPagePrevEmpty' => '@INLINE <li><a class="" href="{$href}"><i class="fa fa-angle-left" aria-hidden="true"></i></a></li>',
	'tplPageNextEmpty' => '@INLINE <li><a class="" href="{$href}"><i class="fa fa-angle-right" aria-hidden="true"></i></a></li>',
	'tplPageFirst' => '',
	'tplPageLast' => '',
	'tplPageFirstEmpty' => '',
	'groupby' => 'id',
	'tplPageLastEmpty' => '',
	'suggestionsRadio' => 'resource|parent',
	'filters' => 'msoption|marka,
		          msoption|model,
            	ms|vendor:vendors,
            	parent:parents',
            	
	'aliases' => 'ms|vendor==vendor,
			     msoption|marka==marka,
				 msoption|model==model',
			'tplFilter.outer.default' => 'filterSelectOuter',
	        'tplFilter.row.default' => 'filterSelectRow',
	        
			'tplFilter.outer.vendor' => 'filterCheckboxOuter',
	        'tplFilter.row.vendor' => 'filterCheckboxRow',
	        
	        'tplFilter.outer.marka' => 'filterSelectOuter',
	        'tplFilter.row.marka' => 'filterSelectRow',
	        
	        'tplFilter.outer.model' => 'filterSelectOuter',
	        'tplFilter.row.model' => 'filterSelectRow',
	        
	        'tplFilter.outer.resource|parent:parents' => 'filterSelectOuter',
	        'tplFilter.row.resource|parent:parents' => 'filterSelectRow',
	
])}
Ilya
01 августа 2022, 11:30
0
Павел, добрый день! Спасибо большое за подробный ответ.
Без ; после:
foreach($content_currency->Record as $currency) {
    $items .= $modx->getChunk($tpl, array(
        'date' => $currency->attributes()->Date,
        'value' => $currency->Value,
    ))
на сайте выдает ошибку 500.
Вставляю ; после двух скобок ));, ошибка пропадает.
Но таблица отображается. Но уже с пустыми [[+date]] и [[+value]]. Скриншот: https://skr.sh/sFDGc49PTvC?a.

P.S В сниппет я также добавил строку:
$currency_code = 'R01235';
Думал, что может из-за этого таблица пустая. Но, оказывается не из-за этого.
Роман
01 августа 2022, 11:30
0
Добавьте
'showLog' => 1
И посмотрите, какой запрос формируется.
Константин
01 августа 2022, 11:30
0
Не могу найти такой строчки в сниппете mFilter2