My task is to ajaxify complex flag form (with additional fields).
I need this because the default ajax flag does not dupport fiedls.
I need to have the flagging form for create flag and then update it when flagging has been created.
I want to place custom flagging ajaxified form in my template
First I get form build:
$term = $variables['term'];
$flag = \Drupal::service('flag')->getFlagById('subscribe_term');
$flagging_entity = \Drupal::service('flag')->getFlagging($flag, $variables['term']);
if (!$flagging_entity) {
$flagging_entity = \Drupal::entityTypeManager()->getStorage('flagging')->create([
'uid' => \Drupal::currentUser()->id(),
'session_id' => NULL,
'flag_id' => $flag->id(),
'entity_id' => $term->id(),
'entity_type' => $term->getEntityTypeId(),
'global' => $flag->isGlobal(),
]);
}
$form = \Drupal::entityTypeManager()
->getFormObject('flagging', 'edit')
->setEntity($flagging_entity);
$variables['flag'] = \Drupal::formBuilder()->getForm($form);
The form works ok.
Then I alter the form ad add ajax callback:
$form['actions']['submit']['#ajax'] = [
'callback' => 'mymodule_flag_form_ajax_callback',
'effect' => 'fade',
];
And then in the ajax callback I try to get the same form:
$render_selector = ".flag-form-wrapper";
$response = new AjaxResponse();
$form_object = $form_state->getFormObject();
$flagging_entity = $form_object->getEntity();
$flagged_entity_field = $flagging_entity->get('flagged_entity')->getValue();
if ($flagged_entity_field) {
$tid = $flagged_entity_field[0]['target_id'];
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
if ($term) {
$flag = \Drupal::service('flag')->getFlagById('subscribe_term');
$flagging_entity = \Drupal::service('flag')->getFlagging($flag, $term);
if (!$flagging_entity) {
$flagging_entity = \Drupal::entityTypeManager()->getStorage('flagging')->create([
'uid' => \Drupal::currentUser()->id(),
'session_id' => NULL,
'flag_id' => $flag->id(),
'entity_id' => $term->id(),
'entity_type' => $term->getEntityTypeId(),
'global' => $flag->isGlobal(),
]);
}
$form_new = \Drupal::entityTypeManager()
->getFormObject('flagging', 'edit')
->setEntity($flagging_entity);
$form_build = \Drupal::formBuilder()->getForm($form_new);
$response->addCommand(new HtmlCommand($render_selector, $form_build));
}
}
but I get the following exception: FormAjaxException
So what I am doing wrong and how to refresh the form using ajax?