Advertisement
jon4god

msextraaddressfields.plugin.php

Mar 10th, 2025 (edited)
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.08 KB | None | 0 0
  1. <?php
  2.  
  3. switch ($modx->event->name) {
  4.     case 'msOnBeforeCreateOrder':
  5.         // Убедитесь, что переменная $msOrder определена
  6.         if (!isset($msOrder)) {
  7.             $modx->log(modX::LOG_LEVEL_ERROR, 'Ошибка: $msOrder не определен.');
  8.             return;
  9.         }
  10.  
  11.         $address = $msOrder->getOne('Address');
  12.         $properties = array();
  13.  
  14.         // Обработка полей из $_POST
  15.         foreach ($_POST as $key => $value) {
  16.             if (strpos($key, 'extfld_') !== false) {
  17.                 // Предотвращаем XSS, обеспечивая очистку входных данных
  18.                 $properties[$key] = htmlentities($value, ENT_COMPAT | ENT_HTML401, 'UTF-8');
  19.             }
  20.         }
  21.  
  22.         if (!empty($properties)) {
  23.             //$modx->log(modX::LOG_LEVEL_ERROR, 'Setting properties: ' . json_encode($properties));
  24.             $address->set('properties', json_encode($properties));
  25.         }
  26.         break;
  27.  
  28.     case 'msOnBeforeUpdateOrder':
  29.         // Убедитесь, что переменная $msOrder определена
  30.         if (!isset($msOrder)) {
  31.             $modx->log(modX::LOG_LEVEL_ERROR, 'Ошибка: $msOrder не определен.');
  32.             return;
  33.         }
  34.        
  35.         $address = $msOrder->getOne('Address');
  36.         $properties = array();
  37.        
  38.         // Собираем данные из правильного источника
  39.         if (isset($_POST['addr_properties'])) {
  40.             $properties = json_decode($_POST['addr_properties'], true);
  41.         }
  42.        
  43.         // Альтернативный вариант: сбор из полей формы
  44.         foreach ($_POST as $key => $value) {
  45.             if (strpos($key, 'addr_properties_') === 0) {
  46.                 $fieldName = str_replace('addr_properties_', '', $key);
  47.                 $properties[$fieldName] = $value;
  48.             }
  49.         }
  50.        
  51.         // Получаем текущие свойства из базы данных
  52.         $currentProperties = json_decode($address->get('properties'), true) ?: array();
  53.        
  54.         // Обновляем свойства, оставляя пустые значения без изменений
  55.         foreach ($properties as $key => $value) {
  56.             if ($value !== '' && $value !== null && $value !== undefined) {
  57.                 $currentProperties[$key] = $value;
  58.             }
  59.         }
  60.        
  61.         // Сохраняем все свойства, даже те, которые не были изменены
  62.         if (!empty($currentProperties)) {
  63.             $address->set('properties', json_encode($currentProperties));
  64.         }
  65.         break;
  66.  
  67.     case 'msOnManagerCustomCssJs':
  68.         if (!isset($page) || $page != 'orders') {
  69.             return;
  70.         }
  71.  
  72.         $modx->controller->addHtml("
  73.        <script type='text/javascript'>
  74.            Ext.onReady(function() {
  75.                console.log('Ext.onReady triggered');
  76.                
  77.                // Проверяем доступность компонента
  78.                Ext.ComponentMgr.onAvailable('minishop2-window-order-update', function() {
  79.                    console.log('minishop2-window-order-update available');
  80.                    
  81.                    this.on('beforesubmit', function(form, action) {
  82.                        console.log('beforesubmit event triggered');
  83.                        console.log('Form:', form);
  84.                        console.log('Action:', action);
  85.                        
  86.                        // Проверяем, является ли action объектом
  87.                        if (typeof action !== 'object') {
  88.                            console.error('Action is undefined');
  89.                            return;
  90.                        }
  91.                        
  92.                        var properties = this.record.addr_properties || {};
  93.                        
  94.                        // Фильтруем поля формы, оставляя только те, что начинаются с 'addr_properties_'
  95.                        form.items.each(function(field) {
  96.                            console.log('Field:', field);
  97.                            if (field.name && field.name.startsWith('addr_properties_') && typeof field.getValue === 'function') {
  98.                                var key = field.name.replace('addr_properties_', '');
  99.                                var value = field.getValue();
  100.                                console.log('Field value:', key, value);
  101.                                if (value !== '' && value !== null && value !== undefined) {
  102.                                    properties[key] = value;
  103.                                    console.log('Field value added:', key, properties[key]);
  104.                                } else {
  105.                                    console.log('Ignoring empty field:', key);
  106.                                }
  107.                            }
  108.                        });
  109.                        
  110.                        if (!action.extraParams) {
  111.                            console.log('action.extraParams is undefined, initializing it');
  112.                            action.extraParams = {};
  113.                        }
  114.                        action.extraParams.addr_properties = JSON.stringify(properties);
  115.                        console.log('Extra params:', action.extraParams);
  116.                    });
  117.                    
  118.                    // Проверяем существование miniShop2 и его конфигурации
  119.                    if (typeof miniShop2 !== 'undefined' && miniShop2.config && miniShop2.config['order_address_fields'].includes('properties')) {
  120.                        if (this.record.addr_properties) {
  121.                            var key;
  122.                            for (key in this.record.addr_properties) {
  123.                                const value_key = this.record.addr_properties[key];
  124.                                
  125.                                if (value_key) {var old_value_key = ': ' + value_key + ' (cкопировать ниже)';} else {var old_value_key = ''}
  126.                        
  127.                                // Добавляем редактируемое поле
  128.                                this.fields.items[2].items.push(
  129.                                    {
  130.                                        xtype: 'textfield',
  131.                                        name: 'addr_properties_' + key,
  132.                                        fieldLabel: _('ms2_properties_' + key) + old_value_key,
  133.                                        anchor: '100%',
  134.                                        style: 'border:1px solid #efefef;width:95%;padding:5px;',
  135.                                        value: value_key
  136.                                    }
  137.                                );
  138.                            }
  139.                        }
  140.                    }
  141.                });
  142.            });
  143.        </script>");
  144.         break;
  145. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement