2013-03-01 79 views
0

我需要將多個複選框保存到連接表的幫助。Cakephp - 將多個複選框保存到連接表

有3個表:

  • 客戶(ID,姓名,地址)
  • 產品(ID,PRODUCT_NAME,DESC)所有產品都進入了。
  • Customers_Products(ID,PRODUCT_ID,CUSTOMER_ID)< - (連接表)

步驟1:
客戶選擇所需產物(蘋果,橙子,櫻桃在複選框) 和點擊<Next>按鈕

第2步:
˚F填寫自己的表格(姓名,地址等)。 並單擊<Submit>按鈕

第3步:
我節省步驟2到Customers表從步驟1至Customers_Products表個人信息和選擇的產品ID(或多個)。 它確實將個人信息和產品ID保存到指定的表格中,但是當客戶選擇多個產品時,它不會保存產品ID。 它增加了行但產品id字段爲空。

這是我的觀點:

  • <?php echo $this->Form->checkbox('CustomerProduct.product.', array('value' => '1', 'style' => 'float: left; display: inline')); ?>
  • <?php echo $this->Form->checkbox('CustomerProduct.product.', array('value' => '2', 'style' => 'float: left; display: inline')); ?>
  • <?php echo $this->Form->checkbox('CustomerProduct.product.', array('value' => '3', 'style' => 'float: left; display: inline')); ?>
  • <?php echo $this->Form->input('Customers.name', array('value'=>'Jon Toshmatov')); ?>

控制器:

$this->Prospect->saveAll($this->request->data); 

型號:

public $hasAndBelongsToMany = array(
    'CustomerProduct' => array(
     'className' => 'CustomerProduct', 
     'joinTable' => 'customers_products', 
     'foreignKey' => 'customer_id', 
     'associationForeignKey' => 'product_id', 
     'unique' => 'false', 
     'dependent' => false, 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'exclusive' => '', 
     'finderQuery' => '', 
     'counterQuery' => '' 
    ) 

期望的結果: 我想保存數據按以下順序:

 
Customers table: 
id  name 
1  Jon T 

Customers_Products *(join table)* 
id product_id customer_id 
1 4   1 
2 3   1 
3 5   1 

回答

0

的問題是,每個複選框還將添加一個「隱藏」的輸入如果通過CakePHP formhelper創建的話。這個隱藏的輸入被添加來確保複選框總是發送一個值(0或1),即使它們沒有被檢查。

但是,在您的示例中,您正在創建3個具有相同「名稱」的複選框,因此每個複選框將覆蓋以前的值。

,最好的辦法是創建CakePHP的表單助手一個「多」複選框;

echo $this->Form->input('Product', array('multiple' => 'checkbox')); 

爲了這個正常工作,應該有一個$products viewVar,包含產品ID和標籤;

內部控制器:

public function some_action() 
{ 
    // your code here 

    $this->set('products', $this->Customer->Product->find('list')); 
} 

更多關於這裏保存HABTM數據; http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm

注意 除非你使用你的模型不規範的名稱,看來你hasAndBelongsToMany是不正確;

懷疑你的關係是Customer hasAndBelongsTo Product,不CustomerProduct

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm

+0

thaJeztah, 感謝您的回覆,我就能夠解決問題。 問題與我的形式複選框的名字,該複選框值不正確地傳遞。 – 2013-03-03 20:37:25

+0

問題可以再次關閉,謝謝。 – 2013-03-03 20:37:59