【发布时间】:2017-09-01 07:44:32
【问题描述】:
我有一个字段集,其中包含一个名为“company”的字段,默认情况下不需要该字段。现在有一个添加此字段集的表单,现在应该需要“公司”。有没有办法在 e 中做到这一点? G。表单工厂?或者我可以在绑定到表单的 inputfilter 类中重写字段集的输入过滤器吗?
感谢您的回复!
字段集
class MyFieldset extends Fieldset implements InputFilterProviderInterface {
public function init() {
$this->add([
'name' => 'company',
'options' => [
'label' => 'Firma'
],
'attributes' => [
'id' => 'address-company'
]
]);
}
public function getInputFilterSpecification() {
return [
'company' => [
'required' => false,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
['name' => 'ToNull']
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 128
]
]
]
],
];
}
}
表格
class MyForm extends Form {
public function init() {
$this->add([
'type' => MyFieldset::class,
'name' => 'test',
'options' => [
'use_as_base_fieldset' => true
]
]);
}
}
表单工厂
class MyFormFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
$hydratorManager = $container->get('HydratorManager');
$inputFilterManager = $container->get('InputFilterManager');
$form = new MyForm();
$form->setHydrator($hydratorManager->get(DoctrineObject::class));
$form->setInputFilter($inputFilterManager->get(MyInputFilter::class));
$form->bind(new Entity());
return $form;
}
}
【问题讨论】:
-
可以在我的一个问题上查看this answer,并将其与this answer 结合起来。第一个是将您的 InputFilters 从您的 Fieldsets 中分离出来。第二个是关于创建一个附加选项,允许您将具有 Fieldset 类型的 Inputs(因此另一个 Fieldset)设置为(不是)必需的。然后覆盖默认的 isValid 方法以允许该检查。需要做一些工作,但使用 Fieldsets 和 Collections 会更容易/更干净 :) 顺便说一句,关于 ZF2 的链接,但可能会有所帮助。
标签: forms zend-framework2 zend-framework3