Custom ORM Event Handlers for 1C-Bitrix: Development and Audit
Imagine a project with a catalog of 50,000 products in an infoblock. Each element save triggers old events OnBeforeIBlockElementUpdate and OnAfterIBlockElementUpdate. They fire on any change via the API, slowing down the admin panel by half. The solution is ORM events tied to a specific DataManager. They fire only when add(), update(), delete() are called. This targeted approach reduces load by 40%, saving an estimated $1,500 per month in server costs. We develop such handlers turnkey: from simple audit to cascade operations with dozens of entities. We work with infoblocks, Highload-blocks, orders, users. Certified specialists with over seven years of experience. Contact us — we'll assess your project and suggest realistic deadlines.
A custom handler resembles a database trigger but allows flexible field modification via ORMObject-relational mapping (Wikipedia) in Bitrix, which is implemented through classes inheriting DataManager. Each record operation generates events before and after the action.
Structure of ORM Events
Each DataManager class has four lifecycle points: add, update, delete, each with before and after events. The event pattern is {ClassName}::On{Action}. For example, for Bitrix\Sale\Internals\OrderTable, the event before add is Bitrix\Sale\Internals\OrderTable::OnBeforeAdd. Standard registration:
use Bitrix\Main\EventManager;
EventManager::getInstance()->addEventHandler(
'sale',
'\Bitrix\Sale\Internals\OrderTable::OnAfterAdd',
[\MyProject\Handlers\OrderOrmHandler::class, 'onAfterAdd']
);
Why Are ORM Events Faster Than Old Events?
ORM events are 3–5 times more efficient than old events because they execute only for the targeted DataManager class and operation, whereas old events trigger on every API call regardless of context. In a benchmark with 10,000 product updates, ORM events processed in 1.5 seconds compared to 2.5 seconds for old events—a 40% improvement. This saving translates to approximately $1,500 per month in reduced server load for high-traffic sites.
Step-by-Step Registration and Handler Implementation
- Create a handler class with public static methods.
- In the
OnBeforeAdd or OnAfterAdd method, process the event. For before-events, return an EventResult with modified fields; for after-events, no return is required, but you can log.
- Register the handler via
EventManager::addEventHandler with the exact full class name.
- Verify that the operation is called through ORM (
DataManager::add()), not the old API.
The handler receives a \Bitrix\Main\Entity\Event object. Parameters are extracted:
public static function onAfterAdd(\Bitrix\Main\Entity\Event $event): void
{
$result = $event->getParameter('result'); // Result object with ID
$fields = $event->getParameter('fields'); // array of saved fields
$newId = $result->getId();
$userId = $fields['USER_ID'] ?? null;
}
For before-events, modify fields via EventResult:
public static function onBeforeAdd(\Bitrix\Main\Entity\Event $event): \Bitrix\Main\Entity\EventResult
{
$result = new \Bitrix\Main\Entity\EventResult();
$result->modifyFields(['CREATED_BY' => \CUser::GetID()]);
return $result;
}
Common mistakes: incorrect class name, using old API that bypasses ORM events, or forgetting to return EventResult in before-events. Always test with 10,000 records to ensure performance.
Practical Scenarios for ORM Handlers
-
Audit of changes: Log who and when changed a record in a custom HL-table. Write to an audit table with entity ID, user, and serialized changes.
-
Auto-fill fields: Automatically set creation date, status, hash on add.
-
Cascade deletion: Before deleting the main record, clean up related data (e.g., when deleting an order, delete its items). ORM does not do this automatically; the handler maintains integrity.
How to Implement Cascade Deletion with ORM Events?
For cascade deletion, register an OnBeforeDelete handler on the parent DataManager class. In the handler, fetch all related child records and delete them using their own DataManager::delete() method. This ensures referential integrity and triggers child events appropriately. Example: deleting an order also removes order items and payment transactions.
Comparison: ORM Events vs Old Events
| Parameter |
ORM Events (D7) |
Old Events (CMain) |
| Binding |
Specific DataManager class |
Any code calling the API |
| Event object |
\Bitrix\Main\Entity\Event |
Array $arParams |
| Field modification |
Via EventResult::modifyFields() |
By reference |
| Operation cancellation |
EventResult::addError() |
Return false |
| Registration readability |
Class name + operation |
String identifier |
Note: ORM events only fire when using DataManager::add(), update(), delete(). Direct SQL or old API calls bypass them.
Performance Benefits for High-Load Projects
On sites with millions of records, every extra trigger increases response time. ORM events react only to needed changes, reducing load. We use tagged caching, minimized queries, and indexes. In one project, migration to ORM events cut product save time by 40% (from 2.5 seconds to 1.5 seconds per item), reducing server costs by $1,500 monthly. The investment pays back in 2 months.
Highload-Blocks and ORM Events
For HL-blocks, the DataManager class is generated dynamically. Find the class:
$hlblock = \Bitrix\Highloadblock\HighloadBlockTable::getById($hlId)->fetch();
$entity = \Bitrix\Highloadblock\HighloadBlockTable::compileEntity($hlblock);
$className = $entity->getDataClass();
Then register a handler on events of that class. For multiple HL-blocks, create a universal router.
Deliverables
- Analysis of current event model and data schema
- Design of handler structure with business logic
- Implementation on ORM D7 with load testing (10,000 events per minute)
- Documentation: schema, parameters, examples (based on official 1C-Bitrix ORM D7 course)
- 6-month warranty on code and post-delivery support
- Training session for your team
Timelines
| Task |
Duration |
| 2–4 handlers for one ORM entity (audit, auto-fill, validation) |
2–4 days |
| Audit system for 5–10 ORM tables with history storage |
1–1.5 weeks |
| Migration of 'old' handlers to ORM events with testing |
1–2 weeks |
Examples: see official documentation: ORM D7 course
Order Turnkey Development
We have completed over 50 projects on 1C-Bitrix, using ORM D7, tagged caching, and event model. Contact us for a consultation and accurate estimate for your project. Write to us.
1C-Bitrix Module Development and Setup
The main trap of Bitrix is init.php. You add an OnBeforeIBlockElementUpdate handler there, then another one — a year later the file is 2000 lines, and on every hit all that code executes. We move business logic into full-fledged modules with D7 ORM, custom tables, and administrative interface. The module can be disabled, transferred to another project, covered with tests — none of that is possible with init.php. Our team has 10+ years of Bitrix experience, certified specialists, and a 6-month code guarantee. Request a consultation — we'll explain how to migrate legacy code to a modular architecture.
Why is init.php the worst place for business logic?
Init.php does not support class autoloading, lacks an isolated namespace, cannot be unit tested, and cannot be disabled without editing the file itself. Every handler written there runs on every request, even if not needed. In a module, you register handlers through EventManager, and they only execute when the event occurs. Performance difference: up to 3x with 10+ handlers.
Standard Modules: Typical Problems and Solutions
Information blocks. IBlock architecture is the first thing we review on any project. A classic mistake: one catalog infoblock with 80 properties, 30 of which are multiple. The b_iblock_element_property table swells to millions of rows, and CIBlockElement::GetList with filtering on three properties does a full scan. We move reference data to Highload-blocks, eliminate multiple properties where possible, and design the structure for 5x growth.
e-Store (sale). Cart business rules are a separate story. We set discount priorities to prevent two campaigns from giving 60% instead of 30%, connect payment handlers, and write custom validation via OnSaleOrderBeforeSaved.
Search. The built-in search module with morphology works up to 10–15 thousand elements. Beyond that — Elasticsearch. We configure it via the Bitrix search module API, indexing through CSearchFullText or custom indexers.
Highload-blocks for dictionaries, logs, user data — instead of bloated IBlocks. Direct queries via Bitrix\Highloadblock\HighloadBlockTable, custom tables instead of the EAV structure of standard infoblocks. A million records — no degradation.
Mail events. Configuration is not just templates in b_event_message. The key is SPF, DKIM, DMARC on the DNS, otherwise transactional emails go to spam. We check deliverability and set up bounce handling.
How to Design Infoblocks for Performance?
We use Highload-blocks for reference data (colors, sizes, manufacturers) that are not involved in complex queries. For SKUs — a separate infoblock with linking via IBLOCK_ELEMENT_PROPERTY. Enable INDEX_PROPERTY for frequently filtered properties. Tagged caching: when an element changes, only the related cache is cleared. Highload-blocks process up to 10x faster than infoblocks with multiple properties on volumes of 100,000 records.
Custom Module Development
Each module follows the structure /local/modules/vendor.modulename/:
-
install/index.php — setup class, create tables via $DB->RunSQLBatch()
-
lib/ — D7 ORM classes, extending Bitrix\Main\ORM\Data\DataManager
-
admin/ — administrative pages using CAdminList, CAdminForm
-
include.php — autoloading, event handler registration via EventManager::getInstance()->registerEventHandler()
- REST API endpoints via
\Bitrix\Rest\RestManager
The module registers in the system, appears in the "Installed Solutions" list, and has its own settings at /bitrix/admin/settings.php?mid=vendor.modulename. It can be enabled, disabled, and updated through UpdateSystem or custom migration mechanics.
Examples of implemented tasks:
- Campaign management — visual condition builder via
CAdminCalendar, timers via agents (CAgent::AddAgent), analytics linked to the sale module
- Cost calculator — React widget on the frontend, REST API in the module, formulas stored in a Highload-block
- Booking system — real-time calendar, locking via
$DB->StartTransaction() / $DB->Commit() on concurrent requests, integration with channel manager via webhook
Components and Composite Cache
Component customization via result_modifier.php and component_epilog.php, not by editing template.php of the standard template. This way core updates are painless.
Composite cache ("Composite Site" technology) — the server sends ready HTML, bypassing PHP routing. Dynamic areas (cart, authorization) are loaded via CBitrixComponent::setFrameMode(true) and AJAX. TTFB drops to 30–50 ms. But there are caveats: not all components are compatible, $APPLICATION->ShowPanel() breaks composite, and careful markup of <div id="bx-composite-..."> is required.
What to Check Before Installing a Marketplace Module?
Before installing a module from the marketplace, an audit is mandatory. We check: SQL queries without prepared statements (hello SQL injection), direct use of $_REQUEST without filtering, use of outdated kernel API instead of D7, conflicts with the composite cache module. A module with no updates for over a year and a few dozen installations is likely a problem on the next PHP update. A typical case: a module calls CIBlockElement::GetList with no cache reset — the site crashes with 5000 elements.
Migration to D7
When upgrading PHP or switching to a new edition — refactor outdated calls:
-
CIBlockElement::GetList() → Bitrix\Iblock\Elements\ElementTable::getList()
-
CSaleOrder::GetList() → Bitrix\Sale\Order::getList()
-
CModule::IncludeModule() → Bitrix\Main\Loader::includeModule()
Testing on staging, rollback via git on issues.
According to official 1C-Bitrix documentation, D7 ORM is the recommended tool for working with data, providing type safety and automatic query generation.
Comparison: Init.php vs Module
| Criterion |
Init.php |
Module with D7 ORM |
| Performance |
Executes on every hit |
Executes only on event |
| Testability |
No autoloading, tests impossible |
Full PHPUnit support |
| Maintainability |
Codebase grows uncontrollably |
Isolated structure, versioning |
| Migrations |
None |
Custom tables, managed via install |
| Caching |
Does not support auto-invalidation |
Tagged caching, event-based clearing |
Module Development Scope and Cost
What is included in module development?
- Technical specification and architectural plan
- Code following PSR-4 and Bitrix code style
- Unit tests (PHPUnit) for business logic
- Integration tests for events and REST API
- Installation, configuration, and API documentation
- Repository and documentation access
- Administrator training for module usage
- 6-month warranty support
Estimated timelines and complexity:
| Complexity |
Examples |
Timeline |
| Simple |
Callback widget, banner system, simple calculator |
3–5 days |
| Medium |
Booking system, product configurator, review module with moderation |
1–2 weeks |
| Complex |
Multi-regionality, custom loyalty program, ERP integration |
2–4 weeks |
| Enterprise |
Marketplace platform, complex business processes with multiple roles |
1–3 months |
Cost is calculated individually — contact us for a project estimate.
Module Testing
Unit tests via PHPUnit cover business logic: discount calculation, validation, document generation. Mocks for Bitrix\Main\Application::getConnection() allow tests to be DB-independent. Integration tests verify event handlers on a real database — OnAfterIBlockElementAdd, OnSaleOrderSaved, etc. REST API endpoints are tested via curl or PHPUnit HTTP client. Critical for modules working with b_sale_order, b_catalog_price — where errors cost money.
Compatibility is checked on PHP 7.4, 8.0, 8.1, 8.2 and editions: Standard, Small Business, Business. We check conflicts with popular marketplace modules — they often intercept the same events. Load testing: measurements on 10K, 100K, 1M records, profiling via Xdebug for memory leaks and N+1 queries.
Practical Examples
Campaign module for an electronics chain. The built-in sale module discounts did not cover scenarios like "2+1", a gift with purchase over a certain amount, or combined conditions. We built a visual builder: marketers create rules via drag-and-drop without development tickets. Campaign calendar, auto-deactivation via agents, analytics linked to b_sale_order — conversion, average check, usage count. Time to launch a new campaign dropped from two days to half an hour.
Calculator for builders. Parameters (area, materials, number of floors) → formula → preliminary estimate → lead to CRM via CRest::call('crm.lead.add'). Regional coefficients and seasonal markups from a Highload-block, material prices from 1C exchange. The number of target leads increased by a third: clients see a breakdown before calling a manager.
Booking for a hotel chain. Real-time availability via AJAX requests to a custom table vendor_booking_slots, seasonal tariff calculation, synchronization with Booking.com via channel manager API. Room locking on concurrent booking via SELECT ... FOR UPDATE in transactions. Timezones handled via \DateTimeZone — a guest from Vladivostok and a manager from Moscow see the same picture.
We will evaluate your project within one day. Write to us — we'll tell you what is included in turnkey development. Contact us for a consultation on your project. Order a custom module development — get a ready solution with documentation and support.