Обучаю битриксу программистов, интеграторов. Подробнee ⇒

Классы-компоненты, контроллеры, BX.ajax.runComponentAction



компонент-класс personal:security
/local/components/personal/security/
---templates/europe/ - папка с шаблоном
------personal.php
------second.php
---class.php
---ajax.php - может быть

class.php
<?php

use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Engine\Contract\Controllerable;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use \Bitrix\Main\Application;




class securityPersonal  extends Controller implements Controllerable {

    public function configureActions()
    {
        return [ 
            'deleteAccount' => [  
                'prefilters' => [
                    new HttpMethod(
                        array(HttpMethod::METHOD_POST)
                    ),
                    new Csrf(),
                ],
                'postfilters' => []
            ],
            'second' => ''
        ];
    }
    
    //обработка действия удаления
    public function deleteAccountAction($action, $sessid, $id){ 
        global $USER;
        
        if($action != 'deleteAccount'){
            throw new \Exception("Technical error", 1);
        }
        if (!check_bitrix_sessid()) {
            throw new \Exception("SESSION_EXPIRED", 1);
        }
        if(!$USER->IsAuthorized()) {
            throw new \Exception("User is not authorized", 1);
        }
        if($USER->getID() == $id){
            $user = new CUser;
            $fields = Array(
                "ACTIVE" => false,
            );
            $user->Update($id, $fields);
            if($user->LAST_ERROR){
                throw new \Exception($user->LAST_ERROR, 1);
            }
        }
        else{
            throw new \Exception("You can't delete not your account", 1);
        }
        return 'Your account was successful delete! You will be redirect at the main page.';
    }
    
    public function secondAction($action, $sessid){ 
       //может быть и другое действие              
    }
     
    function getData(){ 
       //могут быть и другие в классе методы

    }   


    //вызов компонента с "controller" => "security"
    function securityController()
    {
        global $USER;
        $this->arResult["USER_ID"] = $USER->getID();
        $this->arResult["EMAIL"] = $USER->getEmail();
        $this->includeComponentTemplate("personal"); //шаблон personal.php

    }
    
    //можно и другие контроллеры в классе иметь 
    function secondController(){ 
        $this->includeComponentTemplate("second"); //шаблон second.php
    }    
}
вызов компонента на странице
$params = [
    "controller" => "security", // запустится securityController()
    "data" => $_REQUEST
];

$APPLICATION->IncludeComponent(
   'personal:security', // пространство имён компонента
   'europe', // наименование шаблона компонента
    $params
);

шаблон  personal.php
You can delete your <b><?=$arResult["EMAIL"]?></b> account.<br>           
<a href="#" class="btn btn-primary delete-account w-100" >Delete account</a>

<script>
                $(document).ready(function() {
                    $(document).on('click', '.delete-account', function(e) {
                        e.preventDefault();
                        if (confirm('Are you sure you want to delete your account?')) {
                            //пох на порядок, главное назвать также как и описано в deleteAccountAction($action, $sessid, $id) 
                            var data = {
                                id : <?=$arResult["USER_ID"]?>,
                                action: 'deleteAccount',
                                sessid: BX.message('bitrix_sessid'),
                            };
                            var request = BX.ajax.runComponentAction("personal:security", "deleteAccount", {
                                mode: "class",
                                data: data 
                            });
                            
                            //ловим ошибки
                            request.catch(function(response) {                               
                                var message = response.errors[response.errors.length - 1].message;                                
                                console.log(response);                                
                                
                            });

                            //получаем ответ
                            request.then(function(response) {                                
                                if (response.status == "success") {
                                    console.log(response.data);                                      
                                }
                            });
                        }
                    });
                });
</script>           
        
Если блог был полезным, можете угостить меня "чашечкой кофе" :)

Сбер по номеру телефона +7 (953) 585-13-09 Вероника.
Спасибо!