如何最好地将 CakePHP 日期选择器表单数据转换为 PHP DateTime 对象?
我在 app/views/mymodel/add.ctp
中这样做:
<?php echo $form->input('Mymodel.mydatefield'); ?>
然后,在app/controllers/mymodel_controller.php
:
function add() {
# ... (if we have some submitted data)
$datestring = $this->data['Mymodel']['mydatefield']['year'] . '-' .
$this->data['Mymodel']['mydatefield']['month'] . '-' .
$this->data['Mymodel']['mydatefield']['day'];
$mydatefield = DateTime::createFromFormat('Y-m-d', $datestring);
}
绝对必须有更好的方法来做到这一点 - 我只是还没有找到 CakePHP 的方法......
There absolutly has to be a better way to do this - I just haven't found the CakePHP way yet...
我想做的是:
function add() {
# ... (if we have some submitted data)
$mydatefield = $this->data['Mymodel']['mydatefiled']; # obviously doesn't work
}
推荐答案
我知道这是一个老问题,但万一其他人来寻找答案:CakePHP 的通用 Model
类有一个方法, ::deconstruct()
,用于在内部处理这个必要的逻辑.你可以这样使用它:
I know this is an old question, but in case anyone else comes looking for an answer: CakePHP's generic Model
class has a method, ::deconstruct()
, that is used to handle this necessary logic internally. You can use it like this:
$stringDate = $this->MyModel->deconstruct('fieldname', $arrayDate)
相关文章