Problem/Motivation

  • When updating an existing user's data, the uid for the user is not available in hook_field_attach_validate().
  • The issue originates in entity_form_field_validate(), which passes on a "pseudo-entity" generated from the form values:
      $pseudo_entity = (object) $form_state['values'];
      field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
    
  • Most fieldable core entities include the entity id in the form values. (See, for example, node_form().) Therefore, the $pseudo_entity includes the id as expected in those cases.
  • However, user_profile_form() does not use this pattern. It instead stores the entity data to $form_state['user'], which is not available in the field attach hooks.

Proposed resolution

Standardize entity CRUD forms. Or, at a minimum, provide the full, complete entity in a consistent place in $form_state, and use this somehow in entity_form_field_validate().

The workaround for this issue is to look up the user by name in hook_field_attach_validate():

 function mymodule_access_field_attach_validate($entity_type, $entity, &$errors) {                            
   if ($entity_type == 'user') {
     if ($account = user_load_by_name($entity->name)) {
       $entity->uid = $account->uid;
     }
   }

Remaining tasks

TBD

Related issues:

User interface changes

None.

API changes

TBD

Comments

xjm’s picture

xjm’s picture

Issue summary: View changes

Updated issue summary.

xjm’s picture

Issue summary: View changes

Updated issue summary.

sun’s picture

I think this should be fixed in a generic way in #1220212: Provide original entity in hook_field_attach_validate()

We can keep this issue to specifically add

  $form['uid'] = array(
    '#type' => 'value',
    '#value' => $account->uid,
  );

to user_profile_form()

sun’s picture

Issue summary: View changes

Updated issue summary.

berdir’s picture

Version: 8.x-dev » 7.x-dev

No longer an issue in 8.x, so moving to 7.x

drikc’s picture

The workaround in the issue summary which use user_load_by_name($entity->name) to retrieve the missing uid works only if the username isn't modified. The following workaround use the solution mentioned in comment #2:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_user_profile_form_alter(&$form, &$form_state, $form_id) {

  // Add uid here so that is appear in hook_field_attach_validate() $entity argument.
  $form['uid'] = array(
    '#type' => 'value',
    '#value' => $form_state['user']->uid,
  );
}

Status: Active » Closed (outdated)

Automatically closed because Drupal 7 security and bugfix support has ended as of 5 January 2025. If the issue verifiably applies to later versions, please reopen with details and update the version.