3

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;
}
    }
3
  • What is the correct way to load form using ajax? – Haris Apr 4 '17 at 7:19
  • Are you getting any errors when you submit the form? – edwardchiapet Apr 4 '17 at 13:53
  • It is going to not found page. It is going to unknown action url coming with url – Haris Apr 4 '17 at 15:49
3

I had the exact same issue:

When the form was on its own page, ajax submit works.

When the form was loaded through ajax, ajax submit didn't work, submit was redirecting the form to its own page.

After unsuccessfully restarting from scratch twice, I tried to implement this ajax modal example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8/

Success one.

Then removing the openModalCommand to simply display the form on the page.

Success two.

I compared both my unsuccessful attempts and the successful one. There was one difference, in the success one, in the controller the form was built but not rendered.

// Controller to load the form through ajax
public function ajaxSupportTicket() {
    $form = \Drupal::formBuilder()->getForm('Drupal\itportal_support\Form\SupportTicketForm');
    $ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

    // Append the form in the page.
    // The form is sent as is, not rendered
    $ajax_response->addCommand(new \Drupal\Core\Ajax\AppendCommand('#selector', $form));


    return $ajax_response;
}

Now that this works, the whole ajax api of D8 seems very powerful.

Also, try to get rid of your custom javascript to load the form. It can be done using render array. Place a link with use-ajax class.

$output['open_form'] = [
  '#type' => 'link',
  '#title' => $this->t('Open Form'),
  '#url' => Url::fromRoute('mymodule.ajax_form_controller'),
  '#attributes' => [
    'class' => [
      'button',
      'use-ajax',
    ],
  ],
];

// Attach the library for pop-up dialogs/modals.
// drupal.dialog.ajax might be overkill, but I didn't took time to improve
// comments about it are welcome
$output['#attached']['library'][] = 'core/drupal.dialog.ajax';

Hopefully, it can help.

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.