在Drupal 7中将CCK字段添加到自定义表单

时间:2012-10-12 07:42:01

标签: drupal drupal-7 cck

在Drupal 6中有一个使用CCK的方法在我们的自定义表单中附加CCK字段,例如:

$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);

如何在Drupal 7中实现相同的功能?我有一个表单,我想使用我为内容类型创建的字段。我查看了field.module的所有文件但找不到任何内容。其中包含_attach_fieldfield_info_Fieldfield_info_instance等功能,但无法将其呈现为表单字段。

2 个答案:

答案 0 :(得分:2)

终于得到了答案。这是做这件事的伎俩。

$node = new stdClass();
$node->type = 'video'; //content type
field_attach_form('node', $node, $form, $form_state);
unset($form['body']); //unset other fields like this.

这将显示使用字段api添加的所有自定义字段。所以你需要取消设置你不希望在表单中显示的任何额外字段。休息将与IT一样。

答案 1 :(得分:2)

我喜欢你添加整个表单和取消设置的解决方案。我从另一个角度攻击它 - 创建一个丢弃的临时表单并仅复制您想要保留的字段。这是我在http://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_form/7#comment-45908发布的内容:

要将任意实体包(在本例中为自动完成节点引用文本字段)中的单个字段添加到另一个表单上,请将表单创建为临时表单和formstate,然后复制以放置该字段定义。就我而言,我正在制作一个商业结账表格:

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'];

  ..

任何一种解决方案的优势可能取决于“源”形式的复杂性(过于复杂意味着使用表单插入方法进行大量取消)以及源表单是否会随着时间推移接收新字段(新字段将在表单插入方法中显示在“目标”表单上。

感谢您分享您的解决方案!