Наверх

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

Добавление вкладки на страницу редактирования ресурса

18 апреля 2019, 09:06

Плагин

<?php
switch ($modx->event->name) {
    case 'OnDocFormRender':
        if ($mode == modSystemEvent::MODE_UPD) {
            $modx->controller->addLexiconTopic('core:user');
            $modx->controller->addLastJavascript($modx->getOption('assets_url') . 'components/resourceextender/mgr/resource/tab.js?v=1.0.0');
            
        }
        break;
}

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

Добавляем запись лексикона для строки KB

10 апреля 2019, 10:36

<?php
$path = MODX_CORE_PATH . 'lexicon/';
$dirs = scandir($path);
unset($dirs[0]);
unset($dirs[1]);
foreach ($dirs as $dir) {
    $file = $path . $dir . '/file.inc.php';
    if (is_dir($path . $dir) && file_exists($file)) {
        $content = file_get_contents($file);
        if (strpos($content, 'file_size_bytes') === false &&
            strpos($content, 'file_size_kilobytes') === false) {
            $content = str_replace(
                        '$_lang[\'image_size\']',
                        '$_lang[\'file_size_bytes\'] = \'bytes\';' . PHP_EOL .
                        '$_lang[\'file_size_kilobytes\'] = \'KB\';' . PHP_EOL .
                        '$_lang[\'image_size\']', $content);
            file_put_contents($file, $content);
        }
    }
}

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

Поместить превью и keywords для SeoPRO перед контентом

10 апреля 2019, 10:16

Файл
assets/components/seopro/js/mgr/seopro.js

Меняем:
// ...
        var fieldDesc = new Ext.form.Label({
            forId: 'pagetitle',
            text: _('seopro.focuskeywords_desc'),
            cls: 'desc-under'
        });
        fp.insert(3,fieldDesc); /* было fp.add(field); */
        fp.insert(3,field); /* было fp.add(fieldDesc); */
        fp.doLayout();
    },
    addPanel: function() {
        var fp = Ext.getCmp('modx-resource-main-left');
        fp.insert(3, { /* было fp.add({ */
            xtype: 'panel',
// ...

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

Загрузить все актуальные лексиконы для MODX 3

10 апреля 2019, 09:20

Сначала регистрируемся на crowdin.com, полкчаем API-ключ.

Выполнять скрипт в SSH-консоли:

mkdir core/lexicon/crowdin/
curl -o core/lexicon/crowdin/all.zip "https://api.crowdin.com/api/project/modx-revolution/download/all.zip?login={login}&account-key={api_key}"
unzip core/lexicon/crowdin/all.zip -d core/lexicon/crowdin/
cp -R core/lexicon/crowdin/30/core/lexicon core
rm -rf core/lexicon/crowdin

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

tvSuperSelect - выборка ресурсов по тегам с условием AND

07 декабря 2018, 08:54

Чтобы tvSuperSelect выбирал ресурсы, которые соответствуют сразу всем выбранным тегам, нужно создать копию сниппета tvssResources, назвать её, например, tvssResourcesAnd. В копию вносим следующие изменения:

// ...
    if (!empty($orConditions)) { // Заменяем код внутри этого условия
        foreach ($tags as $i => $tag) {
            $leftJoin[$alias . $i] = array(
                'class' => 'tvssOption',
                'alias' => $alias . $i,
                'on' => $alias . $i . '.resource_id = ' . $class . '.id AND ' .
                        $alias . $i . '.tv_id = ' . $tv . ' AND ' .
                        $alias . $i . '.value = "' . addslashes($tag) . '"',
            );
            $where[0][$alias . $i . '.value:!='] = null;
        }
    }
// ...

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

Генерация YML-файла для Яндекс-Маркета

18 июня 2018, 09:44

<?php
@ini_set('display_errors', 1);

define('MODX_API_MODE', true);
require dirname(dirname(dirname(dirname(__FILE__)))) . '/index.php';
$modx->getService('error','error.modError');
$modx->setLogLevel(modX::LOG_LEVEL_INFO);
$modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML');

if ($modx->cacheManager->get('running', array('cache_key' => 'ymarket'))) {
     echo 'Скрипт работает, повторный запуск отменён';
    exit;
}

$running = true;
$modx->cacheManager->set('running', $running, 0, array('cache_key' => 'ymarket'));

$limit = 500;
$offset = $modx->cacheManager->get('offset', array('cache_key' => 'ymarket'));
$filename = __DIR__ . '/yandexmarket-gen.yml';
// ...

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

Программное создание и заполнение опций товара miniShop2

09 апреля 2018, 08:39

<?php
$resources = array($modx->getObject('modResource', $id));

$miniShop2 = $modx->getService('miniShop2');
require_once MODX_CORE_PATH . 'components/simplehtmldom/simple_html_dom.php';
foreach ($resources as $res) {
    $content = $res->get('content');
    $props = $res->getProperties();
    if (!isset($props['original_content']) || !$props['original_content']) {
        $props['original_content'] = $content;
        $res->setProperties($props);
        $res->save();
    }
    $html = str_get_html($content);
    $characters = $html->find('.character');
    $content = $html->find('.content', 0)->innertext;
    foreach ($characters as $char) {
        $name = $char->find('span', 0)->innertext;
        $val = $char->find('span', 1)->innertext;
        print '<b>'.$name . ' - ' . $val . '</b>' . PHP_EOL;
        if (!$option = $modx->getObject('msOption', array('caption' => $name))) {
            print 'Option not found' . PHP_EOL;
            $key = $res->cleanAlias($name);
            if ($found = $modx->getObject('msOption', array('key' => $key))) {
                print 'Option key exists' . PHP_EOL;
                $key = $key . '_2';
            }
            $option = $modx->newObject('msOption');
            $option->fromArray(array('key' => $key, 'caption' => $name, 'type' => 'textfield'));
            $option->save();
            print 'Option '.$key.' created' . PHP_EOL;
        } else {
            print 'Option found' . PHP_EOL;
        }
        if (!$cop = $modx->getObject('msCategoryOption', array('option_id' => $option->id, 'category_id' => $res->parent))) {
            print 'Category option not found' . PHP_EOL;
            $table = $modx->getTableName('msCategoryOption');
            $sql = "INSERT INTO {$table} (`option_id`,`category_id`,`active`) VALUES ({$option->id}, {$res->parent}, 1);";
            $stmt = $this->modx->prepare($sql);
            $stmt->execute();
            print 'Category option created' . PHP_EOL;
        } else {
            print 'Category option found' . PHP_EOL;
            $q = $modx->newQuery('msCategoryOption');
            $q->command('UPDATE');
            $q->where(array('option_id' => $option->id, 'category_id' => $res->parent));
            $q->set(array('active' => 1));
            $q->prepare();
            $q->stmt->execute();
            print 'Category option updated' . PHP_EOL;
        }
        
        if ($po = $modx->getObject('msProductOption', array('product_id' => $res->id, 'key' => $option->key))) {
            print 'Value found' . PHP_EOL;
            $q = $modx->newQuery('msProductOption');
            $q->command('UPDATE');
            $q->where(array('key' => $option->key));
            $q->set(array('value' => $val));
            $q->prepare();
            $q->stmt->execute();
            print 'Value updated' . PHP_EOL;
        } else {
            print 'Value not found' . PHP_EOL;
            $table = $modx->getTableName('msProductOption');
            if (!is_int($val)) {
                $val = '"' . $val . '"';
            }
            $sql = "INSERT INTO {$table} (`product_id`,`key`,`value`) VALUES ({$res->id}, \"{$option->key}\", {$val});";
            $stmt = $this->modx->prepare($sql);
            $stmt->execute();
            print 'Value created' . PHP_EOL;
        }
    }
}

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

Добавление возможности указать контекст в CatalogFill

27 октября 2017, 15:56

// ...
    public function xls_export($parent_id, $xls_type='Excel5'){
        if (!is_numeric($parent_id)) {
            $this->config['context'] = $parent_id;
            $parent_id = 0;
        }
        require_once realpath(dirname(__FILE__)).'/PHPExcel.php';
        
        $out = array('count'=>0,'filepath'=>'','filename'=>'');
        
        if ($parent_id) {
            $parent_folder = $this->modx->getObject('modResource',$parent_id);
            $this->config['context'] = $parent_folder->get('context_key');
        }
        
        if($this->config['include_categories']){
// ...

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

Отдать пользователю ответ, но продолжить обработку данных

14 октября 2017, 17:14

<?php
$modx->log(1, 'First log: ' . date('H:i:s', time() + 60 * 60 * 2));
if (function_exists('fastcgi_finish_request')) {
    echo 'Готово';
    session_write_close();
    fastcgi_finish_request();
}
sleep(10);
$modx->log(1, 'Second log: ' . date('H:i:s', time() + 60 * 60 * 2));

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

mFilter2 - Вывод результатов на отдельной странице

05 августа 2017, 09:35

<script>
    $(document).ready(function(){
        $(document).on('mse2_load', function(e, data) {
            document.location.href = '{$_modx->makeUrl(35)}' + e.currentTarget.URL.replace('{$_modx->config.site_url}{$_modx->resource.uri}', '');
        });
    });
</script>

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

Авторизация

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


Шаблоны MODX

1 2 Дальше »

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