Direkt zum Inhalt

Devbits

Kleine Code-Schnipsel aus unserem Alltag mit Drupal, PHP und DevOps: Problem, Lösung, Code.

23.10.2026 | Lothar Ferreira Neumann

How to fill empty form fields via a custom Drupal AJAX command

In many editor or form workflows fields need to be prefilled (for example based on a selected entity or computed data) without overwriting input the user may have already entered.

<?php

declare(strict_types=1);

namespace Drupal\my_module\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * Ajax command: fill empty form elements with a predefined value.
 *
 * This command targets one or more form elements via a CSS selector and sets
 * their value only if the current value is empty (after trimming).
 *
 * The command also triggers `input` and `change` events so Drupal behaviors and
 * other listeners react as if the user entered the value manually.
 */
final class SetValueIfEmptyCommand implements CommandInterface {

  /**
   * The Ajax command name used by Drupal.AjaxCommands.
   */
  public const COMMAND = 'setValueIfEmpty';

  /**
   * Default selector used when none is provided.
   */
  public const DEFAULT_SELECTOR = '[data-my-fill-target]';

  /**
   * Creates a command instance.
   *
   * @param string $fillValue
   *   The value to set when the target element is empty.
   * @param string|null $targetSelector
   *   CSS selector for the target elements. If omitted, DEFAULT_SELECTOR is used.
   */
  public function __construct(
    protected string $fillValue,
    protected ?string $targetSelector = null,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function render(): array {
    return [
      'command' => self::COMMAND,
      'selector' => $this->targetSelector ?? self::DEFAULT_SELECTOR,
      'value' => $this->fillValue,
    ];
  }

}
/**
 * @file Field empty check.
 */
(function (Drupal) {
  'use strict';

  Drupal.AjaxCommands.prototype.setValueIfEmpty = function (ajax, response) {
    const targetSelector = response && response.selector ? response.selector : '';
    const fillValue = response && typeof response.value === 'string' ? response.value : '';

    if (!targetSelector) {
      return;
    }

    const elements = document.querySelectorAll(targetSelector);
    for (const element of elements) {
      let currentValue = '';

      if (typeof element.value === 'string') {
        currentValue = element.value.trim();
      }
      else if (element.isContentEditable) {
        currentValue = (element.textContent || '').trim();
      }

      if (currentValue !== '') {
        continue;
      }

      if (typeof element.value === 'string') {
        element.value = fillValue;
      }
      else if (element.isContentEditable) {
        element.textContent = fillValue;
      }
      else {
        continue;
      }

      element.dispatchEvent(new Event('input', { bubbles: true }));
      element.dispatchEvent(new Event('change', { bubbles: true }));
    }
  };

})(Drupal);
set_value_if_empty:
  js:
    js/set_value_if_empty.js: {}
  dependencies:
    - core/drupal
    - core/drupal.ajax
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\my_module\Ajax\SetValueIfEmptyCommand;

$response = new AjaxResponse();

// Example: fill a media name field if it's empty.
$fill_value = 'foo-bar';

// Selector for a specific element in this use-case.
$target_selector = '[data-drupal-selector$="my_field"]';

$response->addAttachments([
  'library' => [
    'my_module/set_value_if_empty',
  ],
]);

$response->addCommand(new SetValueIfEmptyCommand($fill_value, $target_selector));

return $response;

Issue

In many editor or form workflows fields need to be prefilled (for example based on a selected entity or computed data) without overwriting input the user may have already entered.

Built-in AJAX setters such as InvokeCommand('val') always assign values unconditionally. When an AJAX update happens after the user started typing, this can unintentionally replace user-provided content.

Prerequisites

This approach only works when executed within an AJAX callback returning an AjaxResponse.

Solution

Use a lightweight custom AJAX command that runs in the browser and checks the current value of the target element(s).
The command sets the provided value only if the field is empty (after trimming).

The server supplies the selector and value while the client performs the final emptiness check and applies the update conditionally, preventing accidental overwrites of user input.

12.02.2026 | Michael Ebert

Get value of an entity field

You often need to access a value of a field within a Drupal entity programmatically, but you may encounter challenges in doing so due to the complexity of Drupal's data structure.

// For single value fields.
$entity->field_name->value;

// If you don`t know the main property.
$main_property_name = $entity->field_name->getMainPropertyName();

// For multiple value fields.
$entity->field_name->getValue();

Issue:

You often need to access a value of a field within a Drupal entity programmatically, but you may encounter challenges in doing so due to the complexity of Drupal's data structure.

Solution:

$entity->field_myfield->value

  • Direct Access: This approach directly accesses the value property of the field item.
  • Single Value: This is typically used when you are certain that the field holds a single value (e.g., a single text value, a single number, etc.). This is common with fields that are configured to store only one value.
  • Simplicity: It provides a simple and straightforward way to get the value if the field only holds one item.
  • Assumptions: It assumes that the field item exists and that the value property is the correct way to access the field data.

$entity->field_myfield->getMainPropertyName()

  • Main Property of the Field: getMainPropertyName() returns the main property of a field. For most fields, this is the value property, but it can also be another property depending on the field type. For example, for a reference field, the main property might be target_id.
  • Field Data Model: Each field in Drupal has a data model that can contains various properties. The main property is considered the primary piece of information for the field.
  • Usage in Entities: This method is useful when you want to use the field in a general context without knowing exactly which specific property represents the main information.

$entity->field_myfield->getValue()

  • Method Access: This approach uses the getValue() method to retrieve the field's value.
  • Array of Values: getValue() returns an array of all the field values. This is useful for fields that can hold multiple values (e.g., multiple text values, multiple references, etc.).
  • Structured Data: The returned array provides more structure and includes potentially other properties of the field items, not just the value property. For example, an image field might return an array with target_id, alt, title, etc.
  • Flexibility: This method is more flexible and can be used for both single and multi-value fields. You will need to handle the array appropriately in your code.

Conclusion:

  • Use $entity->field_myfield->value if you are dealing with a single-value field and want a straightforward, direct access to the field value.
  • Use $entity->field_myfield->getMainPropertyName() if you want to determine the main property of the field in a general way without knowing the specific field type.
  • Use $entity->field_myfield->getValue() if you need to handle multiple values or require the complete array structure of the field data, providing more flexibility and additional information.

12.12.2025 | Michael Ebert

Render field with given formatter type programmatically

You want to print out a field in a given formatter type.

$field_render_array = $entity->{$field_name}->view([
  'type' => 'default_formatter', // Replace with desired formatter type.
  'label' => 'hidden', // If you want to hide the label of the field (optional).
  'settings' => [
    'trim_length' => 100, // Example for textfields: Trim the text to 100 characters.
  ],
]);

Issue:

You want to print out a field in a given formatter type.

Solution:

An easy way would be to use the configuration on the view display of your entity and select the wanted field formatter there. But in some cases (e.g. you don't want to render the field on the node where it is defined) this does not work.

This snippet shows you how to do it programmatically (for example in a preprocess hook). 

As fields themselves do not have a `view()` method, we need to manipulate the render array of a field item list you get when loading an entity.