Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Last active August 29, 2015 14:26
Show Gist options
  • Save JeffTomlinson/b0a8cd6c64c2397e52ed to your computer and use it in GitHub Desktop.
Save JeffTomlinson/b0a8cd6c64c2397e52ed to your computer and use it in GitHub Desktop.
Extract Drupal 7 form API elements from and existing entity form
/**
* Extracts a form API element from and existing entity form.
*
* @param string $field_name
* The field name of the element to extract.
* @param string $form_id
* The form ID of the entity form from which to extract the element.
* @param string $entity_type
* The entity type fo the entity form.
* @param string $bundle_name
* The bundle name within the entity from which to extract the element.
* @param object $entity
* The entity from which the defaults will be derived.
* @param string $langcode
* The language code that should be used for the element extraction.
*
* @return array
* A form API render array for the extracted element.
*/
function example_entity_form_extract_element($field_name, $form_id, $entity_type, $bundle_name, $entity = NULL, $langcode = LANGUAGE_NONE) {
$form = array(
'#parents' => array(),
);
$form_state = array(
'build_info' => array(
'form_id' => $form_id,
),
);
// Get default values for field if available.
if (!empty($entity)) {
$items = field_get_items($entity_type, $entity, $field_name);
}
else {
$items = array();
}
// Get field and field instance information.
$field = field_info_field($field_name);
$instance = field_info_instance($entity_type, $field_name, $bundle_name);
// Get the form element.
$element = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
return $element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment