0

I am currently trying to display a list of nodes with a custom form containing taxonomy dropdowns (placed above node list) to filter out the contents. Now, on page load all content is displaying well by theming with custom template. Now my form is an Ajax form. After filtering I want to display the result with by using same template just passing the filter array of the node(s). Please find my ajax submit callback code.

Not working. render() works only if I pass nodes by loading node by viewMultiples. is there any way I can use similiar to theme() of drupal 7 like theme('my_content_build_page', $nodes)?

$nodes= Myclass::getNodesByEntityQuery($params);
$build = \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'full');
$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand(
    '.result_message', '<div class="my_top_message">'.render($build).'</div>'
  )
);
return $response;

On page load I am theming

$page_params['content'] = MyClass::getNodesByEntityQuery($params);

$build = [
  '#theme' => 'my_content_build_page',
  '#page_params' => $page_params,
];

Can I reuse the same template in Ajax Callback?

1

The replacement for theme() is a build array with a '#theme' key, as you already have for the page.

In Drupal 8 pass this or the other build array from your question unrendered to an ajax html command, because render() in custom code should be avoided if possible:

$build = [
  '#type' => 'container',
  '#attributes' => [
    'class' => ['my_top_message'],
  ],
];

$build['content'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes, 'full');

$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand('.result_message', $build)
);
return $response;
  • Thank you very much for Your reply. It worked . I just added theme key in build array and $build = [ '#theme' => 'theme_key', '#params' => $nodes, '#attributes' => [ 'class' => ['my_top_message'], ], ]; – Md Eqbal Ahmad Apr 9 at 14:19
1
$build = [
  '#theme' => 'my_theme_key',
  '#page_params'=> $nodes,
  '#attributes' => [
    'class' => ['my_top_message'],
  ],
];

$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand('.result_message', $build)
);
return $response;

Theme hook

function mymodule_theme() {
  return [
  'my_theme_key' => [
     'theme' => 'my_template_file',
     'variables' => ['page_params' => NULL],
    ],
 ];
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.