Cakephp:如何向表中添加变量值

时间:2014-07-21 13:16:03

标签: php cakephp form-helpers

如何使用cakephp formhelper向表中添加变量值。在我的表单中,我允许用户输入一些值,但用户的IP地址也会添加到表中。我还在插入数据库之前计算用户的输入。

我应该在cakephp中修改控制器或模型吗?我有一个带有id,cybernumber,created,department,ipaddress的Number表。非常感谢。

//Controller/NumberController.php
public function add() 
{
    if ($this->request->is('post')) 
    {
        $this->Number->create();
        //not working 
        //$this->request->data['Number']['ipaddress'] = $this->request->clientIp();
        //not working 
        //$this->Number->set('ipaddress',$this->request->clientIp());

        if ($this->Number->save($this->request->data)) 
        {
            $this->Session->setFlash(__('OK.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
        }
    }
}

// Model/Number.php
<?php

class Number extends AppModel {

    public $validate = array(
        'cybernumber' => array(
            'rule' => 'isUnique',
            'message' => 'unique only'
        ),
        'department' => array(
            'rule' => 'notEmpty'
        )

    );
}

1 个答案:

答案 0 :(得分:1)

首先在Config / core.php中更改:Configure :: write('debug',0);配置:: write('debug',1);

$this->Number->create();
$this->request->data['Number']['ipaddress'] = $this->request->clientIp();

添加

debug($this->request->data);

检查ipaddress字段是否存在。

尝试检查数据库中的字段类型。也许它与数据格式不兼容。