N
N
Nentra2021-09-27 17:41:37
Bitrix24
Nentra, 2021-09-27 17:41:37

Why doesn't the function run when the event occurs?

In "/local/php_interface/init.php"

wrote

<?
  //добавить пользователя в нужные групповые чаты
AddEventHandler("main", "OnAfterUserAdd", Array("AddUserToGroupChatsClass", "AddUserToGroupChats"), $_SERVER["DOCUMENT_ROOT"] . "/local/php_interface/event_handlers/add_user_to_group_chats_class.php");
?>


Why is my handler not running?
here it says
https://dev.1c-bitrix.ru/api_help/main/functions/m...
that in the "AddEventHandler" function the path is specified as the last argument, but the event does not occur for me.

<?
  //добавить нвого пользователя в нужные групповые чаты
  class AddUserToGroupChatsClass
  {
    // создаем обработчик события "OnAfterUserAdd"
    function AddUserToGroupChats(&$arFields)
    {		 
      use Bitrix\Main\Diag;
      Diag\Debug::writeToFile("Событие наступило", $varName = "", $fileName = "logText.php");
      
    
    }
  }
  
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Nikolaev, 2021-09-28
@Nentra

Yes, you almost did everything right, but not in the right way.
Before copying mindlessly read to the end, I tried to expand the thought in order not only to answer the question, but also to explain some of the actions.
Let's see what you got right:
- You decided to use the event mechanism
- You defined the event correctly
- You used the local folder for development
- You tried to share responsibility between the event subscription and its handler itself.
Now what didn't work for you.
For starters, this is the event subscription itself.
- You misunderstood her arguments
- You used an outdated subscription plugin.
Let's start from the reverse order: AddEventHandler is just a wrapper over \Bitrix\Main\EventManager::addEventHandlerCompatible so we will use it.
First, let's rewrite your code verbatim in the "new way":

$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->addEventHandlerCompatible(
  'main',
  'OnAfterUserAdd',
  [
    'AddUserToGroupChatsClass',
    'AddUserToGroupChats'
  ],
  $_SERVER["DOCUMENT_ROOT"] . "/local/php_interface/event_handlers/add_user_to_group_chats_class.php"
);

It looks better but still doesn't work.
The order of the addEventHandlerCompatible and AddEventHandler arguments is the same and consists of:
- FROM_MODULE_ID - which module we subscribe to
- MESSAGE_ID - which event we subscribe to
- CALLBACK - callback handler (will be called for )
- SORT - order of execution relative to other events
- FULL_PATH - path to file
T. e. it turns out that at you the order of arguments is broken. It would be more correct like this:
$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->addEventHandlerCompatible(
  'main',
  'OnAfterUserAdd',
  [
    'AddUserToGroupChatsClass',
    'AddUserToGroupChats'
  ],
  100,
  $_SERVER["DOCUMENT_ROOT"] . "/local/php_interface/event_handlers/add_user_to_group_chats_class.php"
);

Now let's deal with the subscription model itself: you want to use your own class and separate it into a separate file for convenience.
We will not raise questions about naming, but it is absolutely not necessary to include an additional file for the event. I recommend reading about spl_autoload and composer.
Let's use our ready-made init.php development and place a small autoloader in init.php.
Let's assume that your class AddUserToGroupChatsClass will be responsible for adding.
Your init.php:
/**
 * - /local/php_interface/classes/{Path|raw}/{*|raw}.php
 * - /local/php_interface/classes/{Path|ucfirst,lowercase}/{*|ucfirst,lowercase}.php
 */
spl_autoload_register(function($sClassName)
{
  $sClassFile = __DIR__.'/classes';

  if ( file_exists($sClassFile.'/'.str_replace('\\', '/', $sClassName).'.php') )
  {
    require_once($sClassFile.'/'.str_replace('\\', '/', $sClassName).'.php');
    return;
  }

  $arClass = explode('\\', strtolower($sClassName));
  foreach($arClass as $sPath )
  {
      $sClassFile .= '/'.ucfirst($sPath);
  }
  $sClassFile .= '.php';
  if (file_exists($sClassFile))
  {
    require_once($sClassFile);
  }
});

$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->addEventHandlerCompatible(

  'main',
  'OnAfterUserAdd',
  [
    'AddUserToGroupChatsClass',
    'AddUserToGroupChats'
  ]
);

Now you need to mark up your class in the file: /local/php_interface/classes/AddUserToGroupChatsClass.php
Note that we have removed sorting (you don't care about the order) and file inclusion - the autoloader is now responsible for this.
Now let's work with the contents of this file.
Let's make cosmetic changes:
- remove unnecessary indents
- add phpdoc Let 's make
functional changes:
- bring the file to the form opentag -> namespace -> use -> class
- add the description of the method necessary to call it in call_user_func_array
- Write the correct parameters to the Debug::writeToFile method
<?php

use \Bitrix\Main\Diag;

class AddUserToGroupChatsClass
{
  /**
   * Handle main::OnAfterUserAdd event
   *     after add user to groups
   * @param array &$arFields User data
   * @return void
   */
  public static function AddUserToGroupChats( &$arFields )
  {		 
    Diag\Debug::writeToFile(
      [
        'text'   => "Событие наступило",
        'fields' => $arFields
      ],
      date('d.m.Y'),
      "AddUserToGroupChatsClass.log"
    ); 
  }
}

As a result of the work done, the file `AddUserToGroupChatsClass.log` will be created (I have bitrix env and $_SERVER['DOCUMENT_ROOT'] points to /home/bitrix/www, respectively, the file is located along the path: /home/bitrix/www/AddUserToGroupChatsClass.log )
with something like this:
28.09.2021:
Array
(
    [text] => Событие наступило
    [fields] => Array
        (
            [TITLE] => 
            [NAME] => test1
            [LAST_NAME] => test1
            [SECOND_NAME] => test1
            [EMAIL] => [email protected]
            [LOGIN] => [email protected]
            [PERSONAL_PROFESSION] => 
            [PERSONAL_WWW] => 
            [PERSONAL_ICQ] => 
            [PERSONAL_GENDER] => 
            [PERSONAL_BIRTHDAY] => 
            [PERSONAL_PHONE] => 
            [PERSONAL_FAX] => 
            [PERSONAL_MOBILE] => 
            [PERSONAL_PAGER] => 
            [PERSONAL_STREET] => 
            [PERSONAL_MAILBOX] => 
            [PERSONAL_CITY] => 
            [PERSONAL_STATE] => 
            [PERSONAL_ZIP] => 
            [PERSONAL_COUNTRY] => 0
            [PERSONAL_NOTES] => 
            [WORK_COMPANY] => 
            [WORK_DEPARTMENT] => 
            [WORK_POSITION] => 
            [WORK_WWW] => 
            [WORK_PHONE] => 
            [WORK_FAX] => 
            [WORK_PAGER] => 
            [WORK_STREET] => 
            [WORK_MAILBOX] => 
            [WORK_CITY] => 
            [WORK_STATE] => 
            [WORK_ZIP] => 
            [WORK_COUNTRY] => 0
            [WORK_PROFILE] => 
            [WORK_NOTES] => 
            [AUTO_TIME_ZONE] => 
            [XML_ID] => 
            [PHONE_NUMBER] => 
            [PASSWORD_EXPIRED] => N
            [TIME_ZONE] => 
            [LID] => s1
            [LANGUAGE_ID] => 
            [ACTIVE] => Y
            [BLOCKED] => N
            [GROUP_ID] => Array
                (
                    [0] => Array
                        (
                            [GROUP_ID] => 3
                            [DATE_ACTIVE_FROM] => 
                            [DATE_ACTIVE_TO] => 
                        )

                    [1] => Array
                        (
                            [GROUP_ID] => 12
                            [DATE_ACTIVE_FROM] => 
                            [DATE_ACTIVE_TO] => 
                        )

                    [2] => Array
                        (
                            [GROUP_ID] => 4
                            [DATE_ACTIVE_FROM] => 
                            [DATE_ACTIVE_TO] => 
                        )

                )

            [ADMIN_NOTES] => 
            [PASSWORD] => $5$hjIX0a5X2ps0X6kFG1h5xXAt4elIW.typcRgt23xwX97xU.GgGt0i3HG1a2hwZtcYXwIR3Whg6sXwV.
            [CONFIRM_PASSWORD] => [email protected]
            [UF_DEPARTMENT] => Array
                (
                    [0] => 2
                )

            [UF_PHONE_INNER] => 
            [UF_USER_CRM_ENTITY] => 
            [UF_INN] => 
            [UF_DISTRICT] => 
            [UF_SKYPE] => 
            [UF_TWITTER] => 
            [UF_FACEBOOK] => 
            [UF_LINKEDIN] => 
            [UF_XING] => 
            [UF_WEB_SITES] => 
            [UF_SKILLS] => 
            [UF_INTERESTS] => 
            [UF_EMPLOYMENT_DATE] => 
            [UF_SKYPE_LINK] => 
            [UF_ZOOM] => 
            [UF_TIMEMAN] => 
            [UF_TM_MAX_START] => 00:00
            [UF_TM_MIN_FINISH] => 00:00
            [UF_TM_MIN_DURATION] => 00:00
            [UF_TM_REPORT_REQ] => 
            [UF_TM_REPORT_TPL] => Array
                (
                    [0] => 
                )

            [UF_TM_FREE] => 
            [UF_TM_TIME] => 
            [UF_TM_DAY] => 
            [UF_TM_REPORT_DATE] => 
            [UF_REPORT_PERIOD] => 
            [UF_DELAY_TIME] => 
            [UF_LAST_REPORT_DATE] => 
            [UF_SETTING_DATE] => 
            [UF_TM_ALLOWED_DELTA] => 
            [CHECKWORD] => 433ddaf3c8a14fe75431252a2709b8
            [~CHECKWORD_TIME] => now()
            [ID] => 5
            [RESULT] => 5
        )
)

In total, we have:
- Event subscription (working)
- Autoloader, which will allow you to connect classes as you use them (without having to explicitly write them down)
- Separation of logic between the subscription and the handler.
It would be nice to delve into:
- php classes (namespace, static, public, protected, private)
- composer
I hope it helped.

N
Nentra, 2021-09-28
@Nentra

This does not work for me, although it should work

$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->addEventHandlerCompatible(
  'main',
  'OnAfterUserAdd',
  [
    'AddUserToGroupChatsClass',
    'AddUserToGroupChats'
  ],
  100,
  $_SERVER["DOCUMENT_ROOT"] . "/local/php_interface/event_handlers/add_user_to_group_chats_class.php"
);

This is what works:
AddEventHandler("main", "OnAfterUserAdd", Array("AddUserToGroupChatsClass", "AddUserToGroupChats") );
require_once($_SERVER['DOCUMENT_ROOT'] . "/local/php_interface/event_handlers/add_user_to_group_chats_class.php");

but I get the file
add_user_to_group_chats_class.php
in general, it loads every time, but I would like to make it load only when the event is triggered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question