### Render Views and Components from Controllers in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Demonstrates how to render HTML views, Bitrix components, and extensions from controller methods. Controllers automatically include site templates and support parameter passing to rendered content. Includes examples of renderView, renderComponent, and renderExtension methods. ```php class EntityController extends Controller { // Render a view file public function indexAction(): View { return $this->renderView('entity/index', [ 'title' => 'Entity List', 'items' => EntityTable::getList()->fetchAll() ]); } // Render a component public function detailAction($id): Component { return $this->renderComponent('bitrix:catalog.element', 'detail', [ 'ELEMENT_ID' => $id, 'CACHE_TYPE' => 'A', 'CACHE_TIME' => 3600 ]); } // Render an extension (requires controllerEntrypoint in extension config) public function appAction(): Extension { return $this->renderExtension('mymodule.vue.widget', [ 'userId' => $this->getCurrentUser()->getId(), 'apiEndpoint' => '/api/v1/data' ]); } } ``` -------------------------------- ### Configure Route Groups with Prefixes and Middleware in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Illustrates how to organize routes into groups with shared prefixes, parameter constraints, and naming conventions. This approach reduces code duplication and improves maintainability for API endpoints or similarly structured routes. Includes URL generation example using route names. ```php use Bitrix\Main\Routing\RoutingConfigurator; return function (RoutingConfigurator $routes) { // Group with prefix and shared constraints $routes ->prefix('api/v1') ->where('id', '\\d+') ->name('api.v1.') ->group(function (RoutingConfigurator $routes) { // Matches: /api/v1/users $routes->get('/users', [\Api\Controller\User::class, 'list']) ->name('users.list'); // Matches: /api/v1/users/123 $routes->get('/users/{id}', [\Api\Controller\User::class, 'view']) ->name('users.view'); // Matches: /api/v1/posts/456 $routes->get('/posts/{id}', [\Api\Controller\Post::class, 'view']) ->name('posts.view'); }); // Generate URLs by route name: // $router = \Bitrix\Main\Application::getInstance()->getRouter(); // $url = $router->route('api.v1.users.view', ['id' => 123]); // Result: /api/v1/users/123 }; ``` -------------------------------- ### Implement Custom Events and Handlers in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Demonstrates the Bitrix24 event system for creating custom events with typed classes and handlers. It supports different result types like success, error, and custom results, allowing for flexible integration between different modules. This example shows defining an event class, an event handler, and triggering events. ```php use Bitrix\Main\Event; use Bitrix\Main\EventResult; // Define typed event class final class OrderCreatedEvent extends Event { public function __construct( public readonly int $orderId, public readonly string $status, public readonly array $items ) { parent::__construct( 'demo.module', __CLASS__ ); } } // Define event handler final class OrderEventHandler { public static function onOrderCreated(OrderCreatedEvent $event): EventResult { // Process order event $orderId = $event->orderId; // Send email notification \Bitrix\Main\Mail\Event::send([ 'LID' => SITE_ID, 'EVENT_NAME' => 'ORDER_CREATED', 'FIELDS' => [ 'ORDER_ID' => $orderId, 'STATUS' => $event->status ] ]); // Update inventory foreach ($event->items as $item) { InventoryTable::decreaseStock($item['productId'], $item['quantity']); } // Return success return new EventResult( EventResult::SUCCESS, ['processed' => true] ); } } // Trigger event $event = new OrderCreatedEvent( orderId: 12345, status: 'created', items: [ ['productId' => 1, 'quantity' => 2], ['productId' => 5, 'quantity' => 1] ] ); $event->send(); // Alternative: anonymous event without class $event = new Event( 'demo.module', 'OnOrderStatusChange', [ 'orderId' => 12345, 'oldStatus' => 'pending', 'newStatus' => 'processing' ] ); $event->send(); ``` -------------------------------- ### Send Order Status SMS Notification with Bitrix Framework Source: https://context7.com/andrushin-anton/btx2/llms.txt This code example shows how to send an SMS notification for order status updates. It utilizes the `Bitrix\Main\Sms\Event` class with the 'ORDER_STATUS_SMS' event type, passing order-specific details such as order ID, new status, and tracking URL. The site context is also set before sending. ```php // Send order status notification $event = new SmsEvent('ORDER_STATUS_SMS', [ 'PHONE' => $customerPhone, 'ORDER_ID' => $orderId, 'STATUS' => $newStatus, 'TRACKING_URL' => $trackingUrl ]); $event->setSiteId(SITE_ID); $event->send(); ``` -------------------------------- ### Activate Routing System with .htaccess and Configuration in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Explains how to activate the Bitrix routing system by configuring .htaccess to redirect 404 errors to routing_index.php and defining route files in .settings.php. Routes are loaded from multiple locations including /bitrix/routes/ and /local/routes/ directories. ```apache # .htaccess configuration RewriteCond %{REQUEST_FILENAME} !/bitrix/routing_index.php$ RewriteRule ^(.*)$ /bitrix/routing_index.php [L] ``` ```php // .settings.php configuration return [ 'routing' => [ 'value' => [ 'config' => ['web.php', 'api.php'] ] ], // Routes will be loaded from: // /bitrix/routes/web.php, /local/routes/web.php // /bitrix/routes/api.php, /local/routes/api.php ]; ``` -------------------------------- ### Creating AJAX Controller Actions Source: https://context7.com/andrushin-anton/btx2/llms.txt Demonstrates how to create controller actions in Bitrix Framework that handle incoming requests and return data, typically in JSON format. Actions are public methods ending with `Action`. ```APIDOC ## POST /ajax/controller/item/add ### Description Creates a new item with the provided fields. ### Method POST ### Endpoint `/ajax/controller/item/add` ### Parameters #### Request Body - **fields** (array) - Required - An array of fields to create the item. ### Request Example ```javascript BX.ajax.runAction('vendor:example.Item.add', { data: { fields: { ID: 1, NAME: "test" } } }).then(function (response) { console.log(response); }, function (response) { console.error(response); }); ``` ### Response #### Success Response (200) - **array** - Returns the created item as an array or null if creation failed. #### Response Example ```json { "status": "success", "data": { "ID": 1, "NAME": "test" }, "errors": [] } ``` ## GET /ajax/controller/item/view ### Description Retrieves an item by its ID. ### Method GET ### Endpoint `/ajax/controller/item/view` ### Parameters #### Query Parameters - **id** (integer) - Required - The ID of the item to retrieve. ### Request Example ```javascript // Assuming 'id' is passed as a query parameter or in the request data // Example for calling a method that takes an ID as a parameter // BX.ajax.runAction('vendor:example.Item.view', { data: { id: 1 } }); ``` ### Response #### Success Response (200) - **array** - Returns the item details as an array or null if not found. #### Response Example ```json { "status": "success", "data": { "ID": 1, "NAME": "test" }, "errors": [] } ``` ``` -------------------------------- ### Define Routes with Parameters and Constraints in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Shows how to define routes that map URLs to controllers or closures with support for HTTP method filtering, dynamic parameters with regex constraints, and named routes for URL generation. Routes are configured in web.php or api.php files using RoutingConfigurator. ```php get('/countries', function () { return "List of countries"; }); // Route with parameter and constraint $routes->get('/countries/{country}', function ($country) { return "Country: {$country}"; })->where('country', '[a-zA-Z]+')->name('country.detail'); // Route with controller $routes->get('/posts/{id}', [\Demo\Controller\Post::class, 'view']) ->where('id', '\\d+') ->name('post.view'); // Route with default parameter value $routes->get('/search/{query}', function ($query = '') { return "Search results for: {$query}"; })->where('query', '.*')->default('query', ''); }; ``` -------------------------------- ### Dependency Injection in Controllers Source: https://context7.com/andrushin-anton/btx2/llms.txt Explains how Bitrix Framework controllers support automatic dependency injection for various parameter types, simplifying the process of passing objects and data to controller actions. ```APIDOC ## POST /ajax/controller/folder/rename ### Description Renames a folder. This action demonstrates dependency injection for `Folder` and `CurrentUser` objects. ### Method POST ### Endpoint `/ajax/controller/folder/rename` ### Parameters #### Query Parameters - **id** (integer) - Required - The ID of the folder to rename. - **newName** (string) - Required - The new name for the folder. #### Request Body (Implicitly handled by BX.ajax.runAction based on the JS call) ### Request Example ```javascript BX.ajax.runAction('folder.rename', { data: { id: 123, newName: 'New Folder Name' } }); ``` ### Response #### Success Response (200) - **object** - An object containing the new name of the folder. #### Response Example ```json { "status": "success", "data": { "name": "New Folder Name" }, "errors": [] } ``` #### Error Response - **null** - If the user is not authorized, an error will be added and null might be returned. #### Error Example ```json { "status": "error", "data": null, "errors": [{"message": "Unauthorized", "code": "UNAUTHORIZED"}] } ``` ``` -------------------------------- ### Implement Dependency Injection in PHP Controllers Source: https://context7.com/andrushin-anton/btx2/llms.txt Illustrates dependency injection in Bitrix controllers using `getPrimaryAutoWiredParameter`. This allows controllers to automatically resolve dependencies like custom objects, scalar types, and standard Bitrix objects such as `CurrentUser`. It simplifies parameter handling in action methods. ```php use Bitrix\Main\Engine\AutoWire\ExactParameter; use Bitrix\Main\Engine\CurrentUser; class Folder extends Controller { public function getPrimaryAutoWiredParameter() { return new ExactParameter( Folder::class, 'folder', function($className, $id) { return Folder::loadById($id); } ); } public function renameAction(Folder $folder, $newName, CurrentUser $user) { if (!$user->isAuthorized()) { $this->addError(new Error('Unauthorized')); return null; } $folder->setName($newName); $folder->save(); return ['name' => $folder->getName()]; } } // JavaScript call: // BX.ajax.runAction('folder.rename', { // data: { id: 123, newName: 'New Folder Name' } // }); ``` -------------------------------- ### PHP File and Directory Access Control Configuration Source: https://context7.com/andrushin-anton/btx2/llms.txt Configures access control for files and directories using `.access.php` files. Supports deny (D), read (R), workflow (U), write (W), and full access (X) levels with inheritance. This configuration is typically placed in the root of a directory to control access within that directory and its subdirectories. ```php ``` -------------------------------- ### User Authentication and Permissions in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Handles user authentication, authorization checks, and group management. It allows checking if a user is logged in, verifying their permissions for specific operations, registering new users, blocking accounts, and managing group memberships. ```php /** * @var CUser $USER */ // Check user permissions if ($USER->IsAuthorized()) { echo "User is logged in\n"; echo "User ID: " . $USER->GetID() . "\n"; echo "User login: " . $USER->GetLogin() . "\n"; } // Check operation permissions if ($USER->CanDoOperation('edit_file')) { echo "User can edit files\n"; } // Simple registration $USER->SimpleRegister('user@example.com', 'John Doe'); // Block user $USER->Update(234, [ 'ACTIVE' => 'N', 'BLOCKED' => 'Y' ]); // Force password change on next login $USER->Update(234, [ 'PASSWORD_EXPIRED' => 'Y' ]); // Get user groups $groups = CUser::GetUserGroup(234); // Add user to groups CUser::AppendUserGroup(234, [ 3, // Group ID [ 'GROUP_ID' => 4, 'DATE_ACTIVE_FROM' => '01.01.2025', 'DATE_ACTIVE_TO' => '31.12.2025' ] ]); // Remove user from groups CUser::RemoveUserGroup(234, [3, 4]); ``` -------------------------------- ### Send Email Notifications via Bitrix24 Event System in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Illustrates how to send various types of email notifications using the Bitrix24 mail event system. This method supports templating, automatic site context, and field substitution for dynamic content, enabling personalized communication with users for events like welcome emails, order confirmations, and password resets. It uses the Bitrix\Main\Mail\Event::send() method. ```php use Bitrix\Main\Mail\Event; // Send welcome email Event::send([ 'LID' => SITE_ID, 'EVENT_NAME' => 'WELCOME_EMAIL', 'FIELDS' => [ 'NAME' => $userName, 'EMAIL' => $userEmail, 'CONFIRM_LINK' => $confirmUrl, 'PASSWORD' => $password ] ]); // Send order notification Event::send([ 'LID' => SITE_ID, 'EVENT_NAME' => 'ORDER_CREATED', 'FIELDS' => [ 'ORDER_ID' => $orderId, 'ORDER_TOTAL' => $orderTotal, 'CUSTOMER_NAME' => $customerName, 'ORDER_LINK' => $orderUrl, 'PRODUCTS' => $productsHtml ] ]); // Send password reset Event::send([ 'LID' => SITE_ID, 'EVENT_NAME' => 'PASSWORD_RESET', 'FIELDS' => [ 'EMAIL' => $userEmail, 'RESET_LINK' => $resetUrl, 'VALID_UNTIL' => $expirationDate ] ]); ``` -------------------------------- ### Execute Raw SQL Queries in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Allows direct database interaction for SELECT, INSERT, and UPDATE statements. It supports automatic escaping of values, result iteration, limit/offset parameters, and retrieval of scalar values. Fetching can be done with type conversion or in raw format. ```php use Bitrix\Main\Application; $db = Application::getConnection(); // SELECT query with iteration $result = $db->query('SELECT `ID`, `NAME`, `EMAIL` FROM b_user WHERE ACTIVE = "Y"'); foreach ($result as $row) { echo "{$row['NAME']} ({$row['EMAIL']})\n"; } // SELECT with limit and offset $result = $db->query('SELECT `ID`, `NAME` FROM b_user', 5, 10); // SQL: SELECT `ID`, `NAME` FROM b_user LIMIT 5,10 // Get scalar value (first column of first row) $count = $db->queryScalar('SELECT COUNT(*) FROM b_user WHERE ACTIVE = "Y"'); // Execute without return $db->queryExecute('UPDATE b_user SET ACTIVE = "Y" WHERE DATE_REGISTER > "2024-01-01"'); // Fetch methods while ($row = $result->fetch()) { // fetch() - with type conversion (dates become DateTime objects) print_r($row); } while ($row = $result->fetchRaw()) { // fetchRaw() - original format (dates as strings) print_r($row); } ``` -------------------------------- ### Create AJAX Controller Actions in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Defines controller actions in PHP that can be invoked via AJAX. These actions handle data manipulation and return results as arrays or objects implementing specific interfaces. Dependencies include BitrixMainError and BitrixMainEngineController. ```php namespace Vendor\Example\Controller; use Bitrix\Main\Error; use Bitrix\Main\Engine\Controller; class Item extends Controller { public function addAction(array $fields): ?array { $item = Item::add($fields); if (!$item) { $this->addError(new Error('Could not create item.', 'CREATE_FAILED')); return null; } return $item->toArray(); } public function viewAction($id): ?array { $item = Item::getById($id); if (!$item) { $this->addError(new Error('Could not find item.', 'NOT_FOUND')); return null; } return $item->toArray(); } } ``` -------------------------------- ### Send SMS Verification Code with Bitrix Framework Source: https://context7.com/andrushin-anton/btx2/llms.txt This snippet demonstrates how to send an SMS verification code using the `Bitrix\Main\Sms\Event` class. It sets a specific event type ('VERIFY_CODE_SMS'), provides necessary parameters like phone number and verification code, sets the site ID, and sends the message. Error handling is included to display any issues during the sending process. ```php use Bitrix\Main\Sms\Event as SmsEvent; // Send SMS verification code $event = new SmsEvent('VERIFY_CODE_SMS', [ 'PHONE' => $userPhone, 'CODE' => $verificationCode, 'VALID_MINUTES' => 5 ]); $event->setSiteId(SITE_ID); $result = $event->send(); if (!$result->isSuccess()) { foreach ($result->getErrors() as $error) { echo $error->getMessage(); } } ``` -------------------------------- ### Manage Database Tables with ORM Fields in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Provides methods for comprehensive table management, including creation, renaming, dropping tables, and managing indexes. It utilizes ORM field definitions for table structure and supports checking table existence and truncating tables. ```php use Bitrix\Main\Application; use Bitrix\Main\ORM\Fields\IntegerField; use Bitrix\Main\ORM\Fields\StringField; $db = Application::getConnection(); // Create table $db->createTable('my_table', [ 'ID' => new IntegerField('ID', [ 'primary' => true, 'autocomplete' => true ]), 'NAME' => new StringField('NAME', [ 'size' => 255 ]), 'CODE' => new StringField('CODE', [ 'size' => 50 ]) ]); // Create index $db->createIndex('idx_code', 'my_table', ['CODE'], true); // Create primary key $db->createPrimaryIndex('my_table', ['ID']); // Check if table exists if ($db->isTableExists('my_table')) { echo "Table exists\n"; } // Get table fields description $fields = $db->getTableFields('my_table'); // Rename table $db->renameTable('old_table', 'new_table'); // Drop column $db->dropColumn('my_table', 'DESCRIPTION'); // Truncate table $db->truncateTable('my_table'); // Drop table $db->dropTable('my_table'); ``` -------------------------------- ### PHP Agent Implementation for Scheduled Tasks Source: https://context7.com/andrushin-anton/btx2/llms.txt Defines and registers agents (scheduled tasks) using PHP. Agents are classes executed periodically for recurring tasks. Registration involves specifying the agent method, module, interval in seconds, and optionally a period. This code requires the Bitrix framework. ```php // Define agent class final class MyAgent { public static function runAgent(): string { // Agent logic - cleanup old data $connection = \Bitrix\Main\Application::getConnection(); $connection->queryExecute( "DELETE FROM my_table WHERE DATE_CREATE < DATE_SUB(NOW(), INTERVAL 30 DAY)" ); // Return agent call string to re-register return __METHOD__ . "();"; } public static function sendDailyReport(): string { // Send daily statistics report $stats = StatisticsTable::getDailyStats(); \Bitrix\Main\Mail\Event::send([ 'LID' => SITE_ID, 'EVENT_NAME' => 'DAILY_REPORT', 'FIELDS' => [ 'STATS' => $stats, 'DATE' => date('Y-m-d') ] ]); return __METHOD__ . "();"; } } // Register agent to run daily (86400 seconds) \CAgent::AddAgent( name: '\MyAgent::runAgent();', module: 'demo.module', interval: 86400, period: 'N' // Do not check for period ); // Register agent to run every hour \CAgent::AddAgent( name: '\MyAgent::sendDailyReport();', module: 'demo.module', interval: 3600 ); ``` -------------------------------- ### Call Controller Actions from JavaScript Source: https://context7.com/andrushin-anton/btx2/llms.txt Demonstrates how to call Bitrix controller actions asynchronously using BX.ajax.runAction in JavaScript. It handles both successful responses containing data and error responses with detailed error messages. The function expects the action name and data as parameters. ```javascript BX.ajax.runAction('vendor:example.Item.add', { data: { fields: { ID: 1, NAME: "test" } } }).then(function (response) { console.log(response); // Success response: // { // "status": "success", // "data": { "ID": 1, "NAME": "test" }, // "errors": [] // } }, function (response) { console.log(response); // Error response: // { // "status": "error", // "data": null, // "errors": [{"message": "Could not create item.", "code": "CREATE_FAILED"}] // } }); ``` -------------------------------- ### Send Appointment Reminder SMS with Bitrix Framework Source: https://context7.com/andrushin-anton/btx2/llms.txt This snippet illustrates sending an SMS reminder for an appointment. It uses the `Bitrix\Main\Sms\Event` class with the 'APPOINTMENT_REMINDER' event type and includes appointment details like date, time, and location. The site ID is set, and the reminder is sent. ```php // Send appointment reminder $event = new SmsEvent('APPOINTMENT_REMINDER', [ 'PHONE' => $clientPhone, 'DATE' => $appointmentDate, 'TIME' => $appointmentTime, 'LOCATION' => $location ]); $event->setSiteId(SITE_ID); $event->send(); ``` -------------------------------- ### PHP RBAC Implementation with Custom Controllers Source: https://context7.com/andrushin-anton/btx2/llms.txt Implements Role-Based Access Control (RBAC) using custom controllers in PHP. It supports checking permissions on specific items and filtering entity queries based on user access rights. Requires Bitrix framework components. ```php use Bitrix\Main\Access\AccessibleItem; use Bitrix\Main\Access\BaseAccessController; use Bitrix\Main\Access\User\AccessibleUser; use Bitrix\Main\Engine\CurrentUser; // Define access controller final class PostAccessController extends BaseAccessController { protected function loadItem(int $itemId = null): ?AccessibleItem { return $itemId ? MyPost::loadById($itemId) : null; } protected function loadUser(int $userId): AccessibleUser { return MyUser::loadById($userId); } } // Use in controller final class MyController { public function getAction(int $id, CurrentUser $user, PostAccessController $access) { if (!$access->check($user->getId(), 'view', $id)) { throw new \Bitrix\Main\AccessDeniedException('No access to view this post'); } $post = MyPost::getById($id); return $post->toArray(); } public function listAction(CurrentUser $user, PostAccessController $access) { $query = MyPost::query(); // Apply access filter $filter = $access->getEntityFilter( 'view', $query->getEntity()->getObjectClassName() ); if ($filter) { $query->where($filter); } return $query->fetchCollection(); } } ``` -------------------------------- ### Advanced Query Building with Filtering and Sorting Source: https://context7.com/andrushin-anton/btx2/llms.txt Build complex database queries using the ORM query builder with support for multiple filtering conditions (where, whereBetween, whereIn), sorting, result limiting and offsetting, and field selection. Results can be fetched as collections of objects, arrays, or lists of IDs for efficient data retrieval and iteration. ```php use Bitrix\Main\UserTable; use Bitrix\Main\Type\DateTime; // Complex query with multiple conditions $users = UserTable::query() ->addSelect('ID') ->addSelect('NAME') ->addSelect('EMAIL') ->where('ACTIVE', true) ->whereBetween( 'DATE_REGISTER', DateTime::createFromText('first day of this month'), DateTime::createFromText('now') ) ->whereIn('ID', [1, 2, 3, 5, 8]) ->orderBy('DATE_REGISTER', 'DESC') ->setLimit(10) ->setOffset(0) ->fetchCollection(); // Work with collection foreach ($users as $user) { echo $user->getName() . " (" . $user->getEmail() . ")\n"; } $userIds = $users->getIdList(); // Fetch as array $usersArray = UserTable::query() ->addSelect('ID') ->addSelect('NAME') ->where('ACTIVE', true) ->fetchAll(); ``` -------------------------------- ### Execute Background Jobs After Response in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Adds a background job to execute heavy processing after the HTTP response has been sent to the user. This is useful for tasks like analytics tracking, sending notifications, or updating external systems without delaying the user's page load. It utilizes the Application::getInstance()->addBackgroundJob() method. ```php use Bitrix\Main\Application; // In controller or page public function processOrderAction($orderId) { $order = OrderTable::getById($orderId)->fetchObject(); // Quick response to user $response = [ 'orderId' => $orderId, 'status' => 'processing' ]; // Add background job for heavy processing Application::getInstance()->addBackgroundJob(function () use ($orderId) { // This runs after response is sent to user // Update analytics AnalyticsService::trackOrder($orderId); // Send notifications NotificationService::notifyManagers($orderId); // Generate PDF invoice InvoiceService::generatePdf($orderId); // Update external systems ExternalApiService::syncOrder($orderId); }); return $response; } ``` -------------------------------- ### CRUD Operations with Bitrix ORM Source: https://context7.com/andrushin-anton/btx2/llms.txt Perform Create, Read, Update, and Delete operations on database entities using ORM methods. Includes automatic data validation, type conversion, and error handling. Results provide success/failure status, error messages with codes, and retrieved entity data accessible through getter methods or direct property access. ```php use SomePartner\MyBooksCatalog\BookTable; use Bitrix\Main\Type\Date; // Create (Add) $result = BookTable::add([ 'ISBN' => '978-0321127426', 'TITLE' => 'Patterns of Enterprise Application Architecture', 'PUBLISH_DATE' => new Date('2024-01-15', 'Y-m-d') ]); if ($result->isSuccess()) { $bookId = $result->getId(); echo "Book created with ID: {$bookId}"; } else { foreach ($result->getErrors() as $error) { echo $error->getMessage() . " (Code: " . $error->getCode() . ")\n"; } } // Read (Query) $book = BookTable::query() ->where('ISBN', '=', '978-0321127426') ->where('PUBLISH_DATE', '>=', new Date('2024-01-01', 'Y-m-d')) ->fetchObject(); if ($book) { echo "Title: " . $book->getTitle() . "\n"; } // Update $updateResult = BookTable::update($bookId, [ 'TITLE' => 'Updated Title' ]); // Delete $deleteResult = BookTable::delete($bookId); ``` -------------------------------- ### Define Entity Tables with Bitrix DataManager Source: https://context7.com/andrushin-anton/btx2/llms.txt Create database schema using PHP classes that extend Entity\DataManager. Supports multiple field types including Integer, String, Date, DateTime, Boolean, Float, Decimal, Text, Array, Crypto, and Secret. Fields can have validation rules, custom column names, and default values. The getMap() method returns an array of field definitions that map to database columns. ```php namespace SomePartner\MyBooksCatalog; use Bitrix\Main\Entity; use Bitrix\Main\Type; class BookTable extends Entity\DataManager { public static function getTableName(): string { return 'my_book'; } public static function getUfId(): string { return 'MY_BOOK'; // For custom user fields } public static function getMap(): array { return [ new Entity\IntegerField('ID', [ 'primary' => true, 'autocomplete' => true ]), new Entity\StringField('ISBN', [ 'required' => true, 'column_name' => 'ISBNCODE', 'validation' => function() { return [ function ($value) { $clean = str_replace('-', '', $value); if (preg_match('/^\d{13}$/', $clean)) { return true; } return 'ISBN must contain 13 digits.'; } ]; } ]), new Entity\StringField('TITLE', [ 'size' => 255 ]), new Entity\DateField('PUBLISH_DATE', [ 'default_value' => function() { return new Type\Date(); } ]), new Entity\ExpressionField('AGE_DAYS', 'DATEDIFF(NOW(), %s)', ['PUBLISH_DATE'] ) ]; } } ``` -------------------------------- ### Insert Data with Automatic Escaping in PHP Source: https://context7.com/andrushin-anton/btx2/llms.txt Facilitates inserting single or multiple records into tables using add() and addMulti() methods. These methods provide automatic column validation and value escaping to prevent SQL injection. Non-existent columns are automatically ignored. ```php use Bitrix\Main\Application; $db = Application::getConnection(); // Single insert - returns inserted ID $id = $db->add('my_table', [ 'NAME' => 'example', 'CONTENT' => 'Article about "databases"', 'DATE_CREATE' => new \Bitrix\Main\Type\DateTime() ]); // SQL: INSERT INTO `my_table`(`NAME`, `CONTENT`, `DATE_CREATE`) VALUES ('example', 'Article about \"databases\"', '2024-01-15 10:30:00') // Multiple insert - returns last inserted ID $lastId = $db->addMulti('my_table', [ [ 'NAME' => 'article_one', 'CONTENT' => 'First article content' ], [ 'NAME' => 'article_two', 'CONTENT' => 'Second article content' ] ]); // Non-existent columns are automatically excluded $insertedId = $db->add('b_user', [ 'NAME' => 'John Doe', 'NOT_EXISTS_COLUMN' => 'ignored' // This will be skipped ]); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.