我对Zend Framework 2和Date元素有问题。我试图存储的属性是DateOfBirth,但此属性可能为空。例如,日期未知。数据库中的列允许NULL。附加到它的Doctrine类有一个属性,让它知道它允许null。但是Zend Framework 2仍然给了我这个错误:
"Value is required and can't be empty".
尽管我将required属性设置为false,也将allow_empty设置为true,但什么都不起作用。
atterbute是表单中嵌套字段集的成员。嵌套如下:
- 用户管理表单
- 用户(字段集)
- 人员(字段集)
- 出生日期(元素)
- 人员(字段集)
- 用户(字段集)
我试过的几个例子:
表单未正确验证zend框架2
https://github.com/zendframework/zf2/issues/4302
这是我目前正在使用的代码。希望你能看到我错过的东西。我不知道它是否是嵌套的,但其余的都很完美,只有日期元素给我带来了麻烦。
用户管理表单
<?php
namespace Application'Form;
use Zend'Form'Form;
class UserManagementForm extends Form
{
public function __construct()
{
parent::__construct('usermanagementform');
$this->setAttribute('method', 'post');
$fieldset = new 'Application'Form'Fieldset'User();
$fieldset
->setHydrator(new 'Zend'Stdlib'Hydrator'ObjectProperty(false))
->setObject(new 'Application'Entity'User())
->setOptions(array('use_as_base_fieldset' => true))
;
$this->add($fieldset);
$this->add(array(
'name' => 'btnSubmit',
'type' => 'submit',
'attributes' => array(
'class' => 'btn-primary',
),
'options' => array(
'column-size' => 'sm-9 col-sm-offset-3',
'label' => 'Save changes',
),
));
}
}
?>
用户(字段集)
<?php
namespace Application'Form'Fieldset;
use Zend'Form'Fieldset;
class User extends Fieldset
{
public function __construct()
{
parent::__construct('User');
$fieldset = new 'Application'Form'Fieldset'EmailAddress();
$fieldset
->setHydrator(new 'Zend'Stdlib'Hydrator'ObjectProperty(false))
->setObject(new 'Application'Entity'EmailAddress());
$this->add($fieldset);
$fieldset = new 'Application'Form'Fieldset'Person();
$fieldset
->setHydrator(new 'Zend'Stdlib'Hydrator'ObjectProperty(false))
->setObject(new 'Application'Entity'Person());
$this->add($fieldset);
}
}
?>
人员(字段集)
<?php
namespace Application'Form'Fieldset;
use Zend'Form'Fieldset;
class Person extends Fieldset
{
public function __construct()
{
parent::__construct('Person');
$this->add(array(
'type' => 'date',
'name' => 'DateOfBirth',
'required' => false,
'allowEmpty' => true,
'options' => array(
'label' => 'Date of birth',
'column-size' => 'sm-9',
'label_attributes' => array(
'class' => 'col-sm-3',
),
'format' => 'd-m-Y',
),
));
}
}
?>
'required'不是元素的属性,而是验证器属性。解决方案包括实现Zend''InputFilter''InputFilter ProviderInterface
use Zend'InputFilter'InputFilterProviderInterface;
class UserManagementForm extends AbstractSbmForm implements InputFilterProviderInterface {
public function __construct()
{
... without change
}
public function getInputFilterSpecification()
{
return array(
'DateOfBirth' => array(
'name' => 'DateOfBirth',
'required' => false,
);
);
}
}