在Drupal7中定义并使用其他节点类型的字段作为我的表单元素类型



我正在开发Drupal 7的模块。我定义了一个名为"Booth"的节点类型。现在,在我的模块中,我创建了一个表单,其中包含一些字段,如姓名、电话、地址等。其中一个字段是Booth,它是一个Select类型元素。我想把展位标题(我在"添加内容>展位"中添加的)作为我的选择元素选项。我该怎么做?如何使用展位内容类型的标题字段填充选项数组?[请看下图]

第一个字段必须填写展位名称的标题

$form['exbooth'] = array(
    '#type' => 'select',
    '#title' => t('Exhibition Booth'),
    '#options' => array(), // I want to fill this array with title fields of booth content type
    '#required' => TRUE,
);
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
);
$form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#required' => TRUE,

在drupal API中进行了一些挖掘之后,我终于找到了解决方案。

我使用entity_load()函数检索"展台"内容类型的所有节点,然后将结果的标题放在一个数组中,并为Select选项设置该数组:

$entities = entity_load('node');
$booths = array();
foreach($entities as $entity) {
    if($entity->type == 'booth') {
        $i = 1;
        $booths[$i] = $entity->title;
    }
}
....
//inputs
$form['exbooth'] = array(
    '#type' => 'select',
    '#title' => t('Exhibition Booth'),
    '#options' => $booths, // I set my array of booth nodes here
    '#required' => TRUE,
);

最新更新