2011-03-22 42 views
0

堆棧溢出的第一篇文章...所以容易對我!Drupal的FAPI表單調用回調兩次

對於簡單的表單提交,似乎沒有合適的Drupal FAPI多重回調問題的解決方案。

問題:我的表單在提交時,將兩個條目添加到相應的數據庫表中。鑑於只有一個調用將其添加到數據庫中,我認爲可以安全地假設查詢運行兩次(因此是雙重條目)。

以下代碼可能有助於爲解決方案提供基礎。哦,它也是Drupal 7,所以文檔仍然以D6爲中心。

function mymodule_sidebar_form_add_submit(&$form, &$form_state) { 

    $form_values = $form_state['values']; 

    $se_title = check_plain(trim($form_values['title'])); 
    $se_link = url(trim($form_values['link'])); 
    $se_content = check_plain(trim($form_values['content'])); 
    $se_image = isset($form_values['image']) ? $form_values['image'] : ''; 

    // The multi-line part below is actually a single line the real code 
    $query = sprintf("INSERT INTO sidebar_element(title, image_url, content) 
     VALUES ('%s', '%s', '%s');", $se_title, $se_image, $se_content); 

    db_query($query); 
    drupal_set_message(t('Sidebar Element has been added successfully.')); 
} 

...和我的表單功能包含一個提交按鈕:

$form['submit'] = array(
     '#value' => t('Add Sidebar'), 
     '#type' => 'submit', 
     '#title' => t('Add Sidebar'), 
     '#submit' => array('mymodule_sidebar_form_add_submit'), 
    ); 

我想我需要回答的問題是:

  1. 爲什麼會出現在第一雙回調地點?
  2. 有沒有辦法確定第一個回調?

在此先感謝各位。

回答

0
$form['submit'] = array(
     '#type' => 'submit', 
     '#value' => t('Save') 
); 
    $form['#submit'] = array('my_form_submit'); 

而更換

// The multi-line part below is actually a single line the real code 
    $query = sprintf("INSERT INTO sidebar_element(title, image_url, content) 
     VALUES ('%s', '%s', '%s');", $se_title, $se_image, $se_content); 

    db_query($query); 

// The multi-line part below is actually a single line the real code 
    $query = "INSERT INTO {sidebar_element} (title, image_url, content) 
     VALUES ('%s', '%s', '%s')"; 

    db_query($query, $se_title, $se_image, $se_content); 
+0

哎呀... Drupal的7對不起 – dobeerman 2011-03-22 02:01:01

0

爲Drupal 7

// Add the buttons. 
    $form['actions'] = array('#type' => 'actions'); 

    $form['actions']['submit'] = array(
    '#type' => 'submit', 
    '#access' => my_func(), 
    '#value' => t('Save'), 
    '#weight' => 100, 
    '#submit' => array('my_form_submit'), 
); 

作爲示例讀node_form()代碼

0

要找出第二個調用來自哪裏,最簡單的方法是在提交回調中安裝devel.module並使用ddebug_backtrace()。您可能還需要禁用HTTP redirecto才能看到它(exit())。

但更重要的是,使用API​​,盧克!

<?php 
db_insert('sidebar_element') 
    ->fields(array(
    'title' => $se_title, 
    'image_url' => $se_image, 
    'content' => $se_content, 
)) 
    ->execute(): 
?> 

這是如何插入查詢應該看起來像,你在做什麼是不安全的!

而對於SELECT,使用db_query()與指定的佔位符:

<?php 
$result = db_query('SELECT * FROM {sidebar_element} WHERE title = :title', array(':title' => $something)); 
?>