Saving entities in submitForm()for Drupal 8 , 9 , 10 , and 11

Last updated :  

In the journey of building custom forms in Drupal, mastering the submitForm() method is key. This method handles the saving of data entered into your forms, transforming user input into structured entities that are stored and managed within the system.

Understanding submitForm()

The submitForm() method is where you define what happens after a form is submitted and passes all validations. In this phase, you typically save data to the database, confirm actions with the user, or redirect them to a new page.

The Lifecycle of Form Submission

Form submission involves several key stages: input validation, data processing, and saving entities. We'll explore these stages with a focus on effectively implementing submitForm() using the example of the Fruit entity discussed in previous lessons.

Example: Saving a Fruit Entity

Let's explore how to save a Fruit entity after validating the details such as name and color, which we previously set up.

Step-by-Step Guide to Implementing submitForm()

Step 1: Accessing Form Values

Within submitForm(), access the values submitted through the form. This involves pulling data from the $form_state to update or create entities.


// In src/Form/FruitEditForm.php
namespace Drupal\fruit_module\Form;

use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for the Fruit entity edit forms.
 */
class FruitEditForm extends FruitForm {

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the current entity.
    $entity = $this->entity;

    // Set values on the entity from the form state.
    $entity->set('name', $form_state->getValue('name'));
    $entity->set('color', $form_state->getValue('color'));

    // Save the entity.
    $status = $entity->save();

    // Provide feedback to the user based on the operation.
    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this->t('Created the %label Fruit.', ['%label' => $entity->label()]));
        break;

      case SAVED_UPDATED:
        drupal_set_message($this->t('Updated the %label Fruit.', ['%label' => $entity->label()]));
        break;
    }

    // Redirect to the fruit collection page.
    $form_state->setRedirect('entity.fruit.collection');
  }
}

Step 2: Saving the Entity

Use the entity's save() method to commit the changes to the database. This is a crucial step in ensuring that user data persists as intended. Catch exceptions if necessary to handle errors gracefully and inform users with meaningful messages.

Step 3: Providing User Feedback

After saving, it's important to confirm the action with the user. Using Drupal's message system, you can display messages that reassure users of their action’s success, or prompt them if any issues occurred during the save process.

Considerations for a Robust saveForm Implementation

  • Implement error handling to manage scenarios where the save operation fails.
  • Consider entity revisions if you need an audit trail of changes.
  • Ensure user permissions are respected, especially in multi-user environments where entity access must be controlled.

Summary

Implementing submitForm() is an essential skill in Drupal module development, enabling you to handle user inputs with precision and ensure their proper storage as entities. By understanding how to save entities effectively, you maintain data consistency and enhance overall system reliability.

Teaser for the Next Lesson

In our next lesson, we’ll discuss using form modes for entity forms, which allow for even greater flexibility and customization in displaying and handling forms. Stay tuned to learn how you can leverage form modes to enhance your Drupal applications!