1

我一直在寻找解决方案,但似乎无法弄清楚这一点。我想要做的是在添加产品时,我希望从表单中的输入中填充名称字段。因此名称将包括用户为 type_id、category_id 和 subcategory_id 选择的值。有谁知道实现这一目标的方法?

添加产品查看页面

    <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'));

}
4

1 回答 1

1

为了按照您尝试的方式进行操作,您必须使用客户端 javascript 来“即时”更新输入值,但这不是很安全并且很容易被弄乱。完全删除名称输入并在 Product 模型的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;
}
于 2013-02-27T19:19:04.410 回答