2013-02-27 53 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