Show a form element only to certain roles
Generally when you are hiding fields from user roles there are security implications.

The visibility state functionality you mention just hides things on the front end, which is not secure in terms of stopping users editing fields they are not actualy allowed to use.

If you want to use custom code, you can do this:

/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  // To get the currently logged in user.
  global $user;
  // To target the required form.
  if ($form_id == 'FORM_ID') {
    // Set the role ID of the role that can edit.
    $rid = ROLE_ID_FOR ROLE USER NEEDS TO EDIT;
    // If user doesn't have the role in question.
    if (isset($user-&gt;roles[$rid])) {
      // Deny access to the field.
      $form['FIELD_NAME']['#access'] = FALSE;
    }
  }
}


This is a basic example and you might have to change it to deal with multiple roles having access or something.

This is ok for custom forms or if you only need to control access to a couple of fields but if you want more control or don't want custom code, etc, the best option is the field permissions module.

With that module you can go to the field edit form and select to use custom permissions, after which you can select which roles can access the field.

EDIT
To answer the edit in the question, your code

// If user doesn't have the role in question.
if (isset($user-&gt;roles[$rid])) {


Is doing the opposite of what the comment says it is doing.
To do what the comment says you would want to do this:

// If user doesn't have the role in question.
if (!isset($user-&gt;roles[$rid])) {