I did something like this recently. Since profile uses fields, this make things pretty simple. For the form you could do something like this:
function my_profile_form($form, &$form_state) {
global $user;
if (!isset($form_state['profiles'])) {
$profile = profile2_load_by_user($user, 'profile_machine_name');
if (!$profile) {
$profile = profile_create(array(
'type' => 'profile_machine_name',
'uid' => $user->uid
));
}
$form_state['profiles'][$profile->type] = $profile;
}
// Use field attach form and handle the fields yourself:
field_attach_form('profile2', $profile, $form, $form_state);
// Or use profile2 API which is simpler
profile2_attach_form($form, $form_state);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
Since all the profile form only is the fields that are attached to the profile, you can simply attach the fields yourself to the form, using Drupal core APIs:
field_attach_form
adds the fields to the form.
field_attach_validate
handles validation.
field_attach_submit
to handles adding the values to the entity (profile).
- Lastly you would need to save the profile entity using
profile2_save
.
After browsing the profile2 module code, I found that it provides a wrapper function to attach the fields to the form and save the form. This is simpler, but in doing so, you loose a little control. To use this you need to use the profile2_attach_form
. Doing this will also handle the validation and saving of data.
To use the above code you should be able to c/p it, rename the form and replace profile_machine_name
with the actual machine name of the profile you want to display the form for.