How to render a Drupal 7 field in stand alone PHP file? Hi this is probably a really basic question, but hopefully you guys can help me out...

I have a javascript client application (Separate to my main Drupal 7 website) and rather than maintaining a duplicate select list with a large number of values, I would like to use an AJAX call to a PHP file on the Drupal server which will render the HTML for the list I need.

The list is configured as a custom field (Text List type).

Can I create a PHP file in the root of the website, and include the required module files?

An example would be fantastic!

Thanks!
You could definitely bootstrap Drupal in a standalone file, but if you're doing it inside the same document root as the Drupal installation you'd be better off implementing a custom menu path in a module, and using the callback for that path to output the necessary value.

If you print directly from a page callback function and don't return anything, the standard theme wrappers won't be included and you'll just be left with the value you've printed.

A basic example might look like this:

function MYMODULE_menu() {
  $items['custom-path'] = array(
    'title' =&gt; 'Custom page', // Required, won't actually be displayed anywhere
    'access arguments' =&gt; array('access content'), 
    // 'access callback' =&gt; TRUE, // This is an alternative to the access arguments if you don't need any access control for this path
    'page callback' =&gt; 'MYMODULE_ajax_page',
    'type' =&gt; MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_ajax_page() {
  $output = function_to_produce_field_output();

  print $output;
}


After you clear Drupal's caches any request for http://mysite.com/custom-path should produce the un-themed results from your page callback; you can then use that path as your AJAX callback.

You might also want to look at drupal_add_http_header() to set an appropriate content type before you print the output.

As far as getting the field output goes, it's a bit of a pain but this should work:

$entity_type = 'user';
$bundle = 'user';
$field_name = 'field_field_name';

// Get field info for the allowed values
$field_info = field_info_field($field_name);

// Get instance info for label/required/description/default value
$field_instance = field_info_instance($entity_type, $field_name, $bundle);

// Build the select list
$select = array(
  '#type' =&gt; 'select',
  '#value' =&gt; $field_instance['default_value'],
  '#options' =&gt; $field_info['settings']['allowed_values'],
  '#required' =&gt; $field_instance['required']
);

// Build the element wrapper
$wrapper = array(
  '#title' =&gt; t($field_instance['label']),
  '#description' =&gt; t($field_instance['description']),
  '#children' =&gt; theme('select', array('element' =&gt; $select))
);

// Get the fully rendered element
$rendered = theme('form_element', array('element' =&gt; $wrapper));

print $rendered;