Skip to content
TheChatArchiveThe Chat Archive
Googlegemma-3-27b-it· GoogleHugging Face LMArena Human Preference 140K

Write a Drupal 10 module that allows me to save nodes with ajax. Only consider node edit…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    Write a Drupal 10 module that allows me to save nodes with ajax. Only consider node edit forms (not node add forms). Make sure to support moderation state. Just rebuilding and return the form does not work. You need to replace it using Domphp after rendering the entire form in the php (just rendering the moderation state does not work). Also make sure to display all Drupal messages that would normally appear after saving.

  2. Google Assistant

    Okay, this is a complex request, but here's a Drupal 10 module that attempts to fulfill your requirements. It uses AJAX to save node edit forms, handles moderation state, and replaces the form content with the updated form using DOMDocument. It also displays Drupal messages.

    Important Considerations:

    • Complexity: This is a relatively advanced module. It requires a good understanding of Drupal form API, AJAX, DOMDocument, and Drupal's message system.
    • Performance: Replacing the entire form with DOMDocument can be less performant than more targeted AJAX updates. Consider if this is acceptable for your use case. If you have very large forms, you might need to explore alternative approaches.
    • Security: Always sanitize and validate all input data to prevent security vulnerabilities.
    • Testing: Thoroughly test this module in a development environment before deploying it to production.
    • Dependencies: This module relies on the domphp library. You'll need to install it using Composer: composer require drupal/domphp

    Module Structure:

    Create a directory modules/custom/ajax_node_save and within it, the following files:

    1. ajax_node_save.info.yml:

    name: AJAX Node Save
    type: module
    description: Allows saving node edit forms with AJAX.
    core_version_requirement: ^9.4 || ^10
    package: Custom
    dependencies:
      module:
        - node
        - workflow
        - domphp
    

    2. ajax_node_save.module:

    <?php
    
    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\node\Entity\Node;
    use Drupal\workflow\Entity\Workflow;
    use Drupal\domphp\DomDocument;
    
    /**
     * Implements hook_form_alter().
     */
    function ajax_node_save_form_alter(&$form, FormStateInterface $form_state) {
      if (\Drupal::route()->getRouteName() == 'entity.node.edit_form') {
        $form['actions']['submit']['#ajax_processing'] = TRUE;
        $form['actions']['submit']['#after_build'][] = 'ajax_node_save_after_build';
      }
    }
    
    /**
     * After build callback for the submit button.
     */
    function ajax_node_save_after_build(&$element, FormStateInterface $form_state) {
      return [
        '#type' => 'button',
        '#value' => t('Save (AJAX)'),
        '#ajax' => [
          'callback' => 'ajax_node_save_submit',
          'wrapper' => 'node-edit-form-wrapper', // Important:  Use a wrapper for AJAX replacement
          'method' => 'replace',
          'effect' => 'fade',
        ],
      ];
    }
    
    /**
     * AJAX submit callback.
     */
    function ajax_node_save_submit($form, FormStateInterface $form_state) {
      $node = $form_state->getFormObject()->getEntity();
      $node->save();
    
      // Get all Drupal messages.
      $messenger = \Drupal::messenger();
      $messages = $messenger->allMessages();
    
      // Rebuild the form.
      $form = \Drupal::formBuilder()->getForm($node->id());
      $form_state = $form->getFormState();
    
      // Render the form.
      $form_build = \Drupal::service('form_builder')->buildForm($node->id(), $form_state);
      $form_render = \Drupal::service('renderer')->render($form_build);
    
      // Render the messages.
      $message_render = \Drupal::service('renderer')->render($messages);
    
      // Use DOMDocument to replace the form.
      $dom = new DomDocument();
      $dom->loadHTML($form_render);
    
      // Find the form wrapper.
      $wrapper = $dom->getElementById('node-edit-form-wrapper');
    
      if ($wrapper) {
        $wrapper->parentNode->replaceChild($wrapper, $dom->createElement('div', $form_render));
      }
    
      // Add messages to the DOM.
      $message_div = $dom->createElement('div', $message_render);
      $dom->body->appendChild($message_div);
    
      // Return the updated HTML.
      $response = new AjaxResponse();
      $response->addHtml('#node-edit-form-wrapper', $dom->saveHTML());
      return $response;
    }
    

    3. ajax_node_save.theme (Optional, for styling):

    <?php
    
    /**
     * @file
     * Theme file for the AJAX Node Save module.
     */
    

    Explanation:

    1. ajax_node_save.info.yml: Defines the module's metadata. Crucially, it declares dependencies on node, workflow, and domphp.

    2. ajax_node_save.module:

      • hook_form_alter(): This hook modifies the node edit form.
        • It checks if the current route is the node edit form (entity.node.edit_form).
        • It sets '#ajax_processing' => TRUE on the submit button to enable AJAX processing.
        • It adds an after_build callback (ajax_node_save_after_build) to the submit button.
      • ajax_node_save_after_build(): This function replaces the original submit button with a new button that triggers the AJAX callback.
        • It defines the AJAX callback (ajax_node_save_submit).
        • It sets the wrapper to 'node-edit-form-wrapper'. This is essential. The AJAX response will replace the content within this wrapper.
        • It sets the method to 'replace' to replace the wrapper's content.
        • It sets the effect to 'fade' for a visual transition.
      • ajax_node_save_submit(): This is the AJAX callback function.
        • It retrieves the node entity from the form state.
        • It saves the node using $node->save().
        • It retrieves all Drupal messages using \Drupal::messenger()->allMessages().
        • It rebuilds the node edit form using \Drupal::formBuilder()->getForm().
        • It renders the rebuilt form using \Drupal::service('renderer')->render().
        • It renders the messages using \Drupal::service('renderer')->render().
        • It uses DOMDocument to parse the rendered form HTML.
        • It finds the form wrapper element (node-edit-form-wrapper).
        • It replaces the entire form wrapper with the new form HTML.
        • It adds the rendered messages to the DOM.
        • It creates an AjaxResponse object.
        • It adds the updated HTML to the response, targeting the node-edit-form-wrapper.
        • It returns the AjaxResponse.
    3. ajax_node_save.theme: This file is optional. You can use it to add custom CSS or other theme-related code for your module.

    Installation and Usage:

    1. Place the ajax_node_save directory in your modules/custom directory.
    2. Enable the module in the Drupal admin interface (/admin/modules).
    3. Install the domphp library using Composer: composer require drupal/domphp
    4. Clear the Drupal cache (/admin/config/development/performance).
    5. Edit a node. You should see a "Save (AJAX)" button next to the regular "Save" button.
    6. Click "Save (AJAX)". The form should be updated without a full page reload, and any Drupal messages should be displayed.

    Important Notes and Potential Improvements:

    • Wrapper: The node-edit-form-wrapper is crucial. Make sure it exists in your node edit form template. You might need to add it to your theme's node--edit-form.html.twig file:

      <div id="node-edit-form-wrapper">
        {{ form }}
      </div>
      
    • Error Handling: Add error handling to the ajax_node_save_submit() function to gracefully handle cases where the node save fails.

    • Validation: Ensure that the form is properly validated before saving the node. Drupal's form API provides validation mechanisms.

    • Performance: Consider optimizing the DOMDocument manipulation if performance becomes an issue. Targeted AJAX updates (e.g., updating only the moderation state field) would be more efficient.

    • Moderation State: The code should handle moderation state correctly because $node->save() will automatically update the moderation state based on the form's input.

    • Messages: The code retrieves and displays all Drupal messages, including success, warning, and error messages.

    • Security: Always sanitize and validate all input data.

    This module provides a starting point for saving node edit forms with AJAX. You may need to customize it further to meet your specific requirements. Remember to test thoroughly and address any potential security vulnerabilities.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.