How can I access fields values inside profile2 main profile? Only on edit main profile page? I try to hide a field on profile2 edit page based on another value. Code is from my template.php

function my_theme_form_profile2_edit_main_form_alter

and then calling

global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = $profile->field_checkbox_admin1['und'][0]['value'];

The problem is that profile variable is not accessible if all of the fields in profile are empty. dpm($profile) shows nothing and I get undefined variable error.

1 Answer 1


Just define the variable already before using it

$profile ="";
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = isseet($profile->field_checkbox_admin1['und'][0]['value']) ?      $profile->field_checkbox_admin1['und'][0]['value'] : "";

That is nature the profile 2 module, it doesn't create any entry for any field in the database untill it is not assigned any value actually. So it returns nothing if it is empty.

Hope it will help

  • There is no point in declaring the $profile variable before the call the profile2_load_by_user. It will be overwritten no matter what. What is missing is a test to see what was returned after the call and before making assumptions on how to use it. Commented Aug 8, 2014 at 8:09
  • @J.Reynolds How do you otherwise propose to check a value of a field inside an empty profile2 profile? I am hiding a field based on a field in same profile on same profile page. I need to get to the value first to be able to compare. If empty then hide field.
    – loparr
    Commented Aug 8, 2014 at 10:09
  • @loparr If you are checking values on the profile page, then you are better off just inspecting $form and $form_state. You say you want to hide a field on profile2 edit page based on another value. Is this 'another value' present as a field value on the same profile page? If so $form and $form_state is what you are looking at. Commented Aug 8, 2014 at 10:52
  • @J.Reynolds Defining $profile was just to avoid undefined variable error if you are using it further. Otherwise we can have many options to get the data. Also the options proposed by you is also good. Commented Aug 8, 2014 at 11:56
  • @J.Reynolds Yes, I want to control visibility of fields based on values of checkbox in the same form - so values are 0 or 1. So you say there is no need to load profile? Looking at dpm($form) I could see there are my fields but how to access boolean data? devel shows ['profile_main']['field_checkbox_admin1']['und']['#value_key']. Should I do something like $check = ['profile_main']['field_checkbox_admin1']['und']['#value_key']? Thank you
    – loparr
    Commented Aug 8, 2014 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.