[英]only Last 7 days from Todays Date in zend forms
我的开始只显示过去 7 天,并以 zend 形式与今天的日期进行比较,所有过去的日期都应该禁用,除了过去的 7 天。 我试图在属性部分设置 min 选项但不起作用。 下面是我的代码
$this->add([
'name' => 'start',
'type' => 'Date',
'options' => [
'label' => 'Start Date*',
],
'attributes' => [
'id' => 'start_date',
'required' => 'required'
],
]);
您必须进行两项更改。
请注意:在这些片段中,我使用日期格式Ymd
,只需检查与您的匹配;)
第一个,您需要将最小日期添加到您的元素:
$this->add([
'name' => 'start',
'type' => 'Date',
'options' => [
'label' => 'Start Date*',
],
'attributes' => [
'id' => 'start_date',
'required' => 'required',
'min' => ((new \DateTime())->sub(new \DateInterval('P7D')))->format('Y-m-d')
],
]);
如果您使用 zend 助手打印它,它将正确呈现它:
PHTML 文件
<?php $startDate = $this->form->get('start');?>
<?= $this->formLabel($startDate); ?>
<?= $this->formElement($startDate); ?>
<?= $this->formElementErrors($startDate); ?>
HTML 结果
<label for="start_date">Start Date*</label>
<input type="date" name="start" id="start_date" required="required" min="2021-04-21" value="">
您可以在此处查看结果(并且,如您所见,无需包含 JQuery)
如果您不验证用户的输入,那么在 input 元素中设置最小日期将不会真正有效(我的意思是,每个人都可以更改 HTML 中的属性)。 您必须验证结果。
为了做到这一点,您的表单 class 必须实现Zend\InputFilter\InputFilterProviderInterface
接口。
在这个片段中,我使用了Callback
验证器,但最好(也是最干净)的解决方案是创建一个自定义验证器;)
class YourForm extends Form implements InputFilterProviderInterface {
public function init() {
parent::init();
$this->add([
'name' => 'start',
'type' => 'Date',
'options' => [
'label' => 'Start Date*',
],
'attributes' => [
'id' => 'start_date',
'required' => 'required',
'min' => ((new \DateTime())->sub(new \DateInterval('P7D')))->format('Y-m-d')
],
]);
}
public function getInputFilterSpecification() {
$inputFilter[] = [
'name' => 'start',
'required' => true,
'validators' => [
[
'name' => 'Date',
'options' => [
'format' => 'Y-m-d'
]
],
[
'name' => 'Callback',
'options' => [
'callback' => function ($value) {
$date = \DateTime::createFromFormat('Y-m-d', $value);
// Set time to midnight to avoid getting errors for a small difference in seconds
$date->setTime(0, 0, 0, 0);
// Get current date, set to midnight
$today = (new \DateTime())->setTime(0, 0, 0);
// CHOOSE THE ONE YOU PREFER
// Option 1
// One week is (7 * 24 * 60 * 60) 604'800 seconds
$differenceMillis = $date->getTimestamp() - $today->getTimestamp();
return $differenceMillis >= (-604800);
// Option 2
$dateDifference = $today->diff($date);
return !$dateDifference->invert && $dateDifference < 7;
},
'messages' => [
\Zend\Validator\Callback::INVALID_VALUE => 'The date is more than 7 days in the pas'
]
]
]
]
];
return $inputFilter;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.