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

Добавление дела в лид или сделку с учетом режимов CRM (простой или классический режим)

Если CRM работает в простом режиме происходит добавление дела в сделку, в классическом режиме в лид.

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

  1. Создаём форму на нужной странице:
    <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>
    	
    <form id="form_to_crm">
    	<input type="text" name="NAME" placeholder="Name" required>
    	<input type="text" name="LAST_NAME" placeholder="Last name">
    	<input type="text" name="PHONE" placeholder="Phone">
    	<input type="text" name="EMAIL" placeholder="E-mail">
    	<input type="submit" value="Submit">
    </form>
    
  2. Создаём файл form.php, для сохранения заполненных форм:
    <?
    $sName          = htmlspecialchars($_POST["NAME"]);
    $sLastName    = htmlspecialchars($_POST["LAST_NAME"]);
    $sPhone         = htmlspecialchars($_POST["PHONE"]);
    $sEmail         = htmlspecialchars($_POST["EMAIL"]);
    	
    $arData = [
    	'add_lead' => [
    		'method' => 'crm.lead.add',
    		'params' => [
    			'fields'    =>  [
    				'TITLE' => 'From the site: ' . implode(' ', [$sName, $sLastName]),
    				'NAME' => (!empty($sName)) ? $sName : 'Empty name',//if simple mode crm NAME or LAST_NAME required for converting to contact
    				'LAST_NAME' => $sLastName,
    				'PHONE' => (!empty($sPhone)) ? array(array('VALUE' => $sPhone, 'VALUE_TYPE' => 'HOME')) : array(),
    				'EMAIL' => (!empty($sEmail)) ? array(array('VALUE' => $sEmail, 'VALUE_TYPE' => 'HOME')) : array()
    			]
    		]
    	],
    	'get_lead' => [
    		'method' => 'crm.lead.get',
    		'params' => [
    			'id' => '$result[add_lead]'
    		]
    	],
    ];
    $result = CRest::callBatch($arData);
    	
    if(empty($result['result']['result_error']['add_lead']) && !empty($result['result']['result']['get_lead'])){
    	//if status_id == converted on add then is simple mode crm
    	if($result['result']['result']['get_lead']['STATUS_ID'] == 'CONVERTED'){
    		$resultDeal = CRest::call('crm.deal.list',
    			[
    				'filter'=>[
    					'LEAD_ID' => $result['result']['result']['add_lead']
    				]
    			]);
    		if(!empty($resultDeal['result']['0']['ID'])){
    			$resultActivity = CRest::call('crm.activity.add',//call within an hour
    				[
    					'fields' =>[
    						"OWNER_TYPE_ID"     => 2,//2 - is deal in CRest::call('crm.enum.ownertype');
    						"TYPE_ID"           => 2,//2 - is call in CRest::call('crm.enum.activitytype');
    						"OWNER_ID"          => $resultDeal['result']['0']['ID'],//entity id
    						"COMMUNICATIONS"    => [['VALUE' => $sPhone,'TYPE' => 'PHONE']],
    						"START_TIME" =>  date("Y-m-d H:i:s",time()),
    						"END_TIME" => date("Y-m-d H:i:s",time()+3600),
    						"SUBJECT" => "Сall back",
    						"DESCRIPTION" => "Call within an hour",
    					]
    				]);
    		}
    			
    	}else{
    		$resultActivity = CRest::call('crm.activity.add',//call within an hour
    			[
    				'fields' =>[
    					"OWNER_TYPE_ID"     => 1,//1 - is lead in CRest::call('crm.enum.ownertype');
    					"TYPE_ID"           => 2,//2 - is call in CRest::call('crm.enum.activitytype');
    					"OWNER_ID"          => $result['result']['result']['add_lead'],//entity id
    					"COMMUNICATIONS"    => [['VALUE' => $sPhone,'TYPE' => 'PHONE']],
    					"START_TIME" =>  date("Y-m-d H:i:s",time()),
    					"END_TIME" => date("Y-m-d H:i:s",time()+3600),
    					"SUBJECT" => "Сall back",
    					"DESCRIPTION" => "Call within an hour",
    				]
    			]);
    	}
    		
    }else{
    	if(!empty($result['result']['result_error']['add_lead']))
    		$arResult[] =  'error add lead: '.$result['result']['result_error']['add_lead']['error_description'];
    	if(!empty($result['result']['result_error']['get_lead']))
    		$arResult[] =  'error get new lead: '.$result['result']['result_error']['get_lead']['error_description'];
    }	
    ?>
    


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