Вячеслав Варов

Вячеслав Варов

Был в сети 20 января 2026, 11:18
Заказы принимаю
Вячеслав Варов
Вячеслав Варов
Отвечаю на свой же вопрос — можно вот так

<?php
switch ($modx->event->name) {
    case 'OnHandleRequest':
        // Загрузка общих настроек
        $site_all = MODX_CORE_PATH . 'config/settings/';
        if (file_exists($site_all) && is_dir($site_all)) {
            foreach (glob($site_all . '*.inc.php') as $file) {
                $response = require($file);
                if (is_array($response)) {
                    $modx->config = array_merge($modx->config, $response);
                }
            }
        }
        
        // Конфигурация для сайта с конфигом MODX_CONFIG_KEY
        $site_dir = MODX_CORE_PATH . 'config/settings/' . MODX_CONFIG_KEY . '/';
        
        if (file_exists($site_dir) && is_dir($site_dir)) {
            foreach (glob($site_dir . '*.inc.php') as $file) {
                $response = require($file);
                if (is_array($response)) {
                    $modx->config = array_merge($modx->config, $response);
                }
            }
        }
        
        // Конфигурация для текущего контекста
        $context_key = $modx->context->get('key');
        $context_dir = MODX_CORE_PATH . 'config/settings/' . $context_key . '/';
        
        if (file_exists($context_dir) && is_dir($context_dir)) {
            foreach (glob($context_dir . '*.inc.php') as $file) {
                $response = require($file);
                if (is_array($response)) {
                    $modx->config = array_merge($modx->config, $response);
                }
            }
        }
        break;
}
?>
Структура папок
core/
└── config/
    └── settings/
        ├── common.inc.php           // Общие настройки
        ├── config1/
        │   └── config1-settings.inc.php   // Настройки для MODX_CONFIG_KEY = config1
        ├── config2/
        │   └── config2-settings.inc.php   // Настройки для MODX_CONFIG_KEY = config2
        ├── web/
        │   └── web-settings.inc.php       // Настройки для контекста web
        └── en/
            └── en-settings.inc.php        // Настройки для контекста en
Вид настроек например для
core/config/settings/en/en-settings.inc.php
<?php
return [
    'site_url' => 'https://your-uz-site-url.com/',
    // Добавьте другие настройки контекста здесь
];
?>
Андрей Шевяков
Андрей Шевяков
Всегда выставляю параметр friendly_alias_restrict_chars_pattern равным
/[\0\x0B\t\n\r\f\a&=+°%#«»…<>—№!",.()\/\~:`@\?\[\]\{\}\|\^\'\\\\]/
И url у ресурсов получается четким без лишних символов, только тире между словами остаются. Все остальные настройки translit стандартные. Поисковики вроде норм индексируют страницы.

По поводу файлов тоже нет проблем при загрузке.
Ilya Gureshidze
Ilya Gureshidze
Как обычно: сам задал вопрос — сам отвечаю.
1. Добавил поля id_1C и id_parent_1C в modx_site_content
2. В плагине на OnMODXInit (у меня там куча полей для расширения разных классов)
написал
$modx->map['modResource']['fields']['id_1C'] = '';
    	$modx->map['modResource']['fields']['id_parent_1C'] = '';
    	$modx->map['modResource']['fieldMeta']['id_1C'] = array(
		'dbtype' => 'varchar',
		'precision' => 50,
		'phptype' => 'string',
		'null' => false,
		'default' => ''
	);
	$modx->map['modResource']['fieldMeta']['id_parent_1C'] = array(
		'dbtype' => 'varchar',
		'precision' => 50,
		'phptype' => 'string',
		'null' => false,
		'default' => ''
	);
3. В плагине на OnDocFormSave и onDocFormPrerender
switch ($modx->event->name) {
    case 'OnDocFormPrerender':
        $id_1C = '';
        $id_parent_1C = '';
        
        if (isset($scriptProperties['resource'])) {
            if (is_object($resource)) {
                $id_1C = $resource->get('id_1C');
                $id_parent_1C = $resource->get('id_parent_1C');
            }
        }
$modx->controller->addHtml(<<<HTML
<script>
    Ext.ComponentMgr.onAvailable('modx-resource-main-left', function(page) {
        page.on('beforerender', function() {
            page.insert(2,{
                xtype: 'textfield'
                ,name: 'id_1C'
                ,value: '{$id_1C}'
                ,anchor: '100%'
                ,layout: 'anchor'
                ,fieldLabel: 'ID 1C'
            });
            page.insert(3,{
                xtype: 'textfield'
                ,name: 'id_parent_1C'
                ,value: '{$id_parent_1C}'
                ,anchor: '100%'
                ,layout: 'anchor'
                ,fieldLabel: 'ID родителя 1C'
            });
        })
    });
</script>
HTML
);
        break;
        
    case 'OnDocFormSave':
        $resource->set('id_1C', $_POST['id_1C']);
        $resource->set('id_parent_1C', $_POST['id_parent_1C']);
        break;
}
return;
Все заработало.
Баха Волков
Баха Волков
Если обойтись без сниппетов, то включаем fenom и погнали:

{var $resources = $_modx->runSnippet('pdoResources', [
    'parents' => 0,
    'return' => 'json'
])}

{var $array  = $resources | fromJSON}

{if $array}
<div id="verticalTab">
    <ul class="resp-tabs-list">
        {foreach $array as $r}
            <li>{$r.pagetitle}</li>
        {/foreach}
    </ul>
    <div class="resp-tabs-container">
        {foreach $array as $r}
            <div>{$r.content}</div>
        {/foreach}
    </div>
</div>
{/if}
Роман Ильин
Роман Ильин
Сниппет для удаления старых версий:

<?php
/**
 * versionCleanX
 *
 * @author Scott Pronych, September 27, 2013
 *
 * DESCRIPTION
 *
 * For use with VersionX to delete old content
 *
 * PROPERTIES:
 *
 * &contentType - can be resource, chunk, plugin, snippet, template, or templatevar
 * &maxVersions - integer value for max number of versions you would like to keep
 *
 * USAGE:
 *
 * [[!versionCleanX? &contentType=`resource` &maxVersions=`10`]]
 *
 */
 
$cx_type = $modx->getOption('contentType', $scriptProperties, 'resource');
$cx_max = (int) $modx->getOption('maxVersions', $scriptProperties, 5);
 
$GLOBALS['count'] = 1;
$GLOBALS['total'] = 0;
$GLOBALS['deleted'] = 0;
$GLOBALS['page_total'] = 0;
$GLOBALS['page_deleted'] = 0;
$GLOBALS['page_name'] = '';
$GLOBALS['prev_content_id'] = 0;
$GLOBALS['prev_version_id'] = 0;
 
switch ($cx_type) {
    case 'chunk':
        $name = 'name';
        break;
    case 'plugin':
        $name = 'name';
        break;
    case 'snippet':
        $name = 'name';
        break;
    case 'template':
        $name = 'templatename';
        break;
    case 'templatevar':
        $name = 'name';
        break;
    default:
        $name = 'title';
        $cx_type = 'resource';
}
 
$GLOBALS['db_name'] = 'modx_versionx_' . $cx_type;
 
function delete_row ($id) {
    global $modx;
    $query = "DELETE FROM `" . $GLOBALS['db_name'] . "` WHERE version_id = '" . $id . "'";
    $result = $modx->query($query);
    if (!is_object($result)) return false;
    else {
        $GLOBALS['deleted']++;
        $GLOBALS['page_deleted']++;
        $GLOBALS['page_total']++;
        $GLOBALS['total']++;
        $GLOBALS['count']++;
        return true;
    }
}
 
function log_row () {
    $GLOBALS['data'] .= '<tr><td>' . $GLOBALS['page_name'] . '</td><td>' . $GLOBALS['page_total'] . '</td><td>' . $GLOBALS['page_deleted'] . "</td></tr>\n";
    $GLOBALS['page_deleted'] = 0;
    $GLOBALS['page_total'] = 1;
    $GLOBALS['count'] = 1;
}
 
$query = "SELECT version_id, content_id, " . $name . " AS page_title FROM `" . $GLOBALS['db_name'] . "` ORDER BY content_id ASC, version_id DESC";
 
$GLOBALS['data'] = '';
$output = 'An error occurred: ';
$versionx = $modx->query($query);
if (!is_object($versionx)) {
   return $output . 'query error ' . print_r($modx->errorInfo(), true);
}
else {
 
while($row = $versionx->fetch(PDO::FETCH_ASSOC)) {
    // New content_id so reset
    if ($prev_content_id == 0) {
        $prev_content_id = $row['content_id'];
        $prev_version_id = $row['version_id'];
        $GLOBALS['total']++;
        $GLOBALS['page_total']++;
        $GLOBALS['count']++;
        $GLOBALS['page_name'] = $row['page_title'];
    }
    elseif ($prev_content_id != $row['content_id']) {
        if ($GLOBALS['count'] > $cx_max) {
            if (!delete_row($prev_version_id)) return $output .  'deleting row for ' . $GLOBALS['page_name'] . ' Row: ' . $prev_content_id . ' ' . print_r($modx->errorInfo(), true);
            $GLOBALS['page_total']--;
 
        }
        else {
            $GLOBALS['total']++;
            $GLOBALS['count']++;
        }
        log_row();
        $prev_content_id = $row['content_id'];
        $prev_version_id = $row['version_id'];
        $GLOBALS['page_name'] = $row['page_title'];
    }
    // Content count is over the max so delete previous row
    elseif ($GLOBALS['count'] > $cx_max) {
            delete_row($prev_version_id);
            $prev_content_id = $row['content_id'];
            $prev_version_id = $row['version_id'];
    }
    else {
        $GLOBALS['count']++;
        $GLOBALS['page_total']++;
        $GLOBALS['total']++;
        $prev_content_id = $row['content_id'];
        $prev_version_id = $row['version_id'];
    }
}
log_row();
 
if ($GLOBALS['data'] != '') {
$output = '<h3>VersionX Cleanup for ' . $GLOBALS['db_name'] . '</h3>
<p>Total records: <strong>' . $GLOBALS['total'] . '</strong>
Total deleted: <strong>' . $GLOBALS['deleted'] . '</strong></p>
<table class="table table-striped">
<thead>
<tr>
<th>Page name</th>
<th>Total found</th>
<th>Deleted</th>
</tr>
</thead>
<tbody>
' . $GLOBALS['data'] .  '</tbody></table>
';
}
else $output = 'Error: no data found.';
}
 
$query = "OPTIMIZE TABLE `" . $GLOBALS['db_name'] . "`";
$versionx = $modx->query($query);
if (!is_object($versionx)) {
   $output = 'Optimize error ' . print_r($modx->errorInfo(), true) . $output;
}
 
return $output;


Вызывать так:
[[!versionCleanX? &contentType=`resource` &maxVersions=`10`]]