Extending EntityForm for entity creationfor Drupal 8 , 9 , 10 , and 11

Last updated :  

In Drupal, extending the EntityForm class is a powerful way to create customized interfaces for managing entities. This approach is particularly useful when dealing with custom entity types, allowing developers to tailor form behavior and presentation to meet specific project needs.

Understanding EntityForm

The EntityForm class in Drupal provides a structured framework for building forms that manage entities. This involves not only creating entities but also editing and deleting them, with built-in methods for handling form validation and submission.

Reasons to Extend EntityForm

  • Customization: Create forms that match the exact requirements of your data model and user interactions.
  • Control: Implement custom business logic during validation or submission that ties directly to your entity’s lifecycle.
  • Usability: Improve user interaction through simplified, context-specific forms that enhance the editing experience.

Implementing a Custom EntityForm

To illustrate extending an EntityForm, let’s continue with our previous example of managing a Fruit entity. We'll customize the form to handle specific fields such as name and color, guiding you through building, validating, and submitting this form.

Example: Creating a Fruit Entity

Our Fruit entity will have customizable fields like name and color. Using a custom form, users can input information seamlessly, ensuring our data integrity and business logic are maintained.

Step 1: Create the Entity Definition

If you haven’t already, define the Fruit entity with its properties to lay the groundwork:


// In src/Entity/Fruit.php
namespace Drupal\fruit_module\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Defines the Fruit entity.
 *
 * @ContentEntityType(
 *   id = "fruit",
 *   label = @Translation("Fruit"),
 *   handlers = {
 *     "form" = {
 *       "default" = "Drupal\fruit_module\Form\FruitForm",
 *     }
 *   },
 *   base_table = "fruit",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name"
 *   }
 * )
 */
class Fruit extends ContentEntityBase {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setRequired(TRUE);

    $fields['color'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Color'));

    return $fields;
  }
}

Step 2: Extend the EntityForm

Build a custom form handling class by extending the EntityForm class. This allows you to define custom build, validation, and submission logic for managing the Fruit entity:


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

use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for Fruit entity forms.
 */
class FruitForm extends EntityForm {

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;

    // Add the name field to the form.
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      '#default_value' => $entity->get('name'),
      '#required' => TRUE,
    ];

    // Add the color field to the form.
    $form['color'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Color'),
      '#default_value' => $entity->get('color'),
    ];

    return $form;
  }

  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
    $status = $entity->save();

    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;
    }

    $form_state->setRedirect('entity.fruit.collection');
  }
}

Step 3: Handling User Submissions

Ensure your form’s submission logic is robust, managing entity states and providing feedback upon create or update actions. The save() method in this example commits changes to the database and relays success messages back to the user.

Benefits of Extending EntityForm

  • Facilitates modular, reusable code architecture that enhances maintainability and flexibility.
  • Empowers developers to implement direct business and validation logic within form submissions.
  • Improves user experience by providing contextual interfaces catered to specific editing tasks.

Summary

Extending EntityForm for entity creation in Drupal offers a tailored approach to entity management. By creating custom forms, you ensure that users can cleanly and effectively interact with the data structures necessary for your application’s success. This approach aligns with best practices in module development, encouraging structured, maintainable, and scalable solutions.