javascript – Cambiar el valor de una variable luego de recibirla a través de una función callback

Quisiera ayuda por favor en cómo hacer lo siguiente: Estoy modificando un programa no escrito por mí. En el programa hay una variable que se define al principio del programa a través de una asignación normal. Yo quiero que este valor cambie dinámicamente a través de lo que reciba por ejemplo desde una hoja de cálculo de google.
Para ello utilizo una libreria que consulta la google sheet, y devuelve los datos a través de un archivo JSON en una función callback. Puedo acceder al archivo y extraer el valor que requiero, pero mi problema es que no puedo reasignar el valor ya que la función callback lo devuelve luego de un tiempo. Es decir:

var a = 0;
.
.
function callback(x, y){  // los parámetros x, y son necesarios para acceder a la información

// Recibo los datos en JSON y extraigo el valor requerido "b = 100"

a = b;
console.log (a) // 100
}

console.log(a);   // 0

He intentado varias cosas pero no logro llegar a que la variable a=100 luego de la función y poder utiliar más adelante en el código.
Agradezco mucho su ayuda.

coding standards – Format of callback arguments in YAML files

For instance, for the Filter module, in filter.permissions.yml, custom permissions are defined:

permission_callbacks:
  - DrupalfilterFilterPermissions::permissions

That looks like a static function, but it isn’t. How does that work? Is the format for this kind of callback argument documented or defined anywhere?

CSRF token is not varying in Ajax callback while submitting form

I have a form with ajax callback as following , on each submit token is not varying , it remains constant for all submit .

wall.routing.yml
wall.commentform:
path: ‘/commentform’
defaults:
_title: ‘Comment form’
_form: ‘DrupalwallFormWallCommentPost’
requirements:
_permission: ‘access content’
_csrf_token: ‘TRUE’

In from as following

WallCommentPost.php

$ajax = (
    'callback' => ($this,'_wall_comment_ajax_form_post'),
    'wrapper' => 'field-type-replace-comment',
    'event' => 'click',
    'progress' => array(
        'type' => 'throbber', 
        'message' => '',
        )
      );

$form(‘wall_submit’) = (
‘#type’ => ‘submit’,
‘#value’ => ‘Submit’,
‘#ajax’ => $ajax,
‘#prefix’ => ”,
‘#suffix’ => ”,
‘#attributes’ => array(
‘class’ => array(
‘btn’,
$ajax_class,
‘d-none’,
‘subbtn-‘.$nid
),
‘disabled’=>’disabled’
),
);
$url = Url::fromRoute(‘wall.commentform’);
#$token = Drupal::csrfToken()->get($url->getInternalPath());

$form(‘#action’) = Url::fromRoute(‘wall.commentform’)->setOption(‘query’, (FormBuilderInterface::AJAX_FORM_REQUEST => 1,’token1′ => $token))->toString();

8 – Using a #submit callback on a textfield

We have a need to add ‘repeatable fields’ to a form based on input provided in a textfield. Usually, we use a ‘add another’ button to keep track of the number of fields to render in the buildForm(), and update that number in a submit callback on the button.

The functionality we want isn’t that, though. We have a need so that when somebody enters text into a textfield (other than empty), it adds an additional group of fields below it. We are allowing people to scan barcodes, and every time they scan a barcode into a textfield, we want it to create another group of fields so they can scan another item if they want to.

We attempted to use #submit on the textfield, but #submit doesn’t appear to trigger on the textfield, as we added a print statement, as well as a $form-state->set() in there, and attempt to print out $form_state->get() on the form to no avail.

Since you can’t update the form_state inside of an ajax callback, we can’t figure out a way to achieve what we want to do (Add another group of fields once text is entered into a textarea).

Is there another way we can do this?

(We only allow 10 groups to be added per submission, so as a ‘workaround’ we dynamically add 10 groups in the buildForm, then use #states to hide each one if the previous textfield doesn’t have data, but this doesn’t allow us to add in a ‘remove’ button for each textfield so the user can remove text fields they don’t want to use.)

8 – Ajax Callback only works after second click

I created a custom form with a textbox and a button. When the user clicks on that button, an ajax call should take place.

When I click on that button for the first time, a page refresh takes place. Only when I click on the button for the second time, my ajax-function is called.

I don’t know what I’m doing wrong, so I would be greatful for any suggestion.


    $form('group_rrn')('actions') = array(
        '#type' => 'button',
        '#value' => 'Ga verder',
        '#attributes' => array('class' => array('btn', 'btn-primary')),
        '#ajax' => (
            'callback' => '::ajaxRijksregisternummer',
            'event' => 'click',
            'wrapper' => 'aanvraag',
            'progress' => array(
                'type' => 'throbber',
                'message' => 'Even geduld',
            ),                
        ),
    );

Kind regards!

plugins – Get shortcode attrs inside AJAX callback function

I need to get the attribute values passed to the shortcode inside an AJAX callback function.
With my attempts I get all NULL values. I don’t understand where I’m wrong.
Everything is within a class.

Here is the code (some rows are omitted to simplify)

class MyPlugin
{

    private $id;
    private $delimiter;
    private $file;
    private $type;
    private $width;
    private $height;
    private $values;

    

    public function __construct()
    {
        $this->starter();
    }

    public function starter()
    {

        add_shortcode('show_map', array($this, 'shortcode_func'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
  
        add_action('wp_ajax_nopriv_searchInMap', array($this, 'render'));
        add_action('wp_ajax_searchInMap', array($this, 'render'));
    }

    public function enqueue_scripts(){
    
 
        wp_register_script('leaflet-script', plugin_dir_url(__FILE__) . 'js/leaflet.js', array(), '1.0', false);
        wp_enqueue_script('leaflet-script');


        wp_register_script('cluster-script', plugin_dir_url(__FILE__) . 'js/leaflet.markercluster.js', array('leaflet-script'), '1.0', false);
        wp_enqueue_script('cluster-script');


        wp_enqueue_script('ajax-map', plugin_dir_url(__FILE__) . 'js/ajax-map.js', array('jquery'), '1.0', true);


        wp_enqueue_style('leaflet-style',  plugin_dir_url(__FILE__) . 'css/leaflet.css');
        wp_enqueue_style('cluster1-style',  plugin_dir_url(__FILE__) . 'css/MarkerCluster.css');
        wp_enqueue_style('cluster2-style',  plugin_dir_url(__FILE__) . 'css/MarkerCluster.Default.css');

        global $wp_query;
        wp_localize_script('ajax-map', 'var_ajax_map', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'query_vars' => json_encode($wp_query->query),
            'nonceMap' => wp_create_nonce('nonce-render-map'),
            'shortcodeValues' => json_encode($this->values)

        ));
    
    
    
    }
    
    public function shortcode_func($atts)
    {

        extract(shortcode_atts(
            array(
                'id' => '',
                'file' => '',
                'delimiter' => ';',
                'type' => 'normal',
                'width' => '100%',
                'height' => '600'

            ),
            $atts
        ));

        // class RenderMap: get values from a CSV file and render a map with markers 
        $map = new RenderMap($id, $file, $delimiter, $type, $width, $height);


        $this->id = $id;
        $this->file = $file; // Example: filename.csv
         //(..)
        var_dump($this->file) // You get right value here, not NULL
        
       //below another try to pass values, via $_POST
        $this->values = array(
                 'id'=>$id,
                 'file' => $file,
                'delimiter' => $delimiter,
                'type' => $type,
                'width' => $width,
                'height' => $height
                   )
    
        // class SearchInput: render the search form
        $searchInput = new SearchInput();

        $out = $searchInput->render() . '<div id="map-div">' . $map->get_map() . '</div>';
        return $out;
    }

   
    // AJAX callback
    public function render()
    {
        $text= $_POST('text');
        check_ajax_referer('nonce-render-map', 'nonce_map');

        
        var_dump($_POST('shortcodeAttrs')); // value: NULL
        
        $map2 = new MqfRenderMap($this->id, $this->file, $this->delimiter, $this->type, $this->width, $this->height); // Map not rendered, all function parameters are NULL... What's wrong?
        echo $map2->get_map($text);

        die();
    }




   
}

Content of ajax-map.js

(function ($) {





    $(document).on( 'click', '#map-search-button', function( event ) {
    
    

      event.preventDefault();
      valSearchInput = $('#map-search-input').val();
     
        

      $.ajax({
        url: var_ajax_map.ajaxurl,
        type: 'post',
        data: {
          action: 'searchInMap',
          query_vars: var_ajax_map.query_vars,
          nonce_map: var_ajax_map.nonceMap,
          text: valSearchInput,
          shortcodeAttrs: var_ajax_map.shortcodeValues

        },
        beforeSend: function () {
        

          
        },
        success: function (html) {

          $('#map-div').html(html);
        }
      })

  
    })
    





})(jQuery);

Any help is appreciated. Thank you

Dash Plotly – Import dentro de condicional em um callback

Estou desenvolvendo um app web para backtest de estratégias trading.

Essa é a tela que estou desenvolvendo

async – Como converter uma função baseada em promise para callback em JavaScript?

Podemos converter funções assíncronas que trabalham com callback para trabalharem com promises, como demonstrado nos exemplos abaixo:

callback:

const timeInMs = 1_000;

function asyncCallback(timeMs, callback) {
  setTimeout(() => callback(null, timeMs), timeMs);
}

console.log('first');

asyncCallback(timeInMs, (err, result) => {
  if (err) return console.log('Error: ', err);

  console.log('last');

  console.log('Time passed: ', result);
});

console.log('second');

Mudando para promise:

const timeInMs = 1_000;

function asyncCallback(timeMs, callback) {
  setTimeout(() => callback(null, timeMs), timeMs);
}

// função simples para converter callback em promise
function promisify(callback) {
  return function promisified(...args) {
    return new Promise((resolve, reject) => {
      const argsArray = (
        ...args,
        function (err, result) {
          if (err) return reject(err);

          resolve(result);
        },
      );

      callback(...argsArray);
    });
  };
}

// promisificando e convertendo a função asyncCallback
const asyncPromise = promisify(asyncCallback);

console.log('first');

asyncPromise(timeInMs).then((result) => {
  console.log('last');

  console.log('Time passed: ', result);
});

console.log('second');

// usando async/await
(async () => {
  const result = await asyncPromise(timeInMs);

  console.log('(async/await) Time passed: ', result);
})();

Repare que foi possível mudar de callback para promise graças a função customizada promisify().

A pergunta é:

  • Como converter uma função baseada em promise para callback, ou seja, fazer o oposto de promisify()? Algo como callbackify().

Tem uma função no Node.js chamada callbackify do core module util que faz já faz o caminho inverso:

import { callbackify } from 'util'

const timeInMs = 1_000

function asyncCallback (timeMs, callback) {
  setTimeout(() => callback(null, timeMs), timeMs)
}

function promisify (callback) {
  return function promisified (...args) {
    return new Promise((resolve, reject) => {
      const argsArray = (
        ...args,
        function (err, result) {
          if (err) return reject(err)

          resolve(result)
        },
      )

      callback(...argsArray)
    })
  }
}

const asyncPromise = promisify(asyncCallback)

const callbackFunction = callbackify(asyncPromise)

callbackFunction(timeInMs, (err, result) => {
  console.log('Time passed: ', result) // Time passed:  1000
})

Mas eu quero saber como seria feito uma função “na mão” (semelhante à promisify()), com passo a passo e com explicação detalhada, porque quero entender a lógica de implementação.

Esta minha dúivida é só uma prova de conceito e gostaria de saber…

8 – How to render a view in an ajax callback

I am trying to develop a custom module to ajaxify the commerce form block. I tried using dc_ajax_add_cart and ajax_add_to_cart but they were not addapted to my project.

I have the following callback function

function tb_ajax_cart_reload_offcanvas_cart(array $form, FormStateInterface $form_state){

$response = new AjaxResponse();

// get current order id
$cart_provider = Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
$order_id = $cart->get('order_id')->getString();

// tried this
$cart_block = views_embed_view('commerce_cart_block', 'default',$order_id);
$response->addCommand(new ReplaceCommand('.commerce-cart-block', $cart_block));


// and this
$args = ($order_id);
$view = Views::getView('commerce_cart_block');
if (is_object($view)) {
    $view->setArguments($args);
    $view->setDisplay('default');
    $view->preExecute();
    $view->execute();
    $content = $view->buildRenderable('default', $args);
    $response->addCommand(new ReplaceCommand('.commerce-cart-block', $content));
}

//Alternatively I can reload the whole cart bloc but it is not what i am trying to do
$block = Block::load('cart');
if ($block != null) {
    $cart_block = Drupal::entityTypeManager()
         ->getViewBuilder('block')
         ->view($block);
    $response->addCommand(new ReplaceCommand('.navbar-cart>div', $cart_block));
}

return $response;
}

However it doesn’t work and I get stuck with the following error:

Render #pre_render callbacks must be methods of a class that implements DrupalCoreSecurityTrustedCallbackInterface or be an anonymous function.

I’ve read this post and others but I couldn’t figure out how to properly load the view inside my callback.

Any help is welcome. Thanks

hooks – How to update global variables in plugin activation callback?

Sorry for being such a noob, I’m sure this is an easy question for most. I’m trying to register activation and deactivation hooks for my plugin. In the docs, they warn about the activation callback not having access to global variables:



If you’re using global variables, you may find that the function you pass to register_activation_hook() does not have access to global variables at the point when it is called, even though you state their global scope within the function like this:

The main body variables are therefore in the scope of the activate_plugin() function and are not global, unless you explicitly declare their global scope:

global $myvar;
$myvar = 'whatever';

function myplugin_activate() {

   global $myvar;
   echo $myvar; // this will be 'whatever'
}
register_activation_hook( __FILE__, 'myplugin_activate' );


So, following that advice, I set up my code like this:

global $post_id;
$post_id = 0;

function install_xxx() {
    global $post_id;

    $post = array(
        'post_title'    => __( 'Thank You', 'xxx' ),
        'post_content'  => __( 'Lorem ipsum dolor.', 'xxx' ),
        'post_status'   => 'publish',
        'post_name'     => 'thank-you',
        'post_type'     => 'page'
    );

    $post_id = wp_insert_post( $post, true );
    error_log('Inserted page: ' . $post_id);
}

function uninstall_xxx() {
    global $post_id;
    error_log('Removing page: ' . $post_id);
    $post = wp_delete_post( $post_id, true );
}

register_activation_hook( __FILE__, 'install_xxx' );
register_deactivation_hook( __FILE__, 'uninstall_xxx' );

But in my logs, it will echo something like:

Inserted page: 109

Removing page: 0

And of course, the page isn’t removed.

In other words, the global $post_id isn’t being updated. Any clue what I’m doing wrong?