来自 fieldset 的 ZF2 hydrate 对象
ZF2 hydrate object from fieldset
在 ZF2 中,我有一个如下所示的字段集:
class PhoneRegistrationFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('phoneRegistration');
$this
->setHydrator(new ClassMethods(false))
->setObject(new Phone());
$this->add([
'type' => 'Zend\Form\Element\Select',
'name' => 'phoneType',
'options' => [
'value_options' => // array of values
],
]);
$this->add([
'name' => 'areaCode',
'options' => [
'label' => 'label'
],
]);
// other fields
}
}
形式:
class PhoneRegistrationForm extends Form
{
public function __construct()
{
parent::__construct();
$this
->setAttribute('method', 'post')
->setHydrator(new ClassMethods(false))
->setInputFilter(new InputFilter());
$this->add([
'type' => 'Parties\Form\Fieldsets\PhoneRegistrationFieldset',
]);
$this->add([
'type' => 'Zend\Form\Element\Button',
'name' => 'submitPhoneButton',
'attributes' => [
'type' => 'submit',
]);
}
}
我在控制器中验证表单。它得到验证,但 Phone
对象在验证过程中没有被水化。如果我dump
验证后的对象,它的所有属性都是NULL
。
我怎样才能水化附加到字段集的对象?
编辑:我的解决方案在 ZF3 中不起作用。
意外找到了解决方案:我需要在控制器的表单上调用 bind()
方法,例如:
$this->phoneRegistrationForm->bind(new Phone());
这很有趣,但是你可以把任何对象扔进bind()
方法,你仍然得到水合的字段集的对象。
检查附加到其他字段集的对象的水合后,如果调用表单上的 bind()
方法,它们都会水合。希望这对像我这样刚接触 ZF2 的人有所帮助。
在 ZF2 中,我有一个如下所示的字段集:
class PhoneRegistrationFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('phoneRegistration');
$this
->setHydrator(new ClassMethods(false))
->setObject(new Phone());
$this->add([
'type' => 'Zend\Form\Element\Select',
'name' => 'phoneType',
'options' => [
'value_options' => // array of values
],
]);
$this->add([
'name' => 'areaCode',
'options' => [
'label' => 'label'
],
]);
// other fields
}
}
形式:
class PhoneRegistrationForm extends Form
{
public function __construct()
{
parent::__construct();
$this
->setAttribute('method', 'post')
->setHydrator(new ClassMethods(false))
->setInputFilter(new InputFilter());
$this->add([
'type' => 'Parties\Form\Fieldsets\PhoneRegistrationFieldset',
]);
$this->add([
'type' => 'Zend\Form\Element\Button',
'name' => 'submitPhoneButton',
'attributes' => [
'type' => 'submit',
]);
}
}
我在控制器中验证表单。它得到验证,但 Phone
对象在验证过程中没有被水化。如果我dump
验证后的对象,它的所有属性都是NULL
。
我怎样才能水化附加到字段集的对象?
编辑:我的解决方案在 ZF3 中不起作用。
意外找到了解决方案:我需要在控制器的表单上调用 bind()
方法,例如:
$this->phoneRegistrationForm->bind(new Phone());
这很有趣,但是你可以把任何对象扔进bind()
方法,你仍然得到水合的字段集的对象。
检查附加到其他字段集的对象的水合后,如果调用表单上的 bind()
方法,它们都会水合。希望这对像我这样刚接触 ZF2 的人有所帮助。