0

Looking at https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x because I haven't seen a page updated for Drupal 8, it seems like only a select few form elements are allowed to have #ajax on them. Isn't this too limiting? I want to do Ajax on a markup element. There are a lot of scenarios in which I would want to do Ajax with my own custom HTML, but I don't want to lose the functionality of the Form API, like getting the $form and $form_state.

The way I see it, there are two ways of doing Ajax in Drupal, either normally by just calling a controller, or by using an element in the Form API with an Ajax callback. If I do Ajax normally, I can create data in Javascript however I want and send it to php, but I can't get the data in Drupal's $form object or call some of Drupal's special Ajax functions like entity autocomplete. If I use the Form API, I lose the ability to respond to any events on certain elements of the form.

Why is it like this? And, is there a way to get around it without modifying core?

1 Answer 1

0

In Drupal 8 render elements are plugins and you can define a custom render element in a module without modifying core.

The scenarios you describe probably don't need a custom render element. A #markup with an event attached to it is like a link or a button, where you remove the styling with css.

Additionally you can hook into ajax js and react on events with your own javascript. See ajax.js, the hooks are called prototypes.

4
  • None of this seems to address my primary concern, which is, if I construct data with logic in Javascript, and want to send that to php via Ajax, is that possible? I looked in core and found an example of Drupal.AjaxCommands.prototype and it looks like the Ajax command that allows you to do your own javascript is triggered by php, which means I've already passed the point where I should have grabbed my data from the original javascript. Does that make sense? Drupal Ajax seems to be grabbing the form data, but I need to grab data I've created in JS. Commented May 26, 2016 at 20:34
  • To answer your question, I have data in javascript, how I send it to php via Ajax? Send a post request with your js data to drupal, define a controller with a route, which sends back a symfony response. Client side this is standard jquery ajax, drupal part is a simple controller.
    – 4uk4
    Commented May 26, 2016 at 21:31
  • I'm already doing this, but that's what led me to my first problem, I don't know how to get the $form and $form_state objects by doing it this way. Commented May 26, 2016 at 22:07
  • The only way I know how to transfer js generated data in a form is the hidden element.
    – 4uk4
    Commented May 26, 2016 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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