3

我正在尝试将 JQuery 的日期选择器与 CakePHP 一起使用。我似乎无法弄清楚如何做到这一点,同时还使用 CakePHP 的内置日期验证并允许任何日期格式。我遇到的任何答案都涉及复杂的解决方案。我觉得必须有一种简单的方法来做到这一点,看起来 JQuery 日期选择器是多么常见的东西。

目前,我正在尝试通过将日期转换为 CakePHP 日期数组格式

array( 'day' => '21', 'month' => '3', 'year' => '1993' )

当输入无效数据时,这会导致问题。它在任何空的日期字段中放置两个空格,并且 strtotime 将空格计为“现在”。因此,如果输入了无效数据,并且用户重新发送数据,则会导致任何空的日期字段(不是必需的)被保存为今天的日期。

有任何想法吗?

4

1 回答 1

1

尝试这样的事情:

在模型中:

/*...*/
    $validate = array( 
        'your_date' => array(
            'date' => array(
                //Add 'ymd' to the rule.
                'rule' => array('date', 'ymd'),
                'message' => 'Please select a valid birth date.',
            ),
        ),
    );
/*...*/

在控制器中:

//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>
于 2013-06-24T18:41:54.490 回答