从Model的beforeSave方法中的Form获取数据



我已经创建了一个注册表形式。我有3个选择框。天、月、年。在我的数据库中,我有一个名为"生日"的列,格式为"日期"。现在我想把这三个放在一起,并将结果插入数据库。

public function beforeSave($options = array()){
    $this->data['User']['Birthday'] = $this->data['User']['Year'] . '-' . $this->data['User']['Month'] .'-' . $this->data['User']['Day'];
    return true;
}

但这不起作用:(

这些字段(天、月、年、生日)都没有验证规则。。

我该怎么做?

您可以在您的模型中尝试以下代码:

public function beforeSave($options = array()){
   if(!empty($this->data)){
       //pr($this->data);die;
       $this->data['User']['Birthday'] = date('Y-m-d', strtotime($this->data['User']['Year'] . '-' . $this->data['User']['Month'] .'-' . $this->data['User']['Day']));
      unset($this->data['User']['Year']);
      unset($this->data['User']['Month']);
      unset($this->data['User']['Day']);
   }
   return true;   
}

您的表单中必须有以下表单字段:

<?php echo $this->Form->create('User', array('url' => $this->params));
      echo $this->Form->input('Year', array('options' => $year_options, 'type' => 'select'));
      echo $this->Form->input('Month', array('options' => $month_options, 'type' => 'select'));
      echo $this->Form->input('Day', array('options' => $day_options, 'type' => 'select'));

最新更新