2013-06-24 64 views
3

我想用CakePHP中使用JQuery的datepicker。我似乎无法弄清楚如何做到这一点,同时也使用CakePHP的内置日期验证并允许任何日期格式。 我遇到过的任何答案都涉及复杂的解决方案。 我觉得必须有一个简单的方法来做到这一点,看起来JQuery datepicker是一个常见的事情。CakePHP日期验证与JQuery Datepicker

目前,我的日期转换为CakePHP的日期阵列 格式

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

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

任何想法?

回答

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']); 
    /*...*/ 
} 

在View :

/*...*/ 
//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> 
+1

这工作太好了,谢谢!我错过了说明如何修改日期规则行为的文档(如果有的话)。 –