使用 FormHelper 在 CakePHP 2.x 中将日期保存为 null

Date being saved as null in CakePHP 2.x using FormHelper

我需要从我的表单中传递数据。我有一个下拉列表,可以在视图中选择年份:

echo $this->Form->input('Zona.agno',  array(
    'label'         => 'Año',
    'type'          => 'year',     
    'minYear'       => date('Y') ,
    'maxYear'       => date('Y') + 4,
    'orderYear'     => 'asc',
    'dateFormat'    => 'Y',        
    'empty' => '--Seleccione Año--'
)); 

上面显示了它们,但是当我点击提交时,调试告诉我数据是空的。

在数据库中,数据类型为date

控制器是:

if ($this->request->is('post')) {
    $this->request->data('Zona.activo', 1);
    if ($this->Zona->save($this->request->data)) {
        $this->mensaje(__('La Zona ha sido creada.'));
        $this->redirect(array('action' => 'index'));
    } else {
        $this->mensaje(__('La Zona no ha sido creada, por favor verifica los datos.'), 'error');
    }
}

错误是:

$this->validationErrors(array)

Zona(array)
agno(array)
0 Debe ingresar año que aplica

您的问题是您试图将不完整的日期保存到数据库的 date 字段中,并且由于它无效,ORM 将该字段设置为 NULL。

这里有两个选择:

  • 将数据库中的字段类型更改为smallint,考虑到[=13,这可能从一开始就应该是这样的=] (año) 转换为 year.

  • 添加另外两个字段,所以这三个字段产生一个有效日期:

    <? echo $this->Form->input('Contact.birthdate', array('type' => 'month')); ?>          
    <? echo $this->Form->input('Contact.birthdate', array('type' => 'day')); ?>
    

    但这可能不是你想要的。