2013-02-27 52 views
1

我已經搜索了高和低的解決方案,但似乎無法得到這個想通了。我想要做的是在添加產品時,我希望名稱字段從表單中的輸入中填充。因此該名稱將包含用戶爲type_id,category_id和subcategory_id選擇的值。有誰知道一種方法來完成這個?Cakephp:結合輸入值創建隱藏名稱輸入

添加產品查看頁面

<fieldset> 
    <legend><?php echo __('Add Product'); ?></legend> 
<?php 
    echo $this->Form->input('type_id'); 
    echo $this->Form->input('category_id', array('label' => 'Vendor')); 
    echo $this->Form->input('subcategory_id', array('label' => 'Model')); 
    echo $this->Form->input('location', array('label' => 'Location')); 
    echo $this->Form->input('sku', array('label' => 'Asset Tag')); 
    echo $this->Form->input('mac'); 
    echo $this->Form->input('description', array('label' => 'Notes')); 
    echo $this->Form->input('name', array('value' => ['type_id']['category_id'] , 'type' => 'hidden')); 
    //echo $this->Form->input('cost'); 
    // echo $this->Form->input('Tag'); 
    ?> 
    </fieldset> 

產品控制器添加功能

public function add() { 
    if ($this->request->is('post')) { 
     $this->Product->create(); 
     if ($this->Product->save($this->request->data)) { 
      $this->Session->setFlash(__('The product has been saved')); 
      $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The product could not be saved. Please, try again.')); 
     } 
    } 
    $subcategories = $this->Product->Subcategory->find('list',array('order'=>'Subcategory.name asc')); 
    $categories = $this->Product->Category->find('list',array('order'=>'Category.name asc')); 
    $types = $this->Product->Type->find('list',array('order'=>'Type.name asc')); 
    $this->set(compact('subcategories', 'categories', 'types')); 

} 

回答

1

爲了做到這一點,你正在試圖做到這一點,你將不得不使用客戶端JavaScript更新輸入值「即時」,但這不是很安全,很容易被混淆。將名稱輸入完全刪除並在產品模型的beforeSave方法中處理(或者在保存之前通過在控制器中定義名稱值),將會更有意義。

public function beforeSave($options = array()) { 
    // Generate the name based on type and category 
    $this->data['Product']['name'] = $this->data['Product']['type_id'] . 
            $this->data['Product']['category_id']; 

    return true; 
} 

根據您的評論更新。

爲了得到名稱,只要找到這些名稱(假設你的模型相關聯),並定義這些:

public function beforeSave($options = array()) { 
    // Get the type name 
    $type = $this->Type->field('name', array(
     // Set the condition for the field 
     'Type.id' => $this->data['Product']['type_id'] 
    )); 

    // Get the category name 
    $category = $this->Category->field('name', array(
     // Set the condition for the field 
     'Category.id' => $this->data['Product']['category_id'] 
    )); 

    // Generate the name based on type and category 
    $this->data['Product']['name'] = $type . $category; 

    return true; 
} 
+0

真棒謝謝!這工作幾乎完全符合我的要求。你知道是否有可能用關聯的type_id和category_id替換它們各自的名稱而不是id? – rubyme8 2013-02-27 20:09:03

+0

@ ruby​​me8是的,這是可能的,看到我更新的答案。 – Oldskool 2013-02-27 20:13:58