Добавление пользовательского свойства инфоблока - amel-post/bitrix.help GitHub Wiki

//init.php
$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->addEventHandler("iblock", "OnIBlockPropertyBuildList", [\ChiliHelp\StringCounterIblockProperty::class, "GetUserTypeDescription"]);

//StringCounterIblockProperty.php
namespace ChiliHelp;

class StringCounterIblockProperty
{
    public function GetUserTypeDescription()
    {
        return array(
            "PROPERTY_TYPE"        => "S", #-----один из стандартных типов
            "USER_TYPE"            => "STRING_COUNTER", #-----идентификатор типа свойства
            "DESCRIPTION"          => "Строка со счетчиком",
            "GetPropertyFieldHtml" => array(__CLASS__, "GetPropertyFieldHtml"),
            "GetSettingsHTML" => array(__CLASS__, "GetSettingsHTML"),
            "PrepareSettings" => array(__CLASS__, "PrepareSettings"),
        );
    }

    /*--------- вывод поля свойства на странице редактирования ---------*/
    public function GetPropertyFieldHtml($arProperty, $value, $strHTMLControlName)
    {
        $valueLength = strlen($value['VALUE']);

        $field = <<<HTML
<input type="text" name="{$strHTMLControlName["VALUE"]}" value="{$value['VALUE']}" 
       size="{$arProperty['COL_COUNT']}" id="sc_input_{$arProperty['ID']}">&nbsp;&nbsp;
<span id="sc_counter_wrapper_{$arProperty['ID']}">
    <span id="sc_string_length_{$arProperty['ID']}">{$valueLength}</span> /
    <span id="sc_max_length_{$arProperty['ID']}">{$arProperty['USER_TYPE_SETTINGS']['WIDTH']}</span>
</span>
<script>
    {
        let maxLength = {$arProperty['USER_TYPE_SETTINGS']['WIDTH']};
        let counterWrapper = document.getElementById('sc_counter_wrapper_{$arProperty['ID']}');
        let sc_input = document.getElementById('sc_input_{$arProperty['ID']}');
        sc_input.oninput = function() {
          document.getElementById('sc_string_length_{$arProperty['ID']}').innerHTML = sc_input.value.length;
          if (sc_input.value.length > maxLength) {
              counterWrapper.style.color = 'red';
          } else {
              counterWrapper.style.color = 'inherit';
          }
        }
        sc_input.oninput();
    }
</script>
HTML;
        return $field;
    }

    function GetSettingsHTML($arProperty, $strHTMLControlName, &$arPropertyFields)
    {
        $arPropertyFields = array(
            "USER_TYPE_SETTINGS_TITLE" => "Дополнительные настройки"
        );

        return '<tr>
        <td>Длина поля ввода:</td>
        <td><input type="text" size="5" name="'.$strHTMLControlName["NAME"].'[WIDTH]" value="'.$arProperty['USER_TYPE_SETTINGS']['WIDTH'].'"></td>
        </tr>';
    }

    function PrepareSettings($arFields)
    {
        $width = intval($arFields["USER_TYPE_SETTINGS"]["WIDTH"]);
        return array("WIDTH" => $width);
    }
}
⚠️ **GitHub.com Fallback** ⚠️