为什么这总是保存数据,即使这些字段是空的?

时间:2012-02-25 03:52:36

标签: php cakephp

我有这个模型http://pastebin.com/tSaTvLxW,这是我的控制器http://pastebin.com/iWeyvF71,这是关联的视图add.ctp http://pastebin.com/YWqwMtqx但是当我添加新的信息记录时,即使是教育,体验是空的总是记录是在相应的表中创建的,我不知道是什么导致这种行为,有什么可以帮我找到这个?

1 个答案:

答案 0 :(得分:0)

当我运行此功能时,我在$ this-> request->数据中看到以下内容:

Array
(
    [Information] => Array
        (
            [name] => Test
            [lastname] => Name
            [email] => test@example.com
            [mobile_phone] => 1561561566
            [home_phone] => 1521521522
            [address] => 123 Any Street
            [other_information] => Other information
            [picture] => Array
                (
                    [name] => avatar.png
                    [type] => image/png
                    [tmp_name] => /tmp/php2Jvveh
                    [error] => 0
                    [size] => 89486
                )

        )

    [Education] => Array
        (
            [0] => Array
                (
                    [education_content] => 
                )

        )

    [Experience] => Array
        (
            [0] => Array
                (
                    [experience_content] => 
                )
        )
)

您会注意到{Array}和Experience数组虽然为空,但仍然存在于$this->request->data中。因为您使用的是$this->Information->saveAll($this->request->data),所以它会将一组空数据保存到表中。如果您不想保存空数据,请检查数组以查看它是否为空。如果是,请在保存之前取消设置。您的表单设置方式如下:

if (empty($this->request->data['Experience'][0]['experience_content'])) { 
    unset($this->request->data['Experience']);
}
if (empty($this->request->data['Education'][0]['education_content'])) { 
    unset($this->request->data['Education']);
}
$this->Information->create();
    if ($this->Information->saveAll($this->request->data)) {
    ...snip...