profile2_load_by_user Trying to get property of non-object I use simple code to hide field from profile2 main profile based on another field inside the profile2 main profile. If field_testcheckbox is not checked, hide field_info.

function odbornik_fields_form_profile2_edit_main_form_alter(&amp;$form, &amp;$form_state){
global $user;
$profile = profile2_load_by_user($user-&gt;uid, 'main');
$checkbox = $profile-&gt;field_testcheckbox['und'][0]['value'];
  if ($checkbox == 0) {  
     $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden'; 
    };
}


This code works ok for all users browsing their profiles, except admin user browsing own or others profiles, where I get error: Notice: Trying to get property of non-object on line with this code. 

$checkbox = $profile-&gt;field_testcheckbox['und'][0]['value'];


Admin has the main profile as well and the checkbox field is there too. What can be the problem? Thank you.
You are assuming there is a profile for all users and your admin user seems to not have one. Add a check if there is a profile for the current logged in user:

function odbornik_fields_form_profile2_edit_main_form_alter(&amp;$form, &amp;$form_state){
global $user;
$profile = profile2_load_by_user($user-&gt;uid, 'main');
if($profile) {
  $checkbox = $profile-&gt;field_testcheckbox['und'][0]['value'];
    if ($checkbox == 0) {  
       $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden'; 
     }
  }
}