<div class="correlation correlation--first test444" id="corellation-{$tpl_num}">
  <div class="correlation__row">
    <div class="correlation__key">
      <span>{$base_params['description']}</span><span class="help_bt" h_id="{$base_params['help']}"></span>:
    </div>

    <div style="text-align: left; padding: 3px;">
      <select
        class="form-control form-control-160 construct__field--select"
        name="calc_params[{$tpl_num}][{$base_params['name']}]{if $base_params['set_value']}[field]{/if}"
      >
        {if $base_params['set_value']}
          {foreach from=$type_params['fields'] item=field_info}
            {if $field_info['int_name'] == $base_params['set_params']['field']}
              <option
                value="{$field_info['int_name']}"
                data-type="{$field_info['type_field']}"
                data-id="{$field_info['id']}"
                data-mult="{$field_info['mult_value']}"
                selected
              >{$field_info['name_field']}</option>
            {else}
              <option
                value="{$field_info['int_name']}"
                data-type="{$field_info['type_field']}"
                data-id="{$field_info['id']}"
                data-mult="{$field_info['mult_value']}"
              >{$field_info['name_field']}</option>
            {/if}
          {foreachelse}
            <option value="0" selected>{$lang.no_fields}</option>
          {/foreach}
        {else}
          {foreach from=$type_params['fields'] item=field_info}
            {if $field_info['int_name'] == $base_params['set_params']}
              <option
                value="{$field_info['int_name']}"
                data-type="{$field_info['type_field']}"
                data-id="{$field_info['id']}"
                data-mult="{$field_info['mult_value']}"
                selected
              >{$field_info['name_field']}</option>
            {else}
              <option
                value="{$field_info['int_name']}"
                data-type="{$field_info['type_field']}"
                data-id="{$field_info['id']}"
                data-mult="{$field_info['mult_value']}"
              >{$field_info['name_field']}</option>
            {/if}
          {foreachelse}
            <option value="0" selected>{$lang.no_fields}</option>
          {/foreach}
        {/if}
      </select>

      <input hidden name="calc_params[{$tpl_num}][{$base_params['name']}_info]" value="">
      <input hidden name="calc_params[{$tpl_num}][{$base_params['name']}_type]" value="">
    </div>
  </div>

    {*если  вычисления = копировать поле*}
    {if $tpl_info['id'] == '7' || $tpl_info['id'] == '2'}
        <script type="text/javascript">
            (function(){
                var init = false;

                var changeField = function () {
                    if (!init) {
                        var WhereToinsert = document.getElementsByName('calc_params[{$tpl_num}][cur_field1]')[0];
                        var table_id;
                        if (document.getElementById('calc_form')) {
                            table_id = document.getElementById('calc_form').getAttribute('table-id');
                        } else {
                            table_id = document.getElementById('edit_button_form').getAttribute('table-id');
                        }
                        var field_id = document.getElementsByName('calc_params[{$tpl_num}][cur_field2]')[0];
                        var type_field_for_link = field_id[field_id.selectedIndex].getAttribute('data-type');
                        field_id = field_id[field_id.selectedIndex].getAttribute('data-id');
                        var checkedIndex = WhereToinsert[WhereToinsert.selectedIndex].getAttribute('data-id');
                        var type = WhereToinsert[WhereToinsert.selectedIndex].getAttribute('data-type');

                        let url = 'edit_calc.php?ajax=true&action=getCorrelationFields&table='+table_id+'&sel_field='+field_id+'&sel_table=' + table_id;
                        var request = new XMLHttpRequest();
                        request.open('GET', url);
                        request.onreadystatechange = function() {
                            if (request.readyState == 4) {
                                if(request.status == 200) {
                                  $(WhereToinsert).trigger("chosen:updated");
                                    var data = JSON.parse(request.responseText);
                                    deleteWrappers(WhereToinsert);
                                    for (option in data) {
                                        var calc_paramsOption = document.createElement('option');
                                        if(data[option].id === 'id' || data[option].id === 'status' || data[option].id === 'user_id' || data[option].id === 'add_time'){
                                            calc_paramsOption.setAttribute('value',data[option].id);
                                        } else{
                                            calc_paramsOption.setAttribute('value','f' + data[option].id);
                                        }
                                        calc_paramsOption.setAttribute('data-type',data[option].type_field);
                                        calc_paramsOption.setAttribute('data-id',data[option].id);
                                        var textNode = document.createTextNode(data[option].name_field);
                                        calc_paramsOption.appendChild(textNode);
                                        WhereToinsert.appendChild(calc_paramsOption);
                                    }

                                    if (typeof data == "object" && data.length == 0) {
                                      const disabled_option = document.createElement('option');
                                      disabled_option.setAttribute('disabled', 'disabled');
                                      const text_node = document.createTextNode(lang.No_fields_to_match);
                                      disabled_option.appendChild(text_node);
                                      WhereToinsert.appendChild(disabled_option);
                                    }

                                    for (var i =0; i< WhereToinsert.length; i++){
                                        if (WhereToinsert[i].getAttribute('data-id') === checkedIndex) {
                                            WhereToinsert[i].selected = true;
                                        }
                                    }
                                    init = true;
                                }
                            }
                        };
                        request.send(null);

                    } else {
                        var startFieldSelect = document.getElementsByName('calc_params[{$tpl_num}][cur_field2]')[0];
                        var value = startFieldSelect.selectedIndex;
                        var option = startFieldSelect.querySelectorAll('option')[value];
                        var optiondata = option.getAttribute("data-type");
                        var WhereToinsert = document.getElementsByName('calc_params[{$tpl_num}][cur_field1]')[0];
                        var table_id;
                        if (document.getElementById('calc_form')) {
                            table_id = document.getElementById('calc_form').getAttribute('table-id');
                        } else {
                            table_id = document.getElementById('edit_button_form').getAttribute('table-id');
                        }
                        var field_id = document.getElementsByName('calc_params[{$tpl_num}][cur_field2]')[0];
                        field_id = field_id[field_id.selectedIndex].getAttribute('data-id');
                        deleteWrappers(WhereToinsert);

                        let url = 'edit_calc.php?ajax=true&action=getCorrelationFields&table='+table_id+'&sel_field='+field_id+'&sel_table=' + table_id;
                        ajaxReq(url,WhereToinsert);
                    }
                };
                var startField= document.getElementById('corellation-{$tpl_num}');
                $(startField).on('change', function(e) {
                    changeField();
                });
                function deleteWrappers(WhereToinsert) {
                    //общий блок берем из предыдущей функции  =  parentWhere
                    //находим количество элементов
                    var numberofSlices = WhereToinsert.childElementCount;
                    //срезаем всё до первого
                    for (var i = 0; i < numberofSlices; i++) {
                        //сносим всё кроме первого элемента
                        WhereToinsert.lastElementChild.remove()
                    }
                }
                function changeLinks(data, WhereToinsert) {
                    WhereToinsert.innerHTML = "";

                    for (option in data) {
                        var calc_paramsOption = document.createElement('option');
                        if(data[option].id === 'id' || data[option].id === 'status' || data[option].id === 'user_id' || data[option].id === 'add_time'){
                            calc_paramsOption.setAttribute('value',data[option].id);
                        } else{
                            calc_paramsOption.setAttribute('value','f' + data[option].id);
                        }
                        calc_paramsOption.setAttribute('data-type',data[option].type_field);
                        calc_paramsOption.setAttribute('data-id',data[option].id);
                        var textNode = document.createTextNode(data[option].name_field);
                        calc_paramsOption.appendChild(textNode);
                        WhereToinsert.appendChild(calc_paramsOption);
                    }

                    $(WhereToinsert).trigger("chosen:updated");

                    if (typeof data == "object" && data.length == 0) {
                      const disabled_option = document.createElement('option');
                      disabled_option.setAttribute('disabled', 'disabled');
                      const text_node = document.createTextNode(lang.No_fields_to_match);
                      disabled_option.appendChild(text_node);
                      WhereToinsert.appendChild(disabled_option);
                    }

                    if (typeof set_tpl_events === "function") {
                        set_tpl_events();
                    }
                }

                function ajaxReq(url, WhereToinsert) {
                    var request = new XMLHttpRequest();

                    request.open('GET', url);
                    request.onreadystatechange = function() {
                        if (request.readyState == 4) {
                            if(request.status == 200) {
                                changeLinks(JSON.parse(request.responseText), WhereToinsert)
                            }
                        }
                    };
                    request.send(null);
                };

                changeField();
            })(); // Field.tpl 1
        </script>
    {/if}

    {if $base_params['set_value']}
    <script>
        (function () {
            var table_id;
            let isFirstRender = true;
            if (document.getElementById('calc_form')) {
                table_id = document.getElementById('calc_form').getAttribute('table-id');
            } else {
                table_id = document.getElementById('edit_button_form').getAttribute('table-id');
            }
            var select = document.querySelector(".construct__field--select[name=\"calc_params[{$tpl_num}][{$base_params['name']}][field]\"]");
            var hidden = $("[name=\"calc_params[{$tpl_num}][{$base_params['name']}_type]\"]");
            setTypeToHidden(select, "{$tpl_num}", hidden);
            select.onchange = function (e) {
                setTypeToHidden(e.target, "{$tpl_num}", hidden);
            };

            //инициализируем инпут при загрузке страницы
            var url = formURL(select);
            ajaxReq(url,select);

            $(select).on('change', function(e) {
                url = formURL(select);
                ajaxReq(url,select)
            });
            function formURL(select) {
                select = {
                    selectedIndex: select.selectedIndex,
                    value: select[select.selectedIndex].getAttribute('value'),
                    dataType: select[select.selectedIndex].getAttribute('data-type'),
                    dataID:select[select.selectedIndex].getAttribute('data-id')
                };

                dataType = select.dataType;

                var url = '';

                if (dataType === '1') {
                    //просто формируем инпут для числа дальше по коду
                }

                if (dataType === '2') {
                    //если тащим дату
                    //просто формируем инпут для даты дальше по коду
                }
                if (dataType === '3') {
                    //если тащим текст
                    //просто формируем инпут для текста дальше по коду
                }
                if (dataType === '4') {
                    //если тащим список
                    url = 'edit_button.php?ajax=1&field_id=' + select.dataID +'&button_id=-1&action=getListTypeValue';

                }

                if (dataType === '5') {
                  let q = '';
                  if ('{$base_params['set_params']['set_value']}' != '') {
                    q = '&q={$base_params['set_params']['set_value']}';
                  }

                  //если тащим связь
                  url = 'select_value.php?table=' + table_id
                    + '&field=' + select.dataID
                    + q + '&no_filter';
                }

                if (dataType === '7') {
                    //если тащим пользователь
                    url = 'edit_button.php?ajax=1&field_id=' + select.dataID +'&button_id=-1&action=getListTypeValue';
                }

                if (dataType === '14') {
                    //если тащим группу
                    url = 'calc_construct.php?getGroupCons=true';
                }

                if (url === ''){
                    url = 'select_value.php?table=' + table_id + '&field=' + select.dataID;
                }

                return url;
            }

            function ajaxReq(url,select) {
                var request = new XMLHttpRequest();
                request.open('GET', url);
                request.onreadystatechange = function() {
                    if (request.readyState == 4) {
                        if(request.status == 200) {
                            getDataType(select,request.responseText);
                            //инициализация help значка
                            bind_help_bt('calc_tpl_tr');
                        }
                    }
                };
                request.send(null);
            }

            function getDataType(select,responseText){
                select = {
                    selectedIndex: select.selectedIndex,
                    value: select[select.selectedIndex].getAttribute('value'),
                    dataType: select[select.selectedIndex].getAttribute('data-type')
                };
                formField(select.dataType,responseText);

            }

            //обработка
            function formField(dataType,responseText){
                //находим куда вставить созданный элемент
                var where = document.getElementById('corellation-'+'{$tpl_num}');
                var parentWhere = where.parentNode;
                deleteWrappers(parentWhere);
                //определяемся с данными по типу селекта

                switch(dataType) {
                    case '1':
                        //если тащим число
                        formatTextBlock(parentWhere,responseText);
                        break;
                    case '2':
                        //если тащим дату
                        formatDateBlock(parentWhere,responseText);
                        break;
                    case '3':
                        //если тащим текст
                        formatTextBlock(parentWhere,responseText);
                        break;
                    case '4':
                        //если тащим список
                        formatListBlock(parentWhere,responseText);
                        break;
                    case '5':
                        //если тащим связь
                        formatCommunicationsBlock(parentWhere,responseText);
                        createLinkCombobox();
                        break;
                    case '7':
                        //если тащим пользователь
                        formatUserBlock(parentWhere,responseText);
                        break;
                    case '14':
                        //если тащим группу
                        formatGroupBlock(parentWhere,responseText);
                        break;
                    default:
                        formatTextBlock(parentWhere,responseText);
                        break
                }
                isFirstRender = false;
            }

            function formWrapper(){
                var correlationWrapper = document.createElement('div');
                correlationWrapper.classList.add("correlation-wrap--noupperline");
                return correlationWrapper;
            }

            function formRow(){
                var correlationRow = document.createElement('div');
                correlationRow.classList.add("correlation__row");
                var correlationKey = document.createElement('div');
                correlationKey.classList.add("correlation__key");
                var textNode = document.createTextNode('{$base_params['set_value_description']}');
                correlationKey.appendChild(textNode);
                var helpBtn = document.createElement('span');
                helpBtn.classList.add("help_bt");
                helpBtn.setAttribute('h_id',"{$base_params['help']}");
                textNode = document.createTextNode(':');

                correlationKey.appendChild(helpBtn);
                correlationKey.appendChild(textNode);
                correlationRow.appendChild(correlationKey);
                return correlationRow;
            }

            function savedVal(){
                //проверка на наличие
                if('{$base_params['set_params']['set_value']}' !== '') {
                    return '{$base_params['set_params']['set_value']}';
                } else{
                    return false
                }

            }
            var defaultVal = savedVal();

            function formatGroupBlock(parentWhere,responseText) {

                //создаем элемент для вставки
                var correlationWrapper = new formWrapper();
                var correlationRow = new formRow();

                //формируем селект
                var calcParamsName = "calc_params[{$tpl_num}][{$base_params['name']}][set_value]";
                var calc_paramsSelect = document.createElement('select');
                calc_paramsSelect.classList.add("form-control","form-control-160","dont_use_chosen");
                calc_paramsSelect.setAttribute('type','text');
                calc_paramsSelect.setAttribute('name',calcParamsName);
                calc_paramsSelect.setAttribute('value','{$base_params['set_params']['set_value']}');

                responseText =   JSON.parse(responseText);

                //нулевое значение для селекта
                var calc_paramsOption = document.createElement('option');
                calc_paramsOption.setAttribute('value','false');
                textNode = document.createTextNode(' ');
                calc_paramsOption.appendChild(textNode);
                calc_paramsSelect.appendChild(calc_paramsOption);
                var i=1;
                for (userID in responseText) {
                    calc_paramsOption = document.createElement('option');
                    calc_paramsOption.setAttribute('value',userID);
                    textNode = document.createTextNode(responseText[userID]);
                    calc_paramsOption.appendChild(textNode);
                    calc_paramsSelect.appendChild(calc_paramsOption);
                    if(defaultVal === userID) {
                        calc_paramsSelect.selectedIndex = i;
                        defaultVal = false;
                    };
                    i++
                }


                var correlationVal = document.createElement('div');
                correlationVal.classList.add("correlation__val");
                correlationVal.appendChild(calc_paramsSelect);
                correlationRow.appendChild(correlationVal);
                correlationWrapper.appendChild(correlationRow);


                parentWhere.insertBefore(correlationWrapper, null);

            }


            function formatDateBlock(parentWhere,responseText){

                //создаем элемент для вставки

                var correlationWrapper = new formWrapper();
                var correlationRow = new formRow();

                //формируем инпут для вкорячивания даты
                var calcParamsName = "calc_params[{$tpl_num}][{$base_params['name']}][set_value]";
                var calc_paramsInput = document.createElement('input');
                calc_paramsInput.classList.add('inner__input', 'inner__datepicker');

                //вкорячиваем в инпут сохраненную дату(если есть)
                if (defaultVal) calc_paramsInput.setAttribute('value', defaultVal);
                defaultVal = false;

                calc_paramsInput.setAttribute('name',calcParamsName);

                calc_paramsInput.setAttribute('id','datepicker');

                var calc_paramsSpan = document.createElement('span');
                calc_paramsSpan.classList.add('inner__header-item');
                calc_paramsSpan.appendChild(calc_paramsInput);

                var correlationVal = document.createElement('div');
                correlationVal.classList.add("correlation__val");
                correlationVal.appendChild(calc_paramsSpan);
                correlationRow.appendChild(correlationVal);

                correlationWrapper.appendChild(correlationRow);

                parentWhere.insertBefore(correlationWrapper, null);

                var datepicker = $('.inner__datepicker');

                datepicker.datepicker({
                    showOn: "button",
                    dateFormat: lang.date_js_format,
                    buttonImage: "images/calbtn.png",
                    buttonImageOnly: true,
                    buttonText: lang.Calendar,
                    showAnim: (('\v' == 'v') ? "" : "show"),  // в ie не включаем анимацию, тормозит
                }).attr('placeholder', lang.date_placeholder);

            }

            function formatTextBlock(parentWhere,responseText){

                //создаем элемент для вставки
                var correlationWrapper = new formWrapper();
                var correlationRow = new formRow();

                //формируем инпут
                var calcParamsName = "calc_params[{$tpl_num}][{$base_params['name']}][set_value]";
                var calc_paramsInput = document.createElement('input');
                calc_paramsInput.classList.add("form-control","form-control-160");
                calc_paramsInput.setAttribute('type','text');
                calc_paramsInput.setAttribute('name',calcParamsName);
                calc_paramsInput.value = defaultVal ? defaultVal : "";
                if (defaultVal) calc_paramsInput.setAttribute('value', defaultVal)
                defaultVal = false;

                var correlationVal = document.createElement('div');
                correlationVal.classList.add("correlation__val");
                correlationVal.appendChild(calc_paramsInput);
                correlationRow.appendChild(correlationVal);
                correlationWrapper.appendChild(correlationRow);

                parentWhere.insertBefore(correlationWrapper, null);
            }

            function formatCommunicationsBlock(parentWhere, responseText) {
              //формируем массив данных для вставки
              responseText = JSON.parse(responseText);

              var base_params_value = JSON.parse('{$base_params['set_params']['set_value']|@json_encode}') ?? '';

              //формируем селект
              var calcParamsName = "calc_params[{$tpl_num}][{$base_params['name']}][set_value]";
              var calc_paramsSelect = document.createElement('select');
              calc_paramsSelect.classList.add("form-control", "form-control-160", "dont_use_chosen");
              calc_paramsSelect.setAttribute('type', 'text');
              calc_paramsSelect.setAttribute('name', calcParamsName);
              if (isFirstRender) {
                calc_paramsSelect.setAttribute('value', base_params_value);

                // Назначаем текст для поля, иначе calc_paramsSelect не успевает отрендериться и value остается null
                var intervalId = setInterval(function () {
                  var selectedValue = base_params_value;
                  if (!selectedValue) clearInterval(intervalId);
                  if (selectedValue) {
                    calc_paramsSelect.value = selectedValue;
                    if (calc_paramsSelect.value  != '') {
                      clearInterval(intervalId);
                    }
                  }
                }, 600);

                setTimeout(function() {
                  clearInterval(intervalId);
                }, 6000);

                for (let i = 0; i < responseText.length; i++) {
                  if ('{$base_params['set_params']['set_value']}' == responseText[i]['value']) {
                    calc_paramsSelect.setAttribute('acc_value', decodeHtmlEntities(responseText[i]['result']));
                  }
                }
              }

              //создаем элемент для вставки
              var correlationVal = document.createElement('div');
              correlationVal.classList.add("correlation__val");
              correlationVal.appendChild(calc_paramsSelect);

              var correlationRow = new formRow();
              correlationRow.appendChild(correlationVal);

              var correlationWrapper = new formWrapper();
              correlationWrapper.appendChild(correlationRow);
              parentWhere.insertBefore(correlationWrapper, null);
              defaultVal = false;
            }

            function createLinkCombobox(){
              var calc_paramsSelect = $('select[name="calc_params[{$tpl_num}][put_field][set_value]"]');
              var field_id = document.getElementsByName('calc_params[{$tpl_num}][put_field][field]')[0];
              field_id = field_id[field_id.selectedIndex].getAttribute('data-id');
              create_combobox(calc_paramsSelect);

              var input = calc_paramsSelect.next().find($('.autocomplete__input'));
              var url = 'select_value.php?table='+ table_id +'&field='+ field_id +'&no_filter';

              input.on('keyup', function (e) {
                var word = '&q=';
                if (input.val() !== '') {
                  word += encodeURIComponent(input.val());
                }

                var url_by_word = url + word;
                if (e.keyCode === 17 || e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 27 || e.keyCode === 40 || e.keyCode === 37 ||
                  e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 9 || e.keyCode === 20 || e.keyCode === 13) {
                  return;
                }

                var timeout;
                clearTimeout(timeout);
                timeout = setTimeout(function () {
                  autocomplete_ajax_request(calc_paramsSelect, url_by_word, false, true);
                }, 100);
              });

              autocomplete_ajax_request(calc_paramsSelect, url, false);
              input.val(calc_paramsSelect.attr('acc_value'));
            }

            function formatUserBlock(parentWhere,responseText){
                //создаем элемент для вставки

                var correlationWrapper = new formWrapper();
                var correlationRow = new formRow();

                //формируем селект
                var calcParamsName = "calc_params[{$tpl_num}][{$base_params['name']}][set_value]";
                var calc_paramsSelect = document.createElement('select');
                calc_paramsSelect.classList.add("form-control","form-control-160","dont_use_chosen");
                calc_paramsSelect.setAttribute('type','text');
                calc_paramsSelect.setAttribute('name',calcParamsName);
                calc_paramsSelect.setAttribute('value','{$base_params['set_params']['set_value']}');

                responseText = JSON.parse(responseText);
                var i = 0;
                for (userID in responseText) {
                    var calc_paramsOption = document.createElement('option');
                    calc_paramsOption.setAttribute('value',userID);
                    textNode = document.createTextNode(responseText[userID]);
                    calc_paramsOption.appendChild(textNode);
                    calc_paramsSelect.appendChild(calc_paramsOption);
                    if (defaultVal === userID) {
                        calc_paramsSelect.selectedIndex = i;
                        defaultVal = false;
                    }
                    i++;
                }
                var correlationVal = document.createElement('div');
                correlationVal.classList.add("correlation__val");
                correlationVal.appendChild(calc_paramsSelect);
                correlationRow.appendChild(correlationVal);

                correlationWrapper.appendChild(correlationRow);

                parentWhere.insertBefore(correlationWrapper, null);
            }

            function formatListBlock(parentWhere,responseText) {
                responseText = JSON.parse(responseText);

                var correlationWrapper = new formWrapper();
                var correlationRow = new formRow();

                //формируем селект
                var calcParamsName = "calc_params[{$tpl_num}][{$base_params['name']}][set_value]";
                var calc_paramsSelect = document.createElement('select');
                calc_paramsSelect.classList.add("form-control","form-control-160","dont_use_chosen");
                calc_paramsSelect.setAttribute('type','text');
                calc_paramsSelect.setAttribute('name',calcParamsName);

                var i=0;

                for (userID in responseText) {
                    var calc_paramsOption = document.createElement('option');
                    calc_paramsOption.setAttribute('value',userID);
                    textNode = document.createTextNode(responseText[userID]);
                    calc_paramsOption.appendChild(textNode);
                    calc_paramsSelect.appendChild(calc_paramsOption);
                    if (defaultVal === userID) {
                        calc_paramsSelect.selectedIndex = i;
                        defaultVal = false;
                    }
                    i++;
                }

                var correlationVal = document.createElement('div');
                correlationVal.classList.add("correlation__val");
                correlationVal.appendChild(calc_paramsSelect);
                correlationRow.appendChild(correlationVal);
                correlationWrapper.appendChild(correlationRow);
                parentWhere.insertBefore(correlationWrapper, null);
            }

            function deleteWrappers(parentWhere) {
                //общий блок берем из предыдущей функции  =  parentWhere
                //находим количество элементов
                var numberofSlices = parentWhere.childElementCount;
                //срезаем всё до первого
                for (var i = 1; i < numberofSlices; i++) {
                    //сносим всё кроме первого элемента
                    parentWhere.lastElementChild.remove()
                }
            }
        })(); // Field.tpl 3
    </script>

    {else}

    <script>
        (function () {
            var select = document.querySelector(".construct__field--select[name=\"calc_params[{$tpl_num}][{$base_params['name']}]\"]");
            var hidden = $("[name=\"calc_params[{$tpl_num}][{$base_params['name']}_type]\"]");
            setTypeToHidden(select, "{$tpl_num}", hidden);

            setTimeout(() => { // почему-то при добавлении onchage не вешается, решил таким образом
              select.onchange = function (e) {
                if (typeof set_tpl_events === "function") {
                    set_tpl_events();
                }
                setTypeToHidden(e.target, "{$tpl_num}", hidden);
              }
            }, 1);
        })(); // Field.tpl 4
    </script>
    {/if}
</div>
