【问题标题】:Get data from a Form in the beforeSave method of a Model在 Model 的 beforeSave 方法中从 Form 中获取数据
【发布时间】:2012-09-03 00:49:08
【问题描述】:

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

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

但这不起作用:(

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

我该怎么做?

【问题讨论】:

  • 概念看起来不错 - 你遇到了什么错误?您是否调试过 $this->data 以查看数据中实际包含的内容?
  • 将您的输入更改为 input('User.Birthday.year') 并且对于月份和日期相同。如果 db 中的数据类型为日期,则 cake 应自动将日期输入重新构造为字符串。虽然,为视图重新构建它将不再是自动的。为什么只使用 input('User.Birthday') 并将其类型设置为 date

标签: forms cakephp before-save


【解决方案1】:

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

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

【讨论】:

  • 你为什么在strtotime 然后date。这就像5 * 2 / 2
  • 这是因为如果年年下拉值包含89 而不是1989,那么它可能会在保存时产生问题并导致结果为未注明日期的格式。这就是我使用 strtotime() 的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
  • 2021-08-03
  • 1970-01-01
  • 2019-07-08
  • 2022-07-12
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多