Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By nakeddesign on
I'm having trouble using form_set_error with profile2 fields.
I have a First name and Second name profile2 fields added to my register form. These come through as:
$form_state['values']['profile_public']['und'][0]['value'] and appear on the page as:
<input class="text-full form-text" type="text" id="edit-profile-public-field-first-name-und-0-value" name="profile_public[field_first_name][und][0][value]" value="name 3" size="60" maxlength="50">
form_set_error doesn't seem to be able to target these fields using the following code:
function mymodule_user_form_user_register_form_validate($form, &$form_state) {
// Create a temporary profile2 container so we can validate our fields without $language.
// This is a belt and braces approach - TODO: Explore more elegant way to check entity fields within $form_state['values'] without $language.
$profile2 = profile_create(array('type' => 'public', 'uid' => 0));
$profile2->field_first_name = $form_state['values']['profile_public']['field_first_name'];
$profile2->field_second_name = $form_state['values']['profile_public']['field_second_name'];
// Now we can get the values without knowing the language code.
$field_first_name = field_get_items('profile2', $profile2, 'field_first_name');
$field_second_name = field_get_items('profile2', $profile2, 'field_second_name');
if(!$field_first_name[0]['value']) {
form_set_error('profile_public[field_first_name][und][0][value', 'Please enter your first name.');
}
if (!$field_second_name[0]['value']) {
form_set_error('profile_public[field_second_name][und][0][value', 'Please enter your second name.');
}
}
Has anyone found a workaround or am I missing something maybe?
Comments
Here is the solution I found.
Here is the solution I found.
Thank you.