Add CCK field to custom form in Drupal 7

℡╲_俬逩灬. 提交于 2019-12-05 11:31:13

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!