在我當前的項目中,我使用了嵌套的Zend\Form\Fieldset
s和Zend\Form\Collection
s,它們提供了一種非常舒適的方式將複雜的對象結構映射到表單,以便從表單輸入中獲取完整的對象(可以保存)。如何裝飾ZF2集合中的字段集的元素?
的問題:我有一個Fieldset
FooFieldset
含有Element
foo_element
與Label
爲「foo元件」(代碼見下文),並且需要使用兩次:1.作爲單個Fieldset
; 2.在Collection
。在表單的第一位,我希望顯示其元素;在第二個地方,我想禁用標籤(或者可能改變它們)。 (我也想把它格式化在第二種情況中的另一種方式,但現在最重要的事情是標籤。)
根據上下文如何裝點Zend\Form\Element
個Zend\Form\Fieldset
的在Zend\Form\Element\Collection
?
代碼
class FooFieldset extends Fieldset implements InputFilterProviderInterface
{
public function init()
{
$this->add([
'type' => 'text',
'name' => foo_element',
'options' => ['label' => _('foo element')]
]);
}
public function getInputFilterSpecification() { ... }
}
class BarFieldset extends Fieldset implements InputFilterProviderInterface
{
public function init()
{
$this->add([
'name' => 'foo',
'type' => 'My\Form\Fieldset\Foo',
'options' => []
]);
}
public function getInputFilterSpecification() { ... }
}
class BuzFieldset extends Fieldset implements InputFilterProviderInterface
{
$this->add(
[
'name' => 'foos',
'type' => 'Zend\Form\Element\Collection',
'options' => [
'label' => _('multiple foos'),
'count' => 5,
'should_create_template' => true,
'template_placeholder' => '__placeholder__',
'allow_add' => true,
'target_element' => [
'type' => 'Order\Form\Fieldset\Foo',
],
'label_attributes' => [
'class' => 'col-md-12'
]
]
]);
public function getInputFilterSpecification() { ... }
}
echo $this->formRow($myForm->get('main_fieldset')->get('bar')->get('foo')->get('foo_element');
echo $this->formRow($myForm->get('main_fieldset')->get('buz')->get('foos');
解決方法1
這將有可能使用另一種Fieldset
,例如一個FooFieldst
(sometnig like FooFieldsetForUsingInCollection extends FooFieldst
)的子類,並在那裏調整Label
(和其他設置)。
解決方法2
也將是可以訪問在視圖腳本Collection
的Element
秒和操縱它們在那裏(如here證實)。但我不太喜歡這個解決方案,因爲Fieldset
被定義在多個地方。如果Collection
元素的數量是可變的,那麼還需要進一步的努力。
'main_fieldset' ='BuzFieldset'? – AlexP
不,'Bar'和'Buz'都是'MainFieldset'的Sub-'Fieldset'。對不起,這是一個錯字。請參閱更正的代碼。 – automatix