Документация для разработчиков
Темная тема

Добавление контакта с реквизитами

Пример размещения на странице сайта формы, после заполнения которой в Битрикс24 создаётся новый контакт с прикреплением реквизитов.

Внимание! Для использования примера настройте работу класса CRest и подключите файл crest.php в файлах, где используется данный класс. Подробнее.

  1. Создайте форму на нужной странице:
    <?	
    $arAddressFields = CRest::call('crm.address.fields',[]);
    /*
    crm.address.fields return:  https://dev.1c-bitrix.ru/rest_help/crm/requisite/requisite_fields.php#address
    */
    $arRequisiteType = CRest::call('crm.requisite.preset.list',
    	[
    		'select'=>[
    			"ID", "NAME"
    		]
    	]);
    if(!empty($arRequisiteType['result'])):
    	$arRequisiteType = array_column($arRequisiteType['result'],'NAME','ID');
    	//unset system address fields
    	unset($arAddressFields['result']['TYPE_ID']);
    	unset($arAddressFields['result']['ENTITY_TYPE_ID']);
    	unset($arAddressFields['result']['ENTITY_ID']);
    	//unset uninteresting address fields
    	unset($arAddressFields['result']['COUNTRY_CODE']);
    	unset($arAddressFields['result']['ANCHOR_TYPE_ID']);
    	unset($arAddressFields['result']['ANCHOR_ID']);
    	?>
    	<form id="form_to_crm">
    		<select name="REQ_TYPE" required>
    			<option value="" disabled selected>Select</option>
    			<?foreach($arRequisiteType as $id=>$name):?>
    				<option value="<?=$id?>"><?=$name?></option>
    			<?endforeach;?>
    		</select>
    		<input type="text" name="NAME" placeholder="Name" required>
    		<input type="text" name="LAST_NAME" placeholder="Last name">
    		<input type="text" name="PHONE" placeholder="Phone">
    		<?if(is_array($arAddressFields['result'])):?>
    			<?foreach($arAddressFields['result'] as $key=>$arField):?>
    				<input type="text" name="ADDRESS[<?=$key?>]" placeholder="<?=$arField['title']?>" <?=($arField['isRequired'])?'required':'';?>>
    			<?endforeach;?>
    		<?endif;?>
    		<input type="submit" value="Submit">
    	</form>
    <?else:?>
    		<?='No requisite types.';?>
    <?endif;?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    	$(document).ready(function() {
    		$('#form_to_crm').on( 'submit', function(el) {//event submit form
    			el.preventDefault();//the default action of the event will not be triggered
    			var formData = $(this).serialize();
    			$.ajax({
    				'method': 'POST',
    				'dataType': 'json',
    				'url': 'form.php',
    				'data':  formData,
    				success: function(data){//success callback
    					alert(data.message);
    				}
    			});
    		});
    	});
    </script>
    
  2. Создайте файл form.php, для сохранения заполненных форм:
    <?
    $iRequisitePresetID = intVal($_POST[ "REQ_TYPE" ]);
    $sName = htmlspecialchars($_POST[ "NAME" ]);
    $sLastName = htmlspecialchars($_POST[ "LAST_NAME" ]);
    $sPhone = htmlspecialchars($_POST[ "PHONE" ]);
    $arAddress = [];
    foreach($_POST[ "ADDRESS" ] as $key => $val){
    	$arAddress[ $key ] = htmlspecialchars($val);
    }
    $arAddress[ 'TYPE_ID' ] = 1;//1 is actual address in CRest::call('crm.enum.addresstype');
    $arAddress[ 'ENTITY_TYPE_ID' ] = 8;//8 - is requisite in CRest::call('crm.enum.ownertype');
    
    $arPhone = (!empty($sPhone)) ? array(array('VALUE' => $sPhone, 'VALUE_TYPE' => 'WORK')) : array();
    
    $result = CRest::call(
    	'crm.contact.add',
    	[
    		'fields' => [
    			'NAME' => $sName,
    			'LAST_NAME' => $sLastName,
    			'PHONE' => $arPhone,
    		]
    	]
    );
    if(!empty($result[ 'result' ])){
    	$resultRequisite = CRest::call(
    		'crm.requisite.add',
    		[
    			'fields' => [
    				'ENTITY_TYPE_ID' => 3,//3 - is contact in CRest::call('crm.enum.ownertype');
    				'ENTITY_ID' => $result[ 'result' ],//contact id
    				'PRESET_ID' => $iRequisitePresetID,
    				'TITLE' => implode(' ', [ $sName, $sLastName ]),
    				'ACTIVE' => 'Y',
    				'NAME' => $sName
    			]
    		]
    	);
    
    	if(!empty($resultRequisite[ 'result' ])){
    		$arAddress[ 'ENTITY_ID' ] = $resultRequisite[ 'result' ];//id requisite
    		$resultAddress = CRest::call(
    			'crm.address.add',
    			[
    				'fields' => $arAddress
    			]
    		);
    	}
    	echo json_encode([ 'message' => 'Contact add' ]);
    }elseif(!empty($result[ 'error_description' ])){
    	echo json_encode([ 'message' => 'Contact not added: '.$result[ 'error_description' ] ]);
    }else{
    	echo json_encode([ 'message' => 'Contact not added' ]);
    }
    ?>


© «Битрикс», 2001-2024, «1С-Битрикс», 2024