Алексей Федоров

Алексей Федоров

С нами с 19 октября 2015; Место в рейтинге пользователей: #186
Дмитрий
13 января 2017, 22:53
2
+1
Во первых реши вопрос с сертификатом у регистратора (закажи, установи на хостинг),
после нужно в настройках MODX -> Core -> Система и сервер -> в server_protocol поставить «https», далее
в корне сайта файл-".htaccess " ставишь:

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule .* %{SERVER_NAME}%{REQUEST_URI} [R,L]

или

Вот готовый .htaccess -> «но учти что переадресацию с www. я ставил в настройках хостинга.»

# MODX supports Friendly URLs via this .htaccess file. You must serve web
# pages via Apache with mod_rewrite to use this functionality, and you must
# change the file name from ht.access to .htaccess.
#
# Make sure RewriteBase points to the directory where you installed MODX.
# E.g., "/modx" if your installation is in a "modx" subdirectory.
#
# You may choose to make your URLs non-case-sensitive by adding a NC directive
# to your rule: RewriteRule ^(.*)$ index.php?q=$1 [L,QSA,NC]

RewriteEngine On
RewriteBase /

AddDefaultCharset UTF-8

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
</IfModule>

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

php_flag register_globals Off 
php_flag magic_quotes_gpc Off 
php_value magic_quotes_gpc Off 


# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]



# Make sure .htc files are served with the proper MIME type, which is critical
# for XP SP2. Un-comment if your host allows htaccess MIME type overrides.

#AddType text/x-component .htc



# If your server is not already configured as such, the following directive
# should be uncommented in order to set PHP's register_globals option to OFF.
# This closes a major security hole that is abused by most XSS (cross-site
# scripting) attacks. For more information: http://php.net/register_globals
#
# To verify that this option has been set to OFF, open the Manager and choose
# Reports -> System Info and then click the phpinfo() link. Do a Find on Page
# for "register_globals". The Local Value should be OFF. If the Master Value
# is OFF then you do not need this directive here.
#
# IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS :
#
# Your server does not allow PHP directives to be set via .htaccess. In that
# case you must make this change in your php.ini file instead. If you are
# using a commercial web host, contact the administrators for assistance in
# doing this. Not all servers allow local php.ini files, and they should
# include all PHP configurations (not just this one), or you will effectively
# reset everything to PHP defaults. Consult www.php.net for more detailed
# information about setting PHP directives.

#php_flag register_globals Off



# For servers that support output compression, you should pick up a bit of
# speed by un-commenting the following lines.

#php_flag zlib.output_compression On
#php_value zlib.output_compression_level 5



# The following directives stop screen flicker in IE on CSS rollovers. If
# needed, un-comment the following rules. When they're in place, you may have
# to do a force-refresh in order to see changes in your designs.

#ExpiresActive On
#ExpiresByType image/gif A2592000
#ExpiresByType image/jpeg A2592000
#ExpiresByType image/png A2592000
#BrowserMatch "MSIE" brokenvary=1
#BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
#BrowserMatch "Opera" !brokenvary
#SetEnvIf brokenvary 1 force-no-vary

И готово!
Семён Кудрявцев
23 декабря 2016, 14:02
1
0
У тебя там параметр hooks не указан
Вот пример вызова
[[!AjaxForm?
            &snippet=`FormIt`
            &form=`callback_form`
            &hooks=`email,FormItSaveForm`
            &formName=`Заявка на обратный звонок`
            &formFields=`name,phone`
            &fieldNames=`name==Имя,phone==Телефон`
            &emailTpl=`feedback_from_callback`
            &emailSubject=`Заявка на обратный звонок с сайта`
            &emailFrom=`noreplay@site.ru`
            &emailTo=`admin@email.ru`
            &validate=`name:required,phone:required`
            &placeholderPrefix=`callback`
            &submitVar=`callback_submit`
            &validationErrorMessage=`В форме содержатся ошибки!`
            &successMessage=`Сообщение успешно отправлено`
            ]]
И если ты используешь тестовый тариф на modhost.pro то там отключена функция отправки писем
Василий Столейков
18 сентября 2016, 07:34
2
+1
А вариант тв-галочки и сортировки по этой галочке?
Сортировку можно указать по нескольким полям последовательно, что-то типа этого:
&sortby =`{ "vip":"ASC", "publishedon":"DESC" }`
Если тв-шка называется vip, нужно кажется ещё подключить в вызов сниппета эту тв, проверь.
Василий Наумкин
14 июля 2016, 18:31
2
+4
$count = $modx->getCount('modResource', array('class_key' => 'Ticket', 'createdby' => '15'));
Николай Загумённов
28 мая 2016, 22:56
7
+2
Я использовал компонент tvSuperSelect.
Чтобы с фронта добавлять тэги добавил плагин, который заполняет ТВ поле и таблицу компонента значениями:
<?php
// tvssTagsSave
$tvss = $modx->getService('tvsuperselect', 'tvsuperselect', $modx->getOption('core_path').'components/tvsuperselect/model/tvsuperselect/');
if (!($tvss instanceof tvSuperSelect)) {
    return '';
}

switch ($modx->event->name) {

    case 'OnDocFormSave':
        if (is_object($resource) && is_array($resource->_fields)) {
            $data = $resource->_fields;
            $resource_id = $data['id'];
            // $modx->log(1, print_r($data, 1));

            $flds = $tv_values = array();
            foreach ($data as $key => $value) {
                if ($key == 'tags')  {
                    $tv_id = 1;

                    $array = array_diff($value, array(''));
                    if (!empty($array)) {
                        $flds[] = array(
                            'resource_id' => $resource_id,
                            'tv_id' => $tv_id,
                            'data' => $array,
                        );

                        $tv_values[$tv_id] = $modx->toJSON($array);
                    }
                }
            }
             // пишем в таблицу пакета
            if (!empty($flds)) {
                // $modx->log(1, print_r($flds, 1));

                $table = $modx->getTableName('tvssOption');

                foreach ($flds as $fld) {
                    $sql = 'DELETE FROM '.$table.' WHERE `resource_id` = '.$fld['resource_id'].' AND `tv_id` = '.$fld['tv_id'];
                    $stmt = $modx->prepare($sql);
                    $stmt->execute();
                    $stmt->closeCursor();

                    $values = array();
                    foreach ($fld['data'] as $value) {
                        if (!empty($value)) {
                            $values[] = '('.$fld['resource_id'].',"'.$fld['tv_id'].'","'.addslashes($value).'")';
                        }
                    }

                    if (!empty($values)) {
                        $sql = 'INSERT INTO '.$table.' (`resource_id`,`tv_id`,`value`) VALUES '.implode(',', $values);
                        $stmt = $modx->prepare($sql);
                        $stmt->execute();
                        $stmt->closeCursor();
                    }
                }
            }

            // пишем в таблицу modTemplateVarResource
            if (!empty($tv_values)) {
                //$modx->log(1, print_r($tv_values, 1));

                foreach ($tv_values as $tv_id => $values) {
                    if (!$tv_obj = $modx->getObject('modTemplateVarResource', array(
                        'tmplvarid' => $tv_id,
                        'contentid' => $resource_id,
                    ))) {
                        $tv_obj = $modx->newObject('modTemplateVarResource');
                    }

                    $tv_obj->fromArray(array(
                        'tmplvarid' => $tv_id,
                        'contentid' => $resource_id,
                        'value' => $values,
                    ));
                    $tv_obj->save();
                    // $modx->log(1, print_r($tv_obj->toArray(), 1));

                    unset($tv_obj);
                }
            }
        }
    break;
}
Чтобы выводить во фронте поле добавил сниппет:
<?php
// tvssTagsOptions
/* @var pdoFetch $pdoFetch */
$fqn = $modx->getOption('pdoFetch.class', null, 'pdotools.pdofetch', true);
$path = $modx->getOption('pdotools_class_path', null, MODX_CORE_PATH.'components/pdotools/model/', true);
if ($pdoClass = $modx->loadClass($fqn, $path, false, true)) {
    $pdoFetch = new $pdoClass($modx, $scriptProperties);
} else {
    return false;
}
$pdoFetch->addTime('pdoTools loaded');

if (!$modx->addPackage('tvsuperselect', MODX_CORE_PATH.'components/tvsuperselect/model/')) {
    return false;
}

$tv			= $modx->getOption('tv', $scriptProperties, ''); // TV name or...
$tvid		= $modx->getOption('tvId', $scriptProperties, ''); // ... TV id
$tvInput	= $modx->getOption('tvInput', $scriptProperties, ''); // TV input name
$res		= $modx->getOption('res', $scriptProperties, 0); // Resource id
$tpl		= $modx->getOption('tpl', $scriptProperties, 'tpl.tvssTagsOptions');

$tv_where = $tv ? array( 'name' => $tv ) : '';
$tv_where = $tv_where ?: ( $tvid? array( 'id' => $tvid ) : '' );
// print_r($tv_where);

if( empty($tv_where) ) { return; }


if( $tv_obj = $modx->getObject('modTemplateVar', $tv_where) )
{
	$value = '';
	if( $res != 0 && $tv_val_obj = $modx->getObject('modTemplateVarResource', array(
			'tmplvarid'	=> $tv_obj->id,
			'contentid'	=> $res,
	))) {
		$value = $tv_val_obj->value;
	}
	$value_arr = $modx->fromJSON($value); // Массив со значениями тэгов конкретного ресурса

	// Массив, который мы передадим в процессор, там его ловить в $scriptProperties
	$processorProps = array(
	    'tv_id' => $tv_obj->id,
	);
	// Массив опций для метода runProcessor
	$otherProps = array(
	    // Здесь указываем где лежат наши процессоры
	    'processors_path' => $modx->getOption('core_path') . 'components/tvsuperselect/processors/'
	);
	// Запускаем
	$response = $modx->runProcessor('mgr/option/getoptions', $processorProps, $otherProps);
	// И возвращаем ответ от процессора

	$options_array = $modx->fromJSON($response->response); // Массив со всеми тэгами

	
	
	if (is_array($options_array['results']) || is_object($options_array['results'])) {
		foreach($options_array['results'] as $v) {
			$selected = '';
			if (is_array($value_arr) || is_object($value_arr)) {
				foreach ($value_arr as $key => $val) {
					if ($v['value'] == $val) {
						$selected = "selected=\"selected\"";
					}
				}
			}
			$options .= "<option ". $selected ." value=\"". $v['value'] ."\">";
			$options .= $v['value'];
			$options .= "</option>";
			$selected = "";
		}
	}
	
	$return = $modx->getChunk($tpl, array(
		'tv_id'			=> $tv_obj->id,
		'tv_name'		=> $tv_obj->name,
		'tv_input_name'	=> $tvInput ?: $tv_obj->name,
		'tv_value'		=> $value,
		'res_id'		=> $res,
		'options'		=> $options
	));
	
	return $return;
}
else {
	return;
}
Чанк tpl.tvssTagsOptions:
<select name="tags[]" multiple="multiple" class="js-tvSuperSelect-tags form-control" id="ticket-tags">
	[[+options]]
</select>
В чанке с формой добавления/редактирования тикетов добавил:
<link href="/js/select2-4.0.2/dist/css/select2.min.css" rel="stylesheet" />
	<script src="/js/select2-4.0.2/dist/js/select2.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function(){
			$(".js-tvSuperSelect-tags").select2({
				tags: true
			});
		});
	</script>
	<div class="form-group">
		<label for="ticket-sections">Тэги</label>
		[[!tvssTagsOptions? &tv=`tags` &res=`0`]]
		// В чанке редактирования [[!tvssTagsOptions? &tv=`tags` &res=`[[+id]]`]]
		<span class="error"></span>
	</div>
Прикрутил к полю тэгов Select2, чтобы тэги было удобно заполнять и все.
Может кому пригодится =)
Иван Бочкарев
24 мая 2016, 12:12
1
+1
Чанк ui-button

<li>
   <a href="#" data-filter=".[[+alias]]" class="">[[+pagetitle]]</a>
</li>
Чанк с оформлением article-tpl-projects

<article class="project-item [[getAlias? &id=`[[+parent]]`]]">
	<figure>
		<img src="[[+476x344]]" alt="[[+pagetitle]]" class="img-responsive">
		<figcaption>
            <div class="caption-wrap">
               <div class="actions">
					<a href="[[~[[+id]]]]" class="btn-border btn-border-sm" title="[[+pagetitle]]">
                  		<img src="../img/link.svg" alt="" class="">
                	</a>
                </div>
            </div>
         </figcaption>
	</figure>
	<div class="project-info">
		<a href="[[~[[+id]]]]">[[+pagetitle]]</a>
		<div class="p-client">[[+tv.client]]</div>
	</div>
</article>
в нем указан вызов снипета который и проставляет алиас
<article class="project-item [[getAlias? &id=`[[+parent]]`]]">
Сниппет getAlias

<?php
/**
 * getAlias
 *
 * DESCRIPTION
 *
 * This snippet returns the alias of a page matching an id
 *
 * USAGE:
 *
 * [[!getAlias? &id=`[[+parent]]`]]
 */
 
$page = $modx->getObject('modResource', $id);
if(!empty($page)) {
    return $page->get('alias');
}
return '';
Дмитрий Кондаков
24 апреля 2016, 09:36
1
+1
Еще можно плагином на изменение статуса, это в том случае если покупатель оплачивает не через сайт например. Конструкция следующая:
<?php
switch($modx->event->name) {
  case 'msOnChangeOrderStatus':
    
    # Если статус - оплачен
    if ($status == 2) {

      #
      #
      # тут получаем ссылку на скачивание заказанного товара, 
      # email пользователя, номер заказа ну и все то что нужно для отправки письма
      #
      # И отправляем ссылку на email
      #
      #
      
    }
    
    break;
}
Илья Уткин
16 февраля 2016, 16:11
3
+3
https://modx.pro/users/[[*createdby:userinfo=`username`]]/
Сергей Шлоков
29 декабря 2015, 18:30
2
+2
При использовании AjaxForm сообщения о точной ошибке заполнения не выводятся. Вот тут можно почитать, как сделать нечто подобное
Василий Наумкин
28 декабря 2015, 15:30
4
+3
Обожемой, зачем откапывать рецепты из Evolution?
<?php
switch ($modx->event->name) {    
	case 'OnBeforeDocFormSave':
		if ($modx->user->get('id') != $object->get('createdby')) { 
			$modx->event->output('Ошибка! У вас нет прав редактировать этот документ');
		};
	break;
}