Phalcon\Forms\Form将emtpy字段绑定为空。

问题描述 投票:0回答:1

我的数据库表是这样的

CREATE TABLE `tbl` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `myVar` INT NULL DEFAULT NULL,
  PRIMARY KEY (`id`));

我想把$_POST的空值保存为NULL。

下面是简单的代码。

class MyForm
{
// ...
    public function addInput()
    {
        $t = new Phalcon\Forms\Element\Text('myVar');
        $t->setFilters(['int']);
        // ...
        $this->add($t);
        return $this;
    }
}
class MyController
{
    public function myFunAction()
    {
        $form = new MyForm();
        $entity = new MyModel();
        if ($this->request->isPost() === true) {
            $post = $this->request->getPost();
            if ($form->isValid($post, $entity) === true && $entity->save()) {
                // OK
            }
        }
    }
}

myVar 在我的文本输入中是空字符串 0 在db表中。

是否更好的解决方案是将 NULL 比覆盖 束缚 myForm类中的方法?

php database phalcon
1个回答
1
投票

int phalcon的过滤器删除了除数字、加号和减号以外的所有字符。

这个过滤器内部基于PHP的 过滤器_var 函数。所以如果我们使用 filter_var我们可以这样写一个过滤器,它的默认返回值为 null如果过滤失败

<?php

function filter($input) {
    $options = array(
        'options' => array(
            'default' => NULL, // value to return if the filter fails
        ),
    );

    return filter_var($input, FILTER_VALIDATE_INT, $options);
}

var_dump(filter(1)); // Prints 1
var_dump(filter("1")); // Prints 1
var_dump(filter(0)); // Prints 0
var_dump(filter("")); // Prints NULL

然而Phalcon不允许你发送所有的参数。filter_var 实际上支持。所以 正解 是为了 实现自己的过滤器 并把上面的代码。

但如果你觉得自己很懒。懒办法 是以正确的方式实现的,只需在保存到数据库之前使用这段代码代替。

$input = $input === "" ? null : (int) $input;

不过我建议你用正确的方式来实现它。Phalcon\FilterInterface 因为它可以重复使用。

© www.soinside.com 2019 - 2024. All rights reserved.