Skip to content

Instantly share code, notes, and snippets.

@EscApp2
Created February 17, 2026 07:34
Show Gist options
  • Select an option

  • Save EscApp2/106e20a4826a1a22840adaf1af341c7d to your computer and use it in GitHub Desktop.

Select an option

Save EscApp2/106e20a4826a1a22840adaf1af341c7d to your computer and use it in GitHub Desktop.
generate Unique Code
<?
AddEventHandler("iblock", "OnStartIBlockElementUpdate", "generateUniqueCode",10);
AddEventHandler("iblock", "OnStartIBlockElementAdd", "generateUniqueCode",10);
function generateUniqueCode(&$arFields){
$IBLOCK_ID = $arFields['IBLOCK_ID'];
if($IBLOCK_ID == 17){
if(array_key_exists('CODE',$arFields)) {
if(empty($arFields['CODE']) && !empty($arFields['NAME'])){
$arParams = array("replace_space"=>"-","replace_other"=>"-");
$arFields['CODE'] = Cutil::translit($arFields['NAME'],"ru",$arParams);
}
}
if(!empty($arFields['CODE'])){
$doublesFilter = array(
"IBLOCK_ID"=>$IBLOCK_ID,
"%CODE"=>$arFields['CODE'],
);
$EQUAL_EXIST = false;
$arCount = array();
$pattern = preg_quote($arFields['CODE'],"/").'(_([\d]+))*';
$res_elem = CIBlockElement::GetList(
array(),
$doublesFilter,
false,
false,
array("ID","IBLOCK_ID","CODE","NAME"));
while ($arElem = $res_elem->Fetch()) {
$matches = array();
if($arElem['CODE'] == $arFields['CODE']){
$EQUAL_EXIST = $arElem['ID'];
}
preg_match('/'.$pattern.'/', $arElem['CODE'], $matches);
if($matches[2]){
$arCount[] = $matches[2];
}
}
if(count($arCount) == 0) {
$arCount[] = 0;
}
if($EQUAL_EXIST){
if(!empty($arFields['ID'])){ //update
if($arFields['ID'] != $EQUAL_EXIST){
$arFields['CODE'] .= "_".(max($arCount)+1);
}else{
//do nothing
}
}else{ //add
$arFields['CODE'] .= "_".(max($arCount)+1);
}
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment