I have loaded a form via ajax and submit by ajax not working. But if I load form directly by url ajax submission is working. Form is loaded by ajax is using jQuery.
$('#button').on('click', function () {
$.ajax({
url: "user_group/edit_ajax/",
success: function (result) {
$(".RblockMain").html(result);
}
});
});
mymodule.routing.yml
mymodule.user_group_edit_ajax:
path: 'user_group/edit_ajax/'
defaults:
_controller: '\Drupal\mymodule\Controller\UserController::user_group_edit_ajax'
requirements:
_permission: 'access content'
UserController
public function user_group_edit_ajax() {
$form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\UsergroupForm');
$body_data = array(
'#theme' => 'usergroup_edit_ajax',
'#usergroup_form' => $form,
);
$message = \Drupal::service('renderer')->render($body_data);
$response = new AjaxResponse($message);
return $response;
}
UsergroupForm.php
class UsergroupForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$form['user_group_name'] = array(
'#type' => 'textfield',
'#title' => '',
'#required' => TRUE,
'#attributes' => array('placeholder' => t('Group Name'),),
'#theme_wrappers' => array(),
);
$form['go'] = [
'#type' => 'button',
'#value' => $this->t('Submit'),
'#attributes' => array('class' => array('btn btn-primary'),),
'#ajax' => [
'callback' => array($this, 'submitForm'),
'event' => 'click',
'progress' => ['type' => 'throbber', 'message' => NULL],
],
];
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$title = $form_state->getValue('user_group_name');
$data = array(
'type' => 'admin_user_group',
'title' => $title,
'uid' => 1,
'status' => TRUE,
);
$usergroup = \Drupal::entityManager()->getStorage('node')->create($data);
$usergroup->save();
$response = new AjaxResponse();
$response->addCommand(new AlertCommand('Submitted successfully'));
return $response;
}
}