There was a method with CCK in Drupal 6 to attach a CCK field in our custom form, like:
$field = content_fields('field_name'); // field_name is cck field
(text_field,text_Area,image_field anything.)
$form['#field_info'][$name] = $field;
$form += content_field_form($form, $form_state, $field);
How can I achieve the same functionality in Drupal 7? I had a form and I want to use the field that I created for a content type. I went through all the files of field.module
but couldn't find anything. There are functions in it like _attach_field
, field_info_Field
and field_info_instance
, but they can't be rendered as a form field.
I like your solution of adding the entire form and unsetting. I am attacking it from another angle-- create a throw-away temporary form and copy in only the field(s) you wish to preserve. Here's what I posted at http://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_form/7#comment-45908:
To add a single field off an arbitrary entity bundle (in this case, an autocomplete nodereference textfield) onto another form, create the form as a temporary form and formstate, and copy in to place that field definition. In my case, I'm working on a Commerce checkout form alter:
function example_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
$tmpform = array();
$tmpform_state = array();
$tmpnode = new stdClass();
$tmpnode->type = 'card';
// Create the temporary form/state by reference
field_attach_form('node', $tmpnode, $tmpform, $tmpform_state);
// Create a new fieldset on the Commerce checkout form
$form['cart_contents']['org_ref_wrap'] = array(
'#type' => 'fieldset',
'#title' => t('Support Organization'),
);
// Place a copy of the new form field within the new fieldset
$form['cart_contents']['org_ref_wrap'][] = $tmpform['field_card_organization'];
// Copy over the $form_state field element as well to avoid Undefined index notices
$form_state['field']['field_card_organization'] = $tmpform_state['field']['field_card_organization'];
..
The advantage to either solution likely depends on the complexity of the "source" form (too complex means a lot of unsets with the form-insert method) and whether the source form will ever receive new fields over time (new fields will show up on your "destination" form in the form-insert method).
Thanks for sharing your solution!
At last got the answer. Here is the Trick to do this.
$node = new stdClass();
$node->type = 'video'; //content type
field_attach_form('node', $node, $form, $form_state);
unset($form['body']); //unset other fields like this.
this will display all the custom fields that are added with field api. so you need to unset any extra fields that you don't want to display in your form. rest will be as IT is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With