Get the renderable array for a single field instance
I’m building an interface to simplify the user experience during content creation. Users select options in three <select>
fields, then on submit, they are forwarded to the correct content type add node form for the options selected. Some of the values from the original form will be be pre-filled in the new node add form.
To create this new form, I need fields from the content types and user profile. Given a content type, field name, and field instance, this is the code you need to get the Form API renderable array for the field.
/*
* Gets the renderable array for the specified field. Call from a form function.
*
* @param $entity
* The type of data. Often 'node' or 'user'.
* @param $bundle
* The entity group type. For nodes, this is the content type.
* @param $field_name
* The field name of the field to render
* @param $form
* The form to place the field in
* @param $form_state
* The form state
*
*/
function {site_customization_module}_get_form_field($entity, $bundle, $field_name, &$form, &$form_state) {
// field_default_form() needs this.
$form['#parents'] = array();
$field = field_info_field($field_name);
$ct_instances = field_info_instances($entity, $bundle);
$instance = $ct_instances[$field_name];
//See field_ui_default_value_widget() for original use.
$items = $instance['default_value'];
$addition = field_default_form(NULL, NULL, $field, $instance, LANGUAGE_NONE, $items, $form, $form_state);
$form += $addition;
}
Comments
(Statically copied from previous site)
Gerrit replied on June 14, 2012 - 2:00pm
Awesome snippet! Thanks!
Chris replied on October 16, 2012 - 6:54am
Thank you so much! I’ve got sort of the same problem here and you saved me countless hours!
Charlie replied on January 21, 2013 - 3:14pm
Your code saved me, but I think there’s an issue – $form[’#parents’] should be an array, not an empty string (even if it’s an empty array!). This ensures #ajax will work properly if any fields use it (such as “Add another” or managed file fields. So:
$form[’#parents’] = array();
brad replied on January 24, 2013 - 5:50pm PERMALINK
Ah! Yes. Here is the API reference: http://api.drupal.org/api/drupal/developer%21topics%21forms_api_referenc… I’ve updated the example. Thanks!
Anonymous replied on March 11, 2016 - 2:27am PERMALINK
This is really great. A lot easier than making a custom form from scratch.
Thanks
ssvargass replied on March 29, 2016 - 12:24pm PERMALINK
This solution is working fine for me, thanks!