A
A
Anatoly Teorsky2020-01-27 11:59:28
1C-Bitrix
Anatoly Teorsky, 2020-01-27 11:59:28

How to properly connect an event handler in your module?

Good afternoon, tell me please.

I am writing my module and now at the moment of connecting my event handler.
What I need: Register an event handler for order status changes in the system, and write a function for it in a separate file.
How I do now: I register like this:

$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->registerEventHandler('sale', 'OnSaleStatusOrder', $this->MODULE_ID, 'YoloEvents', 'My_OnSaleStatusOrder');


Next, in the include.php file at the root of the module folder, I create a class and a method:
class YoloEvents
{
  public static function My_OnSaleStatusOrder($order_id, $status_val){
    if($status_val == 'F'){
      $order = Sale\Order::load($order_id);
      $order->setField("STATUS_ID", "qq");
      $order->save();
    }
  }
}

Only I don’t know why in this file)

Please explain, otherwise I didn’t understand anything from this on the forums. I understand how to connect to handlers through init.php, I know how to connect through an unnamed function, etc., but I don’t know how to connect a function that is in a separate file.

Don't throw stones, just help please.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2020-01-27
@mamkaror

In install/index.php of the module, you need to register the dependency using this function
https://dev.1c-bitrix.ru/api_help/main/functions/m...
And put the file in lib/ so that autoloading of Bitrix classes works
Example:
In install/index.php

function InstallEvents()
{
        RegisterModuleDependences('search', 'BeforeIndex', 'mymodule.smartsearch', '\\MyModule\\SmartSearch\\EventHandler', 'BeforeIndex');
}

function UnInstallEvents()
{
        UnRegisterModuleDependences('search', 'BeforeIndex', 'mymodule.smartsearch', '\\MyModule\\SmartSearch\\EventHandler', 'BeforeIndex');
}

In libs/ eventhandler.php file with content
namespace MyModule\SmartSearch;

class EventHandler
{
    function BeforeIndex($arFields)
    {
        \CModule::IncludeModule("iblock");

        if ($arFields["MODULE_ID"] == "iblock") {
            $result = \CIBlockElement::GetByID($arFields["ITEM_ID"]);
            if ($element = $result->Fetch()) {

                $arFields['PARAM1'] = $element['IBLOCK_SECTION_ID'];
            }
        }

        return $arFields;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question