This project is not covered by Drupal’s security advisory policy.

The Form Alterer module provides OOP plugin functionality to developers for easily altering forms in Drupal 9+. Typically, forms are altered via the hook system (i.e. hook_form_alter) in a module's *.module file. However, this is tedious, overly repetitive, and it really doesn't follow Drupal's new best practices for OOP design. Now, we have a module where we can alter forms via the Drupal Plugin API using an object-oriented approach.

Features

  • Provides a form_alterer_test module to illustrate functionality
  • Provides a new Attribute plugin that is discovered at Drupal\my_module\Plugin\FormAlterer
  • Provides a new YAML plugin that is discovered at my_module.form_alterers.yml
  • Plugins can provide a list of form_ids in the Plugin Definition to alter forms in different contexts
  • Plugins can provide a base form id in the list of form_ids to provide a more general form altering
  • Plugins can provide static_overrides in the Plugin Definition to alter the form(s) statically

Examples

Attribute Plugin

<?php

namespace Drupal\my_module\Plugin\FormAlterer;

use Drupal\Core\Form\FormStateInterface;
use Drupal\form_alterer\Attribute\FormAlterer;
use Drupal\form_alterer\Plugin\FormAlterer\FormAltererPluginBase;

/**
 * The test form_alterer plugin class.
 */
#[FormAlterer(
  id: 'test_form_alter',
  form_ids: [
    'node_page_edit_form',
  ]
)]
class MainContentPageFormAlterer extends FormAltererDefault {

  /**
   * {@inheritDoc}
   */
  public function alterForm(&$form, FormStateInterface $form_state, $form_id) {
    $form['#markup'] = 'Altered!';
  }

YAML Plugins

my_module_taxonomy_term_content_editor:
  label: "Form Alterer: Taxonomy Terms"
  execution_order: 2
  form_ids:
    - taxonomy_term_form
  static_overrides:
    # Show parent relations to admins only
    relations:
      '#access': TRUE
  access_roles:
    - content_editor

my_module_taxonomy_term:
  label: "Form Alterer: Taxonomy Terms"
  form_ids:
    - taxonomy_term_form
  static_overrides:
    # Hide parent relations
    relations:
      '#access': FALSE

my_module_media:
  label: "Form Alterer: Media"
  form_ids:
    - media_form
  static_overrides:
    # Hide the revision information.
    revision_information:
      '#access': FALSE

Supporting this Module

I am actively maintaining this module, but need help with putting in functional php tests.

I can be reached on the following networks to collaborate on this project:

LinkedIn Profile
Drupal Slack Channel

Project information

Releases