mcpField
D
drupal-form-alter

drupal-form-alter

github.com/edutrulDevelopment7349 installsUpdated 21w ago
Repository

About drupal-form-alter

A form-alter reference for Drupal developers, covering the object-oriented Hook approach in Drupal 10.3+ and 11. Examples show field adjustments and retrieving a form object and entity.

Key features

  1. 01Use object-oriented Hooks
  2. 02Mark fields as required
  3. 03Set field default values
  4. 04Hide form fields
  5. 05Retrieve form objects and entities

Use cases

  1. 01Change field validation requirements
  2. 02Prepopulate fields with defaults
  3. 03Hide internal fields when needed

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/edutrul/drupal-ai --skill drupal-form-alter

After installing, type/drupal-form-alterin Claude Code to confirm it loaded.

Bundled filesREADME.md

Details

From the project README

Drupal Form Alter

OOP Hook (Drupal 10.3+ / 11)

// src/Hook/MyModuleHooks.php
namespace Drupal\my_module\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Form\FormStateInterface;

final class MyModuleHooks {

  #[Hook('form_alter')]
  public function formAlter(array &$form, FormStateInterface $form_state, string $form_id): void {
    if ($form_id === 'node_article_form' || $form_id === 'node_article_edit_form') {
      // Alter the article node form.
      $form['title']['#description'] = t('Enter a descriptive title.');
    }
  }

  // Target a specific form more efficiently
  #[Hook('form_node_article_form_alter')]
  public function formNodeArticleFormAlter(array &$form, FormStateInterface $form_state): void {
    $form['#validate'][] = [MyModuleHooks::class, 'validateArticleForm'];
    $form['actions']['submit']['#submit'][] = [MyModuleHooks::class, 'submitArticleForm'];
  }

}

Common Alterations

// Make a field required
$form['field_subtitle']['widget'][0]['value']['#required'] = TRUE;

// Add a field default value
$form['field_subtitle']['widget'][0]['value']['#default_value'] = 'Default';

// Hide a field
$form['field_internal']['#access'] = FALSE;

// Add a CSS class
$form['#attributes']['class'][] = 'my-custom-form';

// Change submit button label
$form['actions']['submit']['#value'] = t('Save Article');

// Add a custom submit handler (runs AFTER default)
$form['actions']['submit']['#submit'][] = '::mySubmitHandler';

// Prepend a custom validate handler
array_unshift($form['#validate'], '::myValidateHandler');

Get Form Object

$form_object = $form_state->getFormObject();
if ($form_object instanceof NodeForm) {
  $node = $form_object->getEntity();
}

Comments

Markdown supported