'Drupal 9 : Ajax process to display an entity form in a popup
I need help I am new in Drupal 9 Ajax development. I have developed a piece of code but it doesn't work.
To sumarise, I want to display an entity form in a popup. The popup is built dynamically with jQuery, I use Ajax to fill the popup and the form is built in an ajax command (the code is : \Drupal::service('entity.form_builder')->getForm($livraison, 'edit');)
The form is well displayed but I think I miss something in ajax developpement because when I submit the form, the entity is not saved. When I look at the javascript console log, I see 3 others command responses plus the command I have created in server side (modifLivraison).
result: Array(4) [ {…}, {…}, {…}, {…} ]
0: Object { command: "settings", settings: {…}, merge: true }
1: Object { command: "insert", method: "prepend", selector: "head", … }
2: Object { command: "insert", method: "append", selector: "body", … }
3: Object { command: "modifLivraison", modif: "...
I think that the Entity form needs some javascript and that's why these 3 commands have been added. I don't know if my ajax process is correct. Here my code : In the command class:
class ModifLivraisonCommand implements CommandInterface
{ protected livraisonId; ...
/**
* Implements Drupal\Core\Ajax\CommandInterface:render().
*/
public function render()
{
...
$entitytype_manager = \Drupal::service('entity_type.manager');
$storage = $entitytype_manager->getStorage('livraison');
$livraison = $storage->load($this->livraisonId);
...
$livraison_form = \Drupal::service('entity.form_builder')->getForm($livraison, 'edit');
$livraison_form['#cache']['max-age'] =0;
$output = \Drupal::service('renderer')->render($livraison_form);
return [
'command' => 'modifLivraison',
'modif' => $output
];
...
The controller :
public function modifLivraison($livraison) {
$response = new AjaxResponse();
$response->addCommand(new ModifLivraisonCommand($livraison));
return $response;
}
and the javascript in the client side :
create_popup('0,0,0,0')
...
jQuery.ajax('/livraisons/modif-livraison/' + livraison, {
success: function(result,textStatus, jqXHR) {
jQuery(".spinner").remove();
console.log(result);
var ajax;
Drupal.AjaxCommands.prototype.settings(ajax,result[0],200)
jQuery(result[1].selector)[result[1].method](result[1].data);
jQuery(result[2].selector)[result[2].method](result[2].data);
...
jQuery("#modif_livraison").append(result[3].modif);
...
}
})
I think the error is in the way of ajax calling of the url (jQuery.ajax('/livraisons/modif-livraison/' + livraison ...)
My problem is the entity is not saved when the form is submitted. What's wrong ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
