Coming from #1886852: Geofield: Empty values on widgets with default values skip validation, I've noticed an odd field behavior that I'm not sure is intended. How to replicate.

  1. Create a new text field on an entity, give it any default value, allow for empty values.
  2. Add a new entity, clear out the default value for the new field and give it an empty value.
  3. Save the entity. What should happen here is that the field should have no value, but instead it has the default value.

When you go back and edit the entity, clearing out the field works as expected. This behavior happens both in the latest version of D7 (7.18) and a reasonably recent version of D8-dev (Last commit 704fe8db02c0b45fd9ed1043150f16cc2a5545f2, December 27).

In D7, the code that I think causes the issue is in the field module (field.default.inc).

/**
 * Default field 'insert' operation.
 *
 * Insert default value if no $entity->$field_name entry was provided.
 * This can happen with programmatic saves, or on form-based creation where
 * the current user doesn't have 'edit' permission for the field.
 */
function field_default_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // _field_invoke() populates $items with an empty array if the $entity has no
  // entry for the field, so we check on the $entity itself.
  // We also check that the current field translation is actually defined before
  // assigning it a default value. This way we ensure that only the intended
  // languages get a default value. Otherwise we could have default values for
  // not yet open languages.
  if (empty($entity) || !property_exists($entity, $field['field_name']) ||
    (isset($entity->{$field['field_name']}[$langcode]) && count($entity->{$field['field_name']}[$langcode]) == 0)) {
    $items = field_get_default_value($entity_type, $entity, $field, $instance, $langcode);
  }
}

It seems like we should check if the field is empty by the field module's implementation of hook_field_is_empty here, but I'm not 100% sure what that would look like in code. I suspect that the code looks the same in D8, but I wasn't 100% sure where to look for it in the new D8 file structure. As soon as I find it, I'll post a comment.

Comments

swentel’s picture