Created
February 17, 2026 07:34
-
-
Save EscApp2/106e20a4826a1a22840adaf1af341c7d to your computer and use it in GitHub Desktop.
generate Unique Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <? | |
| 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