cakephp在保存表单数据之前将值设置为模型

时间:2014-03-10 08:58:36

标签: forms cakephp

我正在学习CakePHP。我想将表单数据提交到数据库,在保存之前,我希望修改几个字段。这是我试过的:

public function addProduct() {

    $this->layout = false;
    $this->render ( false );

    $this->loadModel ( 'Product' );

    $this->Product->create();

    $conditions = array('Product.category_id' => $this->request->data["categoryproduct"],
                        'Product.company_id' => $this->request->data["companyproduct"],
                        'Product.name' => $this->request->data["name"]
                    );

    $product = $this->Product->find ( 'first', array ('conditions' => $conditions ) );

    if ($product)
        echo "duplicate";
    else{

        $discount = $this->request->data["discount"];

        if($discount>0){
            $cost = $this->request->data["cost"];
            $this->Product->costforyou = intval($cost - $cost * $discount / 100);
        }
        else
            $this->Product->costforyou = 0;

        $this->Product->category_id = $this->request->data["categoryproduct"];
        $this->Product->company_id = $this->request->data["companyproduct"];
        $this->Product->create_date = date('Y-m-d h:i:s');
        $this->Product->status = "active";

        if ($this->Product->save($this->request->data)) {
            echo "Product added";
        } else {
            echo "Error in adding product";
        }
    }
}

但是我手动设置的所有字段都没有获取数据。我试着看一下CakePHP书籍,但在那里找不到任何东西。

2 个答案:

答案 0 :(得分:0)

我解决了这个问题。这是我的新代码:

public function addProduct() {

    $this->layout = false;
    $this->render ( false );

    $this->loadModel ( 'Product' );

    $this->Product->create();

    $conditions = array('Product.category_id' => $this->request->data["categoryproduct"],
                        'Product.company_id' => $this->request->data["companyproduct"],
                        'Product.name' => $this->request->data["name"]
                    );

    $product = $this->Product->find ( 'first', array ('conditions' => $conditions ) );

    if ($product)
        echo "duplicate";
    else{

        $discount = $this->request->data["discount"];
        $costforyou = 0;

        if($discount>0){
            $cost = $this->request->data["cost"];
            $costforyou = intval($cost - $cost * $discount / 100);
        }

        $this->request->data["category_id"] = $this->request->data["categoryproduct"];
        $this->request->data["company_id"] = $this->request->data["companyproduct"];
        $this->request->data["costforyou"] = $costforyou;
        $this->request->data["createdate"] = date('Y-m-d h:i:s');
        $this->request->data["status"] = "active";

        if ($this->Product->save($this->request->data)) {
            echo "Product added";
        } else {
            echo "Error in adding product";
        }
    }
}

答案 1 :(得分:0)

为什么不用这个beforeSave()

这是在保存之前修改数据的便捷方法。