我正在尝试将 JQuery 的日期选择器与 CakePHP 一起使用。我似乎不知道该怎么做 同时还使用 CakePHP 的内置日期验证并允许任何日期格式。 我遇到的任何答案都涉及复杂的解决方案。 我感觉必须有一个简单的方法来做到这一点,看起来 JQuery 如何 datepicker 是一个很常见的东西。
目前,我正在尝试将日期转换为 CakePHP 日期数组 格式
array( 'day' => '21', 'month' => '3', 'year' => '1993' )
当输入无效数据时,这会导致问题。它在任何空日期中放置两个空格 字段,并且 strtotime 将空格计为“现在”。因此,如果无效数据是 输入,并且用户重新发送数据,这会导致任何空日期字段(不是必需的) 保存为今天的日期。
有什么想法吗?
最佳答案
尝试这样的事情:
在模型中:
/*...*/
$validate = array(
'your_date' => array(
'date' => array(
//Add 'ymd' to the rule.
'rule' => array('date', 'ymd'),
'message' => 'Please select a valid birth date.',
),
),
);
/*...*/
在 Controller 中:
//Put into a function so you can reuse the same code.
function convertDates( &$data ){
if (!empty($data['date_of_birth']) && strtotime($data['date_of_birth']) ){
$data['date_of_birth'] = date('Y-m-d', strtotime($data['date_of_birth']));
}
}
调用上述函数的函数:
public function add() {
/*...*/
//Convert the dates to YYYY-MM-DD format before attempting to save.
$this->convertDates( $this->request->data['ModelName'] );
/*...*/
}
查看中:
/*...*/
//Make input form a text field, and give it a class of datepicker (or whatever).
echo $this->Form->input('date_of_birth', array(
'class'=>'datepicker', 'type'=>'text','label'=>'Date of Birth'
)
);
/*...*/
然后在底部添加初始化脚本:
<script>
//Initialize your datepicker at the bottom.
$(document).ready(function() {
$( "input.datepicker" ).datepicker({
yearRange: "-100:+50",
changeMonth: true,
changeYear: true,
constrainInput: false,
showOn: 'both',
buttonImage: "/img/calendar.png",
buttonImageOnly: true
});
});
</script>
关于jquery-ui - 使用 JQuery Datepicker 进行 CakePHP 日期验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17282582/