簡體   English   中英

如何使用Form API以編程方式創建選擇輸入,其值來自外鍵?

[英]How can I programmatically create a select input whose values come from a foreign key using Form API?

我有一個具有引用表B的外鍵的表A。我希望與表A關聯的表單具有一個選擇字段,其值將來自表B。我希望選擇字段具有帶有鍵值對的選項,它們來自表B.

表A和表B都包含不同類型的實體。

我目前正在尋找使用Entity Reference的編程解決方案,但不必從Administration > Structure > <entity type>添加一個新字段。

我使用了使用entity_load解決方案,然后將已加載的實體作為選項添加到選擇字段中:

$foreign_entity_items = entity_load('foreign_entity');
$foreign_entity_options = array();
foreach ($foreign_entity_items as $foreign_entity_item) {
    $foreign_entity_options[$foreign_entity_item->some_field] = $foreign_entity_item->some_other_field;
}

$form['some_form_element'] = array(
    '#title' => t('Some title'),
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => $foreign_entity_options
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM