Дата последнего изменения: 06.09.2016
Создадим действие, которое будет писать в лог БП или текстовый файл, произвольные значения из шаблона бизнес-процесса. Пусть имя у действия будет write2logactivity.
Создайте структуру файлов будущего Activity. Папка с Activity должна быть расположена в /bitrix/activities/custom/
. Название папки с действием должно совпадать с именем файла, в котором находится класс с Activity, в данном случае папка должна называться /write2logactivity
.
Структура в общем виде подобна структуре компонентов:
/lang/ru
– содержит папки с языковыми сообщениями. Папки должны называться в соответствии с идентификаторами языков. Например, ru, en. В каждой папке содержатся файлы с фразами, одноименные соответствующим файлам действия:Задайте описание будущего действия в файле .description.php:
<? if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die(); $arActivityDescription = array( "NAME" => GetMessage("BPDDA_DESCR_NAME"), "DESCRIPTION" => GetMessage("BPDDA_DESCR_DESCR"), "TYPE" => "activity", // Тип - действие "CLASS" => "Write2LogActivity", //Класс с Activity "JSCLASS" => "BizProcActivity", //Стандартная JS библиотека, которая будет рисовать Activity "CATEGORY" => array( "ID" => "other", // Activity будет располагаться в категории "Прочее" ), ); ?>
В визуальном редакторе получаем иконку своего действия:
Запрограммируйте форму настроек действия в файле properties_dialog.php:
<script> <? foreach ($arCurrentValues["MapFields"] as $fieldKey => $documentFieldValue) { ?> AddCondition('<?= CUtil::JSEscape($fieldKey) ?>', '<?= CUtil::JSEscape($documentFieldValue) ?>'); <? } if (count($arCurrentValues) <= 0) { ?>AddCondition("", "");<? } ?> var check = '<?= $arCurrentValues["write2file"];?>'; if (check == "Y") { document.getElementById("write2file").checked = "checked"; Write2File(); } </script>
В результате на экране получим:
В зависимости от положения опции Писать файл, вывод мы получим либо в логе БП:
либо в файле:
Задайте код собственно действия в файле write2logactivity.php.
<? if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die(); class CBPWrite2LogActivity extends CBPActivity { public function __construct($name) { parent::__construct($name); $this->arProperties = array( "Title" => "", "MapFields" => null, "write2file" => null, "path2file"=> null ); } public function Execute() { if (is_array($this->arProperties["MapFields"]) && count($this->arProperties["MapFields"])) { $printVal = $this->__get("MapFields"); $bFirst = true; foreach($printVal as $key => $val) { if ($this->arProperties["write2file"] == "Y") { $f = fopen ($_SERVER["DOCUMENT_ROOT"].$this->arProperties["path2file"], "a+"); if ($bFirst) fwrite ($f, print_r ("\n\n\n===========================================================\n",true)); fwrite ($f, print_r ($key." = ".$val."\n",true)); fclose($f); $bFirst = false; } else $this->WriteToTrackingService($key." = ".$val); } } return CBPActivityExecutionStatus::Closed; } public static function GetPropertiesDialog($documentType, $activityName, $arWorkflowTemplate, $arWorkflowParameters, $arWorkflowVariables, $arCurrentValues = null, $formName = "") { $runtime = CBPRuntime::GetRuntime(); if (!is_array($arCurrentValues)) { $arCurrentValues = array(); $arCurrentActivity = &CBPWorkflowTemplateLoader::FindActivityByName($arWorkflowTemplate, $activityName); if (is_array($arCurrentActivity["Properties"]) && array_key_exists("MapFields", $arCurrentActivity["Properties"]) && is_array($arCurrentActivity["Properties"]["MapFields"])) { foreach ($arCurrentActivity["Properties"]["MapFields"] as $k => $v) { $arCurrentValues["MapFields"][$k] = $v; } $arCurrentValues["write2file"] = $arCurrentActivity["Properties"]["write2file"]; $arCurrentValues["path2file"] = $arCurrentActivity["Properties"]["path2file"]; } } $runtime = CBPRuntime::GetRuntime(); return $runtime->ExecuteResourceFile( __FILE__, "properties_dialog.php", array( "arCurrentValues" => $arCurrentValues, "formName" => $formName, ) ); } public static function GetPropertiesDialogValues($documentType, $activityName, &$arWorkflowTemplate, &$arWorkflowParameters, &$arWorkflowVariables, $arCurrentValues, &$arErrors) { $runtime = CBPRuntime::GetRuntime(); $arProperties = array("MapFields" => array()); if (is_array($arCurrentValues) && count($arCurrentValues)>0) { if (is_array($arCurrentValues["fields"]) && count($arCurrentValues["fields"]) > 0 && is_array($arCurrentValues["values"]) && count($arCurrentValues["values"]) > 0) { foreach($arCurrentValues["fields"] as $key => $value) if (strlen($value) > 0 && strlen($arCurrentValues["values"][$key]) > 0) $arProperties["MapFields"][$value] = $arCurrentValues["values"][$key]; } $arProperties ["write2file"] = $arCurrentValues["write2file"] == "Y" ? "Y" : "N"; $arProperties ["path2file"] = $arCurrentValues["path2file"]; } $arCurrentActivity = &CBPWorkflowTemplateLoader::FindActivityByName($arWorkflowTemplate, $activityName); $arCurrentActivity["Properties"] = $arProperties; return true; } public static function ValidateProperties($arTestProperties = array(), CBPWorkflowTemplateUser $user = null) { $arErrors = array(); $path = ""; if ($arTestProperties["path2file"]) { $path = $_SERVER["DOCUMENT_ROOT"].$arTestProperties["path2file"]; if (!file_exists($path) && !is_writable(GetDirPath($path))) $arErrors[] = array("code" => "DirNotWritable", "parameter" => "path2file", "message" => GetMessage("DIR_NOT_WRITABLE")); if (file_exists($path) && !!is_writable(GetDirPath($path))) $arErrors[] = array("code" => "FileNotWritable", "parameter" => "path2file", "message" => GetMessage("FILE_NOT_WRITABLE")); } return array_merge($arErrors, parent::ValidateProperties($arTestProperties, $user)); } } ? >
Разъясним несколько моментов, на которые надо обратить внимание разработчикам.
class CBPWrite2LogActivity extends CBPActivity { public function __construct($name) { parent::__construct($name); $this->arProperties = array( "Title" => "", "MapFields" => null, "write2file" => null, "path2file"=> null ); }
public static function GetPropertiesDialog($documentType, $activityName, $arWorkflowTemplate, $arWorkflowParameters, $arWorkflowVariables, $arCurrentValues = null, $formName = "") { $runtime = CBPRuntime::GetRuntime(); if (!is_array($arCurrentValues)) { $arCurrentValues = array(); $arCurrentActivity = &CBPWorkflowTemplateLoader::FindActivityByName($arWorkflowTemplate, $activityName); ............................... } $runtime = CBPRuntime::GetRuntime(); return $runtime->ExecuteResourceFile( __FILE__, "properties_dialog.php", array( "arCurrentValues" => $arCurrentValues, "formName" => $formName, ) ); }
public static function GetPropertiesDialogValues($documentType, $activityName, &$arWorkflowTemplate, &$arWorkflowParameters, &$arWorkflowVariables, $arCurrentValues, &$arErrors) { $runtime = CBPRuntime::GetRuntime(); $arProperties = array("MapFields" => array()); //Получили массив значений $arCurrentValues if (is_array($arCurrentValues) && count($arCurrentValues)>0) { ........................ $arProperties ["write2file"] = $arCurrentValues["write2file"] == "Y" ? "Y" : "N"; $arProperties ["path2file"] = $arCurrentValues["path2file"]; } //Получаем переменные текущего действия по ссылке и заменяем их $arCurrentActivity = &CBPWorkflowTemplateLoader::FindActivityByName($arWorkflowTemplate, $activityName); $arCurrentActivity["Properties"] = $arProperties; return true; }
public static function ValidateProperties($arTestProperties = array(), CBPWorkflowTemplateUser $user = null) { $arErrors = array(); $path = ""; if ($arTestProperties["path2file"]) { $path = $_SERVER["DOCUMENT_ROOT"].$arTestProperties["path2file"]; if (!file_exists($path) && !is_writable(GetDirPath($path))) $arErrors[] = array("code" => "DirNotWritable", "parameter" => "path2file", "message" => GetMessage("DIR_NOT_WRITABLE")); if (file_exists($path) && !!is_writable(GetDirPath($path))) $arErrors[] = array("code" => "FileNotWritable", "parameter" => "path2file", "message" => GetMessage("FILE_NOT_WRITABLE")); } return array_merge($arErrors, parent::ValidateProperties($arTestProperties, $user)); }