Show a form element only to certain roles Drupal's form API has a visibility state property that allows you to hide certain Form fields depending on the options selected in earlier forms. 

Is there something similar for User role (e.g. a particular form field will only display if the logged in user has a certain role). 

I know I can hide unwanted form fields according to role via CSS, but I would rather not print out the fields in the first place. I am creating my form inside theme-settings.php

Edit Update:

Here is my code following Rooby's answer:

function legendarysettings_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 == 'system_theme_settings') {
    // Set the role ID of the role that can edit.
    $rid = 3;
    // If user doesn't have the role in question.
    if (isset($user-&gt;roles[$rid])) {
      // Deny access to the field.
      $form['theme_settings']['admin']['#access'] = FALSE;
    }
  }


This works, except it hides the 'admin' field for role 3 (which is the admin role) but shows it to all other roles. I want the admin field to be only visible to the admin role.
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])) {