1

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 \Drupal\Core\Security\TrustedCallbackInterface 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

1
  • It doesn't matter where you render this #pre_render callback, it will always throw this error until you fix it. This is not an Ajax issue. – 4k4 Apr 27 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.