agentleFS
edutruledutrul/drupal-ai/.claude/skills/drupal-form-alter/SKILL.md

drupal-form-alter

Skill71 starsChanged 7 months agoMITView on GitHub

Drupal form alter patterns — hook_form_alter, hook_form_FORM_ID_alter, OOP hooks, hiding fields with access, changing required/default values, and adding validate or submit handlers.

The file

Files
SKILL.md

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

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.