Provide original entity in hook_field_attach_validate()

Created on 15 July 2011, over 13 years ago
Updated 17 July 2023, over 1 year ago

Problem/Motivation

hook_field_attach_validate() allows modules to add their own validation for field values. However, the hook is not provided with the original values for the field, which means that in order to validate changes to values, one has to load the entity in the validation hook, something like the following:

 function mymodule_field_attach_validate($entity_type, $entity, &$errors) {
   // Check for a pre-existing entity (i.e., the entity is being updated).      
   list($entity_id, , $bundle) = entity_extract_ids($entity_type, $entity);
   if ($entity_id) {
    // This is gross.
     $orig_entity = entity_load($entity_type, array($entity_id));
     $orig_entity = $orig_entity[$entity_id];
   }
   else {
     $orig_entity = FALSE;
   }

  // Now do stuff.
}

Furthermore, even the above workaround will not work for user profile forms, because the $entity does not even include the uid in that case.

Proposed resolution

Pass the original values to hook_field_attach_validate() in $entity->original.

The orignal values are not directly available in field_attach_validate(), but they were presumably available to that function's caller. The only caller in core is field_attach_form_validate(), which has both new and original values in the form data.

Remaining tasks

Review proposed solution and patch.

Related issues:

User interface changes

None.

API changes

None. (The actual entity is not being altered; only the "pseudo entity" used during validation.)

πŸ“Œ Task
Status

Postponed: needs info

Version

9.5

Component
FieldΒ  β†’

Last updated 5 days ago

Created by

πŸ‡ΊπŸ‡ΈUnited States xjm

Live updates comments and jobs are added and updated live.
  • API addition

    Enhances an existing API or introduces a new subsystem. Depending on the size and impact, possibly backportable to earlier major versions.

  • Needs backport to D7

    After being applied to the 8.x branch, it should be considered for backport to the 7.x branch. Note: This tag should generally remain even after the backport has been written, approved, and committed.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024