компонент-класс personal:security
class.php
вызов компонента на странице
шаблон personal.php
можно обращаться не к компоненту, а к модулю
https://hmarketing.ru/blog/bitrix/bx-ajax-runcomponentaction/
| /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>
|
можно обращаться не к компоненту, а к модулю
https://hmarketing.ru/blog/bitrix/bx-ajax-runcomponentaction/
- nikaverro.mymodule - модуль
- api - неймспейс который мы зарегистрировали в файле .settings.php модуля
- myClass - название файла и класса в папке lib/controller
- myMethod - метод myMethodAction в классе myClass
var request = BX.ajax.runAction('nikaverro:mymodule.api.myClass.myMethod', {
data: {
param1: 'value1',
param2: 'value2'
}
});
request.then(function(response){
console.log(response);
}); |