Como guardar o valor do input em função callback

Como posso guardar em uma variável o valor do input na função abaixo ?

showSwalConfirmText(callback) {         const { value: text } = this.swal.question({             title: 'Você tem certeza?',             input: 'textarea',             inputPlaceholder: 'Digite o motivo...',             showCancelButton: true,             confirmButtonColor: '#3085d6',             cancelButtonColor: '#d33',             confirmButtonText: 'Sim',             cancelButtonText: 'Não',             confirmButtonClass: 'btn btn-success',             cancelButtonClass: 'btn btn-danger',             buttonsStyling: true,                      }).then(function () {             callback(true);         }, function (dismiss) {             if (dismiss === 'cancel') {                 callback(false);             }         });     }

Triggering a callback when user put in the Konami cheat code anywhere in the page

I wrote this just for some fun and also to practise my ES6 skills. When user key in the Konami Cheat Code(⬆️⬆️⬇️⬇️⬅️➡️⬅️➡️🅱️🅰️↩️) anywhere in the page, it should trigger a callback. In the following example, it should trigger an alert.

What could be improved?

Are there more ES6 features I could use in this code?

const {onKonamiSequenceTriggered, clearKonamiSequanceTriggered} = (() => {     const konamiSequence = ["ARROWUP", "ARROWUP", "ARROWDOWN", "ARROWDOWN", "ARROWLEFT", "ARROWRIGHT", "ARROWLEFT", "ARROWRIGHT", "B", "A", "ENTER"];     konamiSequence.reverse();     let currentSequence = Array.prototype.slice.call(konamiSequence);      const callbacks = {};      let eventId = 0;      const onKonamiSequenceTriggered = callback => {         callbacks[eventId] = callback;         return eventId++;     };      const clearKonamiSequanceTriggered = id => delete callbacks[id];      document.addEventListener("keyup", event => {         if (event.key.toUpperCase() !== currentSequence.pop()) {             currentSequence = Array.prototype.slice.call(konamiSequence);         }         if (!currentSequence.length) {             Object.values(callbacks).forEach(callback => {                 try {                     callback();                 } catch (e) {                     console.error(e);                 }             });             currentSequence = Array.prototype.slice.call(konamiSequence);         }     });      return {         onKonamiSequenceTriggered,         clearKonamiSequanceTriggered     }; })();  onKonamiSequenceTriggered(() => alert("You've got it!")); 

How to transform a quote into an order from CALLBACK HOOKS, MAGENTO 2.3

I’m trying to integrate a payment gateway. And they provide a callback hooks i’ve set for them to return me the CartID (Quote’s entity_id).

But from here on, it feels like it isnt right for me to call guest API, as the cart belongs to an actual customer’s cart. Neither do i have the access tokens when the callback hook is being sent to the API i’ve created.

How can i create the order (sales_order table & sales_order_grid) based on the quote i could receive ?

Please advise what should i do as im stuck on this for 3 days.

can’t access ‘this’ function in React callback

I have a React component where by I need to change the state after a successful database call. The database call uses a callback function, which I can’t change, however I can’t find a way to access the redirect function in the same component, from within the call back function. I just get the error enableRedirect' of null

I’ve tried changing the callback function to an arrow function, but then it doesn’t get called correctly. I’ve been reading other answers to similar problems, but can’t make it apply to my situation

    ...     componentDidUpdate = (prevProps, prevState) => {     if (prevState.braintreeToken !== this.state.braintreeToken) {        dropin.create(         {           authorization: this.state.braintreeToken,           container: "#dropin-container",         }, //callback function happens here         (createErr, instance) => {           button.addEventListener("click", function() {             instance.requestPaymentMethod(function(               requestPaymentMethodErr,               payload             ) {               api                 .submitPayload(payload, plan, id)                 .then(res => {                   //this is where I'm trying to call my enable redirect function                   this.enableRedirect();                 })                 .catch(err => {                   //error handling                 });             });           });         }       );     }   };      // the function I'm trying to call     enableRedirect = () => {       this.setState({         redirect: true       });     };  ... 

I need the enableRedirect Function to be called in the callback!

How to solve “@deprecated — Use an observer instead of a complete callback”?

So I was trying to get data by using http call and after I use my code, It won’t work and when I check, it does not produce any array. It gave me this message after I hover my mouse over the subscribe function.

Here are my code:

public getCust(){ this.http.get(this.thisUrl+’name=’+this.param.namaID+’&dob=’+this.param.dob+’&idno=’+this.param.idno+’&idt=’+this.param.idt+’&norek=’+this.param.norek+’&cif=’+this.param.cif) .subscribe((res : any[])=>{ console.log(res); this.custs = res; }) }

These are the message that produce by me hovering over the subscribe function:

(method) Observable.subscribe(next?: (value: Object) => void, error?: (error: any) => void, complete?: () => void): Subscription (+4 overloads) @deprecated — Use an observer instead of a complete callback

@deprecated — Use an observer instead of an error callback

@deprecated — Use an observer instead of a complete callback

How do i use onHourShow callback in a date_popup control with the Form API

On my form I have a date_popup control:

$  form['order-group']['delivery'] = array(     '#title'                => t('I Need The Equipment Ready By'),     '#type'                 => 'date_popup',     '#date_format'          => 'd-M-Y H:i',     '#timepicker'           => 'timepicker',     '#timepicker_options'   => array(         'rows'            => 3,         'hours'         => array(             'starts'    => 12,             'ends'      => 17,         ),         'onHourShow'   => 'onHourShow(hour)',         'minutes'         => array(             'starts'    => 0,             'ends'      => 0,         ),         'showCloseButton' => TRUE,         'closeButtonText' => t('Close'),     ),     '#default_value'  => date('Y-m-d 12:00',time()),     '#date_label_position'  => '', );  

I only want the hours 12, 15 and 17 to be available so I added the onHourShow Javascript callback.

I then added the following to my javascript file (included with drupal_add_js, earlier in the script)

function onHourShow(hour) {     if (hour == 12 || hour == 15 || hour == 17) {         return true;     } else {         return false;     } } 

In the console I get the following error:

Uncaught TypeError: onHourShow.apply is not a function     at Timepicker._generateHTMLHourCell (jquery.ui.timepicker.js?psw6eo:797)     at Timepicker._generateHTML (jquery.ui.timepicker.js?psw6eo:622)     at Timepicker._updateTimepicker (jquery.ui.timepicker.js?psw6eo:467)     at Timepicker._setTimeFromField (jquery.ui.timepicker.js?psw6eo:1112)     at Timepicker._attachTimepicker (jquery.ui.timepicker.js?psw6eo:190)     at HTMLInputElement.<anonymous> (jquery.ui.timepicker.js?psw6eo:1474)     at Function.each (jquery.min.js?v=1.7.2:2)     at $  .fn.init.each (jquery.min.js?v=1.7.2:2)     at $  .fn.init.$  .fn.timepicker (jquery.ui.timepicker.js?psw6eo:1470)     at Object.attach (date_popup_timepicker.timepicker.js?psw6eo:8) 

How can i add ajax callback to checkbox in drupal form?

I am using taxonomy manager module I want to add ajax callback to checkbox tree view for checkbox is checked condition but it is not working can some one please suggest me. I have modified the code like this

$  form[$  term->tid]['checkbox'] = array(       '#type' => ($  multiple) ? 'checkbox' : 'radio',       '#title' => $  term->name, // Escaping is done in theme wrappers.       '#value' => $  value,       '#return_value' => $  term->tid,       '#ajax' => array(         'callback' => 'ajax_example_autocheckboxes_callback',         'wrapper' => 'checkboxes-div',         'method' => 'replace',         'effect' => 'fade',       ),       '#required' => FALSE,       '#theme_wrappers' => ($  multiple) ? array('taxonomy_manager_tree_checkbox') : array('taxonomy_manager_tree_radio'),       '#highlight' => in_array($  term->tid, $  terms_to_highlight) ? TRUE : FALSE,     ); 

This is the taxonomy manager module themefunction

function theme_taxonomy_manager_tree_checkbox($  variables) {    global $  user;   $  element = $  variables['element'];   $  element['#attributes']['type'] = 'checkbox';   $  element['#attributes']['ajax']['event'] = 'change';   element_set_attributes($  element, array('id', 'name', '#return_value' => 'value'));    // Unchecked checkbox has #value of integer 0.   if (!empty($  element['#checked'])) {     $  element['#attributes']['checked'] = 'checked';   }   _form_set_class($  element, array('form-checkbox'));   $  output = '<input' . drupal_attributes($  element['#attributes']) . ' />';   /* custom alter function */   if(user_is_logged_in()){     if(!user_access('administer taxonomy')){       $  cdms_taxonomy_id = taxonomy_term_load($  element['#return_value']);        // echo "IF"; exit;          }else{       $  cdms_taxonomy_id = taxonomy_term_load($  element['#return_value']);       // echo "Else"; exit;           }   }   // echo '<pre>';print_r($  variables);  echo"Term load"; print_r($  cdms_taxonomy_id);  exit;   $  data = [     'title' =>  $  element['#title'],     'tid' => @$  cdms_taxonomy_id->field_cdms_txy_id[LANGUAGE_NONE][0][value],     'count' => '',   ];   // Calling all modules implementing hook_my_data_alter():   drupal_alter('my_data', $  data);    if (!in_array("Client User", array_values($  user->roles))) {   $  title = $  element['#title'] ."(".$  data['count'].")"; }else{    $  title = $  element['#title']; }   if (in_array("Client User", array_values($  user->roles))) {     $  title = check_plain($  title);   }else{     if (isset($  element['#link'])) {         $  attr = array();         $  attr["class"][] = "term-data-link";         $  attr["class"][] = "term-data-link-id-" . $  element['#return_value'];         if (isset($  element['#extra_info'])) {           $  attr["title"] = $  element['#extra_info'];         }         $  title = l($  title, $  element['#link'], array('attributes' => $  attr));       }       else {         $  title = check_plain($  title);       }   }    $  element['#children'] = '<label class="option">' . $  output . ' ' . $  title . '</label>';   $  element['#title_display'] = 'none';   return theme('form_element', array('element' => $  element)); } 

Обработка/отправка сообщений беседы CallBack api

Давно меня посетила мысль о написании бота для нужд автоответчика. Недавно я приступил к делу, с LongPoll не возникало проблем. Причина по-которой я решил перейти на CallBack api было то, что он работает на удалённом сервере.

Решил я сделать его для беседы; есть же беседы в WhatsApp/Viber , где несколько людей интересуются одной темой. В интернете по-этому поводу информации нужной я не нашёл и решил обратиться сюда. Проблема: Бот не видит сообщения в беседе. С правами администратора, с доступом к сообщениям, с упоминаниями, ни в какую не хочет реагировать. Писать в беседу он может, но путём ручной установки id беседы. Беседу не видно в сообщениях сообщества, так же бот не видит сообщения принципе. Вопросы: Как получить сообщение ботом при обращении или других махинациях?

from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse import json, requests, random2, vk, editdistance  # keyboard = { #     "one_time": time, #     "buttons": [ #     [vl.button(text, color)], #     ]} # keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8') # keyboard = str(keyboard.decode('utf-8'))  token = '' confirmation_token = '' secret_key = ''  sk = '' directory = 'mybot/vk_bot/'  session = vk.Session() api = vk.API(session, v=5.95)  class methods(object):     def __init__ (self, uid=''):         self.uid = uid      def fix(self, word, need_word): # Дистанция Левенштейна         number = editdistance.eval(word, need_word) # Количество отличающихся букв в словах         return number      def dlt(self, text, chars="+×÷=%_€£¥₩@#$  /^&№\"\'*()-':;!,.`~\|}{][▪○●□■♤♡♢♧☆⊙°•¤《》¡¿0123456789"): # Гибкая версия удаления символов         for c in chars:             text = text.replace(c, "")         return text      def rep(self, text, symbols=('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','[',']','{','}',';',':', '\'', '\"', ',', '<', '.', '>'), syllables=('й','ц','у','к','е','н','г','ш','щ','з','ф','ы','в','а','п','р','о','л','д','я','ч','с','м','и','т','ь','х','х','ъ','ъ','ж','ж','э','э','б','б','ю','ю')): # Гибкая замена         for symbol in symbols:             text = text.lower().replace(symbol, syllables[symbols.index(symbol)])         return text      def clr(self, text, symbols=('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','[',']','{','}',';',':', '\'', '\"', ',', '<', '.', '>'), syllables=('й','ц','у','к','е','н','г','ш','щ','з','ф','ы','в','а','п','р','о','л','д','я','ч','с','м','и','т','ь','х','х','ъ','ъ','ж','ж','э','э','б','б','ю','ю'), chars="+×÷=%_€£¥₩@#$  /^&№\"\'*()-':;!,.`~\|}{][▪○●□■♤♡♢♧☆⊙°•¤《》¡¿0123456789"): # Гибкая очистка текста         for c in chars:             text = text.replace(c, "")         for symbol in symbols:             text = text.lower().replace(symbol, syllables[symbols.index(symbol)])         return text      def zamena(self, text): # Замена по звукам на русские         symbols = ('sh','zh','q','w','e','r','t','ya','ia','u','o','p','[','{',']','}','a','s','d','f','g','h','j','k','l',';',':','\'','\"','z','x','c','v','b','n','m',',','<','.','>','y','i','1','2','3','4','5','6','7','8','9','0')         syllables = ('ш','ж','к','в','е','р','т','я','я','у','о','п','х','х','ъ','ъ','а','с','д','ф','г','х','ж','к','л','ж','ж','ь','э','з','х','с','в','б','н','м','б','б','ю','ю','ы','и','о','д','т','ч','п','ш','с','в','д','о')         for symbol in symbols:             text = text.lower().replace(symbol, syllables[symbols.index(symbol)])         return text      def add(self, answer, ufile,directory="", need_format=".txt", text="QWERTGDRTIKGFTY", answer_2=""): # Запоминание текста в .txt файл         try:             f = open(directory+ufile+need_format, 'r')             qwe = f.read()             f.close()             begin = "#START#\n"             end = "#END#"             if answer + answer_2 not in qwe:                 virus_code=''                 with open(directory+ufile+need_format, 'r') as file:                     for line in file:                         if begin in line or '#START#' in line:                             pass                         elif line == text or line == text + "\n":                             pass                         elif end in line or '#END#\n' in line:                             break                         elif '\n' not in line:                             virus_code+=line+'\n'                         elif '\n' in line:                             virus_code+=line                         else:                             virus_code+=line                 with open(directory+ufile+need_format, 'w') as file:                     file.write(begin + answer + answer_2 + '\n' + virus_code + end)                 return False             else:                 return True         except:             virus_code=''             with open(directory+ufile+need_format, 'r') as file:                 for line in file:                     if begin in line or '#START#' in line:                         pass                     elif end in line or '#END#\n' in line:                         break                     elif '\n' not in line:                         virus_code+=line+'\n'                     elif '\n' in line:                         virus_code+=line                     else:                         virus_code+=line             with open(directory+ufile+need_format, 'w') as file:                 file.write(begin + virus_code + end)             return False      def sudoadd(self, answer, ufile,directory="", need_format=".txt", text="QWERTGDRTIKGFTY", answer_2=""): # Запоминание текста в .txt файл         try:             begin = "#START#\n"             end = "#END#"             virus_code=''             with open(directory+ufile+need_format, 'r') as file:                 for line in file:                     if begin in line or '#START#' in line:                         pass                     elif line == text or line == text + "\n":                         pass                     elif end in line or '#END#\n' in line:                         break                     elif '\n' not in line:                         virus_code+=line+'\n'                     elif '\n' in line:                         virus_code+=line                     else:                         virus_code+=line             with open(directory+ufile+need_format, 'w') as file:                 file.write(begin + answer + answer_2 + '\n' + virus_code + end)         except:             virus_code=''             with open(directory+ufile+need_format, 'r') as file:                 for line in file:                     if begin in line or '#START#' in line:                         pass                     elif end in line or '#END#\n' in line:                         break                     elif '\n' not in line:                         virus_code+=line+'\n'                     elif '\n' in line:                         virus_code+=line                     else:                         virus_code+=line             with open(directory+ufile+need_format, 'w') as file:                 file.write(begin + virus_code + end)      def fileclr(self, ufile, directory="", need_format=".txt"): # Очистка файла         begin = "#START#\n"         end = "#END#"         file = open(directory+ufile+need_format, 'w')         file.write(begin + end)         file.close()      def uprandw(self, file, s1, s2, directory="", need_format=".txt"): # Гибкая случайная строка из файла         h=open(directory+need_format,'r')         x = random2.randint(s1,s2)         for i in range(x):             h.readline()         y = h.readline()         h.close()         return y      def randw(self, file, directory="", need_format=".txt"): # Случайная строка из файла         f = open(directory+file+need_format, 'r')         qwerty = []         begin = "#START#\n"         end = ("#END#", "#END#\n")         qwerty.extend(f)         f.close()         for word in qwerty:             for w in end:                 if begin in qwerty:                     qwerty.remove(begin)                 elif w in qwerty:                     qwerty.remove(w)         return random2.choice(qwerty)      def fixfind(self, file, find, directory="", need_format=".txt", text="Text: ", answer="Answer: "): # Найти самый подходящий противолежащий по индексу текст         f = open(""+file+'.txt', 'r')         qwe = []         qwe.extend(f)         f.close()         qwerty_1 = []         qwerty_2 = []         for line in qwe:             if text in line:                 line = line.replace(text, '')                 line = line.replace('\n', '')                 qwerty_1.append(line)             elif answer in line:                 line = line.replace(answer, '')                 line = line.replace('\n', '')                 qwerty_2.append(line)         for word in qwerty_1:             x = editdistance.eval(word, find)             if x < 3:                 find = word                 y = qwerty_2[qwerty_1.index(find)]                 return y      def find(self, file, find, directory="", need_format=".txt", text="Text: ", answer="Answer: "): # Найти противолежащий по индексу текст         f = open(""+file+'.txt', 'r')         qwe = []         qwe.extend(f)         f.close()         qwerty_1 = []         qwerty_2 = []         for line in qwe:             if text in line:                 line = line.replace(text, '')                 line = line.replace('\n', '')                 qwerty_1.append(line)             elif answer in line:                 line = line.replace(answer, '')                 line = line.replace('\n', '')                 qwerty_2.append(line)         y = qwerty_2[qwerty_1.index(find)]         return y      def rus(self, text, padej, chislo=False): # Склонение по русским падежам         '''         И - Именительный         Р - Родительный         В - Винительный         Д - Дательный         Т - Творительный         П - Предложный         '''         url = "https://ws3.morpher.ru/russian/declension"         params = dict (             s=text,             format="json",             )         response = requests.get(url=url, params=params)         data = json.loads(response.text)          if chislo != False:             x = data.get('множественное').get(padej)             return x         else:              x = data.get(padej)             return x      def sms(self, answer, chat=False): # Отправка сообщения         if chat == False:             api.messages.send(access_token=token, peer_id=self.uid, message=answer, random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)         else:             api.messages.send(access_token=token, peer_id=self.uid+2000000000, message=answer, random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)      def photo(self, answer, typ, oid, mid, msg='Фоточка', chat=False):    # Отправка вложения         # typ = type ; oid = id владельца (обратите внимание, если объект находится в сообществе, этот параметр должен быть отрицательным); mid = id вложения.         # type — тип медиавложения: photo — фотография; video — видеозапись; audio — аудиозапись; doc — документ; wall — запись на стене; market — товар; poll — опрос.         if chat == False:             api.messages.send(access_token=token, peer_id=self.uid, message=msg, attachment=str(typ)+str(oid)+'_'+str(mid), random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)         else:             api.messages.send(access_token=token, peer_id=self.uid+2000000000, message=msg, attachment=str(typ)+str(oid)+'_'+str(mid), random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)  class board(object):     def button(label, color, payload=""):         return {             "action": {                 "type": "text",                 "payload": json.dumps(payload),                 "label": label             },             "color": color         }      def key(uid, text, texta='', color='', colora='', another=False, time=False, chat=False):         # 1. primary #5181B8         # 2. default #FFFFFF         # 3. negative #E64646         # 4. positive #4BB34B         color = color.lower()         colora = colora.lower()         if color == 'blue':             color = 'primary'         elif color == 'green':             color = 'positive'         elif color == 'red':             color = 'negative'         else:             color = 'default'         if colora == 'blue':             colora = 'primary'         elif colora == 'green':             colora = 'positive'         elif colora == 'red':             colora = 'negative'         else:             colora = 'default'         if another == False:             keyboard = {             "one_time": time,             "buttons": [             [board.button(text, color)]]}         elif another == True:             keyboard = {             "one_time": time,             "buttons": [             [board.button(text, color)],             [board.button(texta, colora)]             ]}          keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')         keyboard = str(keyboard.decode('utf-8'))          if chat == False:             api.messages.send(access_token=token, peer_id=uid, keyboard=keyboard, random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)         else:             api.messages.send(access_token=token, peer_id=uid+2000000000, keyboard=keyboard, random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)      def mykey(uid, mybuttons, time=False, chat=False):         # 1. primary #5181B8         # 2. default #FFFFFF         # 3. negative #E64646         # 4. positive #4BB34B          keyboard = {         "one_time": time,         "buttons": [mybuttons]}          # [board.button(text, color)],         # [board.button(text, color)]          keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')         keyboard = str(keyboard.decode('utf-8'))          if chat == False:             api.messages.send(access_token=token, peer_id=uid, keyboard=keyboard, random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)         else:             api.messages.send(access_token=token, peer_id=uid+2000000000, keyboard=keyboard, random_id=random2.randint(1, 1000000))             return HttpResponse('ok', content_type="text/plain", status=200)  class commands(object):     def __init__ (self, text, need_symbol, uid):         self.text = text         self.symbol = need_symbol         self.push = methods(uid)      def unknown(self, answer="Прости, но я не понимаю эту команду."): # Реакция на неизвестную команду         self.push.sms(answer)      def error(self): # Сообщение об ошибке         self.push.sms('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')      def newfun(self, need_text, answer): # Реакция на команду         if self.text == self.symbol+need_text:             self.push.sms(answer)             return True         else:             return False  class Main(object):     def __init__ (self, data):         self.data = data      def info(self):         text = self.data['object']['body']         uid = self.data['object']['user_id']         # user = api.users.get(uid)         # first_name = user['first_name']         # last_name = user['last_name']         # full_name = first_name +' '+ last_name         date = self.data['object']['date']         self.answer = {'message':text.capitalize(), 'user_id':str(uid), 'date':str(date)} # 'first_name':first_name, 'last_name':last_name, 'full_name':full_name         return self.answer      def AI(self):         dont = 'Я не совсем понял.'         file = 'AI'         text = self.answer['message']         zam_text = text.replace('ё', 'е')         zam_text = methods().clr(zam_text).capitalize()          push = methods(self.answer['user_id'])          if zam_text != "" and zam_text != " ":              try:                 bot_text = methods().fixfind(file, zam_text).capitalize()                 push.sms(bot_text)             except:                 push.sms(dont)                 bot_text = dont              send_text = bot_text              after = 'Text: '             later = 'Answer: '              f = open(file+'txt', 'r')             qwe = []             qwe.extend(f)             f.close()             qwerty = []             for line in qwe:                 if after in line:                     line = line.replace(after, '')                     line = line.replace('\n', '')                     qwerty.append(line)                 elif later in line:                     pass             if zam_text not in qwerty:                 methods().sudoadd("Answer: ", file, answer_2=send_text)                 methods().add("\nText: ", file, answer_2=zam_text.capitalize())         else:             push.sms(dont)          print("\n{[Сообщение: "+self.answer["message"]+']'+'['+"От: "+methods().rus(self.answer["user_id"], 'Р')+']}\n')  @csrf_exempt def index(request):     if (request.method == "POST"):         data = json.loads(request.body)          methods().add(data['type'], 'types', directory)          if (data['secret'] == secret_key):             if (data['type'] == 'confirmation'):                 return HttpResponse(confirmation_token, content_type="text/plain", status=200)             if (data['type'] == 'message_new'):                  uid = data['object']['user_id'] # peer_id 2000000000                 text = data['object']['body'].lower()                  num = methods().fix(text, 'A')                  x = methods().clr(text) # Очищаем текст                 j = methods().add(str(data['object']['date']), 'json', directory) # Записываем время сообщения в файл и проверяем наличие                 c = methods().add(str(uid), 'id', directory) # Записываем id пользователя в файл и проверяем его наличие                  if j == False and text != None and text != '' and text != ' ' and num > 1 and x != '' and x != ' ':                      # Названия переменным даны по-моим оссоциациям к этим словам                     fraid = methods(uid)                     evan = commands(text, '!', uid)                     cpp = Main(data)                      m = True                     if c == True:                         m = False                     else:                         methods().add(str(uid), 'id', directory)                         fraid.sms('Привет!')                         # Тут можно написать приветствие при первом сообщении пользователя.                      if m == False:                         # Тут можно написать ответ/обработку сообщения и любой код, ведь он выполнится, если придёт новое сообщение     else:         return HttpResponse('Я тебя вижу :)') 

Бот написан на Django. Для работы потребуется в нужной директории создать txt файлы: id, json, types, data.

Был приведён почти ведь код, для лучшего понимания.

Если нужна какая-либо дополнительная информация, то с радостью дам больше подробностей, если это поможет решить проблему.

How to add javascript after form was validated with ajax callback?

I created a simple form. How could I add JavaScript commands after form was validated? Why is it so hard do this?

$  form['submit'] = array(   '#type' => 'submit',   '#value' => 'submit',   '#validate' => 'my_validate_callback',   '#ajax' => array(     'callback' => 'my_form_callback',     'method' => 'replace',     'wrapper' => 'form-wrap',     'effect' => 'fade'   ) ); 

Form with ajax callback, know if it’s the first time it’s build

I have a form with an ajax callback, this callback replace the entire form with a new one.

The problem is that in this callback I need to know if it’s the first time the form is build or not, I make actions from this condition. I have try the basic things that I can found everywhere on the web (set a variable in the form_state if it’s not set) but I can’t make it works.

The behavior I want to have is when I click on the submit button, if it’s the first click then I open a modal wich ask if I want to confirm or not, if I confirm it just relaunch the submit (without re opening the modal), if not it does nothing.

Do you have any idea to make this ?

Here is my code :

The submit button in the form :

$  form['actions']['checkout'] = array(   '#type' => 'submit',   '#value' => t('Réserver maintenant'),   '#submit' => array('_step2_submit_callback'),   '#validate' => array('_step2_validate_callback'),   '#attributes' => array('class' => array('step2-submit-button')),   '#ajax' => array(     'callback' => '_step2_ajax_checkout_callback',     'wrapper' => 'participants-container',   ), ); 

And the callback :

function _ga_registration_step2_ajax_checkout_callback($  form, $  form_state) {   $  commands = [];    $  canCheckout = false;    if($  form_state['values']['group_assurances'] == 'none' && $  form_state['#openPopup']) {     $  canCheckout = false;   }     if ($  canCheckout) {     [...]   } else {     drupal_add_js(array('module_registration' => array('openPopup' => true)), array('type' => 'setting'));   }    return array('#type' => 'ajax', '#commands' => $  commands); } 

And here is my JS to open the popup :

 Drupal.behaviors.module_registration = {             attach: function (context, settings) {                 if(settings.module_registration.openPopup){                     settings.module_registration.openPopup = false;                     Swal.fire({                         type: '',                         customClass: 'alert_assurance',                         width: '50%',                         heightAuto: false,                         html: [...],                         showCloseButton: true,                         showCancelButton: true,                         focusConfirm: false,                         reverseButtons: true,                         confirmButtonText: [...],                         cancelButtonText: [...],                     }).then((result) => {                         if (result.value) {                             // Click on the submit button (to continue)                             $  ('.step2-submit-button').mousedown();                         }                     })                 }              }         }; 

And the problem is that when I close the popup and it click on the submit button, it reopen the popup.. And even with values in form_state I can’t manage to know when it’s the first time the form is created