I use the code snippet from: render a drupal 8 entity in a string
$node = \Drupal::entityManager()->getStorage('node')->load($nodeid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$renderarray = $view_builder->view($node, 'full');
$html = \Drupal::service('renderer')->renderRoot($renderarray);
It works in a normal controller class without problems. But I did not get it to work in an Ajax Callback in a Custom Form.
The $html = \Drupal::service('renderer')->renderPlain($build); returns nothing.
Where ist the problem? Here is the reduced code of my test form:
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class SearchApiPageBlockForm extends FormBase {
public function getFormId() {
return 'search_api_page_block_form';
}
public function buildForm(array $form, FormStateInterface $form_state, $args = array()) {
$form['form']['actions'] = array('#type' => 'actions',);
$form['form']['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('TESTBUTTON!'),
'#ajax' => array(
'callback' => '::myAjaxCallback',
),
);
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('comment');
$storage = \Drupal::entityTypeManager()->getStorage('comment');
$node = $storage->load(103); //cid 103 already exists
$build = $view_builder->view($node);
dpm('before rendering'); // -> dpm output is: 'before rendering'
$html = \Drupal::service('renderer')->renderPlain($build);
dpm($html);// -> dpm has no output
dpm('after rendering');// -> dpm has no output
}
}
My goal is, to return the html of an entity via the
$response->addCommand(new HtmlCommand('#testtmp_message', $output));
UPDATE: Content of build: dpm(build)
$response->addCommand(new HtmlCommand('#testtmp_message', $build));