### PHP ORM Collection Query with Date Filtering Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Retrieves a collection of user IDs based on their registration date falling within a specified range (start of month to today). It uses Bitrix's ORM with date manipulation and fetches the results as a collection. ```php use Bitrix\Main\Type\DateTime; use Bitrix\Main\UserTable; $users = UserTable::query() ->addSelect('ID') ->whereBetween( 'DATE_REGISTER', DateTime::createFromText('начало месяца'), DateTime::createFromText('сегодня') ) ->fetchCollection(); $usersIds = $users->getIdList(); ``` -------------------------------- ### Execute Background Jobs in PHP with Bitrix Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Shows how to queue heavy tasks to be executed in the background without blocking the user's request. This is achieved using `Application::getInstance()->addBackgroundJob()`, which accepts a closure containing the processing logic. This improves user experience by providing a responsive interface. ```php \Bitrix\Main\Application::getInstance()->addBackgroundJob(function () { // Heavy processing logic }); ``` -------------------------------- ### Render Bitrix Components from Controller Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Displays Bitrix components directly from controller actions by returning Component object with component name, template, and parameters. ```php class EntityController extends Controller { public function indexAction(): Component { return $this->renderComponent('bitrix:component.name', 'template-name', [ 'param' => 'value', ]); } } ``` -------------------------------- ### Register and Implement Event Handlers in PHP Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Shows how to create an event handler class and register it with the Bitrix event manager. This allows specific actions to be triggered in response to system events. It depends on the BitrixMainEventManager and BitrixMainEventResult classes. ```php final class MyEventHandler { public static function handle(MyEvent $event): \Bitrix\Main\EventResult { // Process event if ($hasErrors) { return new \Bitrix\Main\EventResult( \Bitrix\Main\EventResult::ERROR, $errors, ); } return new \Bitrix\Main\EventResult( \Bitrix\Main\EventResult::SUCCESS, ); } } // Register handler $eventManager = \Bitrix\Main\EventManager::getInstance(); $eventManager->addEventHandler("mymodule", "OnMacrosProductCreate", "OnMacrosProductCreate"); ``` -------------------------------- ### Schedule Agent Tasks in PHP with Bitrix Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Demonstrates how to define an agent class with a static method and schedule it to run periodically using `CAgent::AddAgent`. Agents are used for running tasks on a schedule, such as daily maintenance or data updates. The `runAgent` method must return a string representing the next call. ```php final class MyAgent { public static function runAgent(): string { // Agent logic return __METHOD__ . "();"; } } // Schedule agent \CAgent::AddAgent( name: '\MyAgent::runAgent();', module: 'demo.module', interval: 86_000, // once per day ); ``` -------------------------------- ### Pagination Implementation with Page Navigation Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Implements paginated data retrieval using PageNavigation parameter that automatically handles limit and offset. Returns paginated results with total count callback for proper pagination controls. ```php use \Bitrix\Main\Engine\Response; use \Bitrix\Main\UI\PageNavigation; public function listChildrenAction(Folder $folder, PageNavigation $pageNavigation) { $children = $folder->getChildren([ 'limit' => $pageNavigation->getLimit(), 'offset' => $pageNavigation->getOffset(), ]); return new Response\DataType\Page('files', $children, function() use ($folder) { return $folder->countChildren(); }); } ``` -------------------------------- ### File Operations - Upload, Retrieval, and Download Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Handles file operations including saving uploads to server, retrieving file information, serving files as downloads via BFile response, and serving resized images. Supports both local storage and S3 storage backends. ```php // Save file $fileId = CFile::SaveFile( $_FILES['file'], 'path-to-file', ); // Get file $fileInfo = CFile::GetByID($fileId); // Serve file as download public function downloadAction($orderId) { return \Bitrix\Main\Engine\Response\BFile::createByFileId($fileId); } // Serve resized image public function showAvatarAction($userId) { return \Bitrix\Main\Engine\Response\ResizedImage::createByImageId($imageId, 100, 100); } ``` -------------------------------- ### Create and Dispatch Custom Events in PHP Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Defines a custom event class extending Bitrix's Event and demonstrates how to dispatch it and process its results. This enables decoupled module communication and extensibility. Dependencies include the BitrixMainEvent and BitrixMainEventResult classes. ```php final class MyEvent extends \Bitrix\Main\Event { public function __construct( public readonly string $orderId, public readonly string $status, ) { parent::__construct( 'demo.module', __CLASS__, ); } } // Dispatch event $event = new MyEvent(1, 'created'); $event->send(); // Process event results foreach ($event->getResults() as $eventResult) { switch($eventResult->getType()) { case \Bitrix\Main\EventResult::ERROR: // Handle error break; case \Bitrix\Main\EventResult::SUCCESS: $handlerRes = $eventResult->getParameters(); break; } } ``` -------------------------------- ### JavaScript AJAX Call to Bitrix Controller Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Demonstrates how to call a Bitrix controller action ('vendor:example.Item.add') from the frontend using BX.ajax.runAction. It sends data and handles success or error responses, showing the expected JSON structure. ```javascript BX.ajax.runAction('vendor:example.Item.add', { data: { fields: { ID: 1, NAME: "test" } } }).then(function (response) { console.log(response); // { // "status": "success", // "data": { "ID": 1, "NAME": "test" }, // "errors": [] // } }, function (response) { console.log(response); // { "status": "error", "errors": [...] } }); ``` -------------------------------- ### User Authentication and Operations (PHP) Source: https://context7.com/andrushin-anton/testing-context7/llms.txt This PHP code snippet demonstrates various user management operations within the Bitrix Framework. It includes checking user permissions, registering users, blocking accounts, setting password expiration, retrieving user groups, and adding users to groups. Ensure the CUser class and necessary configurations are available in your environment. ```php /** * @var CUser $USER */ // Check permissions if ($USER->CanDoOperation('edit_file')) { // User has permission } // Register user $USER->SimpleRegister('user@example.com'); // Block user $USER->Update(234, [ 'BLOCKED' => 'Y', ]); // Require password change $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' => '01.12.2025', ], ]); ``` -------------------------------- ### Process Tasks Asynchronously with Message Queues in PHP Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Details how to define a message class extending `AbstractMessage`, send it to a queue, and process it using a custom receiver. This enables asynchronous task processing, improving application performance and responsiveness. Dependencies include `BitrixMainMessengerEntityAbstractMessage` and `BitrixMainMessengerReceiverAbstractReceiver`. ```php // Define message class MyMessage extends \Bitrix\Main\Messenger\Entity\AbstractMessage { public function __construct( public readonly int $id, public readonly string $content, public readonly \Bitrix\Main\Type\DateTime $created, ) {} } // Send to queue $message = new MyMessage(1, 'any text', new \Bitrix\Main\Type\DateTime()); $message->send('queue_id'); // Process message class MyMessageHandler extends \Bitrix\Main\Messenger\Receiver\AbstractReceiver { protected function process(MessageInterface $message): void { if (($message instanceof MyMessage) === false) { throw new UnprocessableMessageException($message); } // Process message } } ``` -------------------------------- ### Send SMS Messages Using Bitrix Event System Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Illustrates sending SMS messages through configured providers using the Bitrix event system. It involves creating an `\Bitrix\Main\Sms\Event` object with an event name and fields, then setting the site ID and sending the message. Dependencies include the `\Bitrix\Main\Sms\Event` class. ```php $event = new \Bitrix\Main\Sms\Event('WELCOME_SMS', [ 'NAME' => $userName, 'CONFIRM_LINK' => $confirmUrl, ]); $event->setSiteId(SITE_ID); $event->send(); ``` -------------------------------- ### Bitrix Routing Configuration Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Configures URL routes for a Bitrix application using RoutingConfigurator. It defines a default route for the homepage and a group of routes for '/post' URLs, including a named route 'post-get' with a regex constraint. ```php use Bitrix\Main\Routing\RoutingConfigurator; return function (RoutingConfigurator $routes) { $routes->any('/', [ \Demo\Module\Controller\Page::class, 'index', ]); $routes ->prefix('/post') ->group(function (RoutingConfigurator $routes) { $routes ->any('{code}', [ \Demo\Module\Controller\Post::class, 'get', ]) ->where('code', '\w+') ->name('post-get'); }); }; ``` -------------------------------- ### Render HTML Views from Controller Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Renders HTML views with automatic template integration by returning View object with template name and context parameters. ```php class EntityController extends Controller { public function indexAction(): View { return $this->renderView('entity/index', [ 'param' => 'value', ]); } } ``` -------------------------------- ### Render JavaScript Extensions with SSR-like Functionality Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Renders JavaScript extensions from controller actions with server-side rendering-like functionality by returning Extension object with extension module name and configuration options. ```php class EntityController extends Controller { public function indexAction(): Extension { return $this->renderExtension('mymodule.vue.widget', [ 'option' => 'name', ]); } } ``` -------------------------------- ### Dependency Injection in Controller Actions Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Automatically injects objects and services into controller actions using ExactParameter. Loads Folder objects by ID and injects them as method parameters, enabling direct access to loaded entities without manual retrieval. ```php 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, string $newName) { $folder->setName($newName); $folder->save(); } public function downloadAction(Folder $folder) { return \Bitrix\Main\Engine\Response\BFile::createByFileId($folder->getFileId()); } } ``` -------------------------------- ### Role-Based Access Control Implementation Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Implements role-based access control by extending BaseAccessController to define item and user loading logic. Provides methods to check individual item access and filter queries based on user permissions. ```php use Bitrix\Main\Access\AccessibleItem; use Bitrix\Main\Access\BaseAccessController; use Bitrix\Main\Access\User\AccessibleUser; 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->can($user->getId(), 'view', $id)) { // User has access } } public function listAction(PostAccessController $access) { $query = MyPost::query(); $filter = $access->getEntityFilter( 'view', $query->getEntity()->getObjectClassName() ); if ($filter) { $query->addFilter($filter); } $rows = $query->fetchCollection(); } } ``` -------------------------------- ### PHP Generate URL from Named Route Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Shows how to dynamically generate a URL in PHP by referencing a named route ('post-get') and providing its parameters. This avoids hardcoding URLs and improves maintainability. It utilizes the Bitrix Application router. ```php $router = \Bitrix\Main\Application::getInstance()->getRouter(); $url = $router->route('post-get', ['code' => 'my-post']); // Output: /post/my-post ``` -------------------------------- ### PHP ORM Query Builder for Single Record Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Constructs an ORM query using Bitrix's object-oriented syntax to fetch a single user record based on login and active status. It demonstrates filtering and fetching as an object, allowing subsequent modification and saving. ```php use Bitrix\Main\UserTable; $user = UserTable::query() ->where('LOGIN', '=', 'user@example.com') ->where('ACTIVE', true) ->fetchObject(); $user->setActive(true); $user->save(); ``` -------------------------------- ### PHP MVC Controller for Item Operations Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Defines a Bitrix MVC controller with methods to add and view items. It handles business logic and returns data or errors, adhering to Bitrix's controller structure. Dependencies include BitrixMainEngineController and BitrixMainError. ```php namespace Vendor\Example\Controller; use Bitrix\Main\Engine\Controller; use Bitrix\Main\Error; class Item extends Controller { public function addAction(array $fields): ?array { $item = Item::add($fields); if (!$item) { $this->addError(new Error('Could not create item.', 'ITEM_ADD_ERROR')); return null; } return $item->toArray(); } public function viewAction($id): ?array { $item = Item::getById($id); if (!$item) { $this->addError(new Error('Could not find item.', 'ITEM_NOT_FOUND')); return null; } return $item->toArray(); } } ``` -------------------------------- ### Send Templated Emails Using Bitrix Event System Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Demonstrates sending templated emails via the Bitrix event system. It utilizes the `\Bitrix\Main\Mail\Event::send` method, requiring `SITE_ID`, `EVENT_NAME`, and `FIELDS` for the email content. This is useful for transactional emails like welcome messages. ```php \Bitrix\Main\Mail\Event::send([ 'LID' => SITE_ID, 'EVENT_NAME' => 'WELCOME_EMAIL', 'FIELDS' => [ 'NAME' => $userName, 'CONFIRM_LINK' => $confirmUrl, ], ]); ``` -------------------------------- ### Validate Data Using PHP Attributes in Bitrix Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Demonstrates data validation using PHP attributes for type-safe input handling within the Bitrix framework. It shows how to apply validation rules like `AtLeastOnePropertyNotEmpty`, `Email`, `Phone`, and `PositiveNumber` to class properties. The `main.validation.service` is used to perform the validation. ```php use Bitrix\Main\Validation\Rule\AtLeastOnePropertyNotEmpty; use Bitrix\Main\Validation\Rule\Email; use Bitrix\Main\Validation\Rule\Phone; use Bitrix\Main\Validation\Rule\PositiveNumber; #[AtLeastOnePropertyNotEmpty(['email', 'phone'])] final class User { #[PositiveNumber] private ?int $id; #[Email] private ?string $email; #[Phone] private ?string $phone; } // Validate object use Bitrix\Main\DI\ServiceLocator; $validation = ServiceLocator::getInstance()->get('main.validation.service'); $user = new User(); $user->setEmail($email); $user->setPhone($phone); $result = $validation->validate($user); if (!$result->isSuccess()) { foreach ($result->getErrors() as $error) { echo $error->getMessage(); } } ``` -------------------------------- ### PHP Controller Action Filters with Attributes Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Applies action filters like Authentication, HttpMethod (POST), and Cors to controller actions using PHP attributes in Bitrix. This simplifies access control and request handling for controller methods. ```php namespace Demo\Module\Controller; use Bitrix\Main\Engine\ActionFilter\Attribute\Rule\Authentication; use Bitrix\Main\Engine\ActionFilter\Attribute\Rule\Cors; use Bitrix\Main\Engine\ActionFilter\Attribute\Rule\HttpMethod; use Bitrix\Main\Engine\Controller; class Post extends Controller { #[Authentication] #[HttpMethod(['POST'])] public function updateAction(int $id, PostForm $form) { // Update logic } #[Cors(allowOrigin: '*')] public function getAction(string $code) { // Get logic } } ``` -------------------------------- ### Controller Validation with Attributes and Auto-wiring Source: https://context7.com/andrushin-anton/testing-context7/llms.txt Implements automatic validation for controller action parameters using attribute-based rules and validation engines. Validates login (phone or email), password, and password confirmation fields. If validation fails, the action won't execute, providing automatic error handling. ```php use Bitrix\Main\Validation\Rule\NotEmpty; use Bitrix\Main\Validation\Rule\PhoneOrEmail; final class CreateUserDto { public function __construct( #[PhoneOrEmail] public ?string $login = null, #[NotEmpty] public ?string $password = null, #[NotEmpty] public ?string $passwordRepeat = null, ) {} } class UserController extends Controller { public function getAutoWiredParameters() { return [ new \Bitrix\Main\Validation\Engine\AutoWire\ValidationParameter( CreateUserDto::class, fn() => CreateUserDto::createFromRequest($this->getRequest()), ), ]; } public function createAction(CreateUserDto $dto): Result { // If $dto is invalid, this action won't execute // Create user logic } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.