Михаил

Михаил

С нами с 18 апреля 2013; Место в рейтинге пользователей: #573
Николай Загумённов
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, чтобы тэги было удобно заполнять и все.
Может кому пригодится =)