Search code examples
datecakephpdrop-down-menucakephp-2.x

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


I need to pass data from my form. I have a drop-down with the years to choose from in the view:

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--'
)); 

The above displays them, but when I hit submit, debug tells me that the data is empty.

In the database, the data type is date.

The controller is:

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');
    }
}

The erros is:

$this->validationErrors(array)

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

Solution

  • Your problem is that you are trying to save an incomplete date into a date field in the database, and because it's invalid, the ORM is setting the field to NULL.

    You have two options here:

    • Change the field type in the database to smallint, which is probably what it should have been from the start, considering agno (año) translates to year.

    • Add two other fields, so the three produce a valid date:

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

      But probably this is not what you are after.