I'm trying to understand and get around this whole form collection thing, but the documentation isn't really expansive and I just can't find out how to do some specific things I need.
I will refer to the example in the official manual to explain what i need:
When the collection is created, you get to use a custom fieldset as target:
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'categories',
'options' => array(
'label' => 'Please choose categories for this product',
'count' => 2,
'should_create_template' => true,
'template_placeholder' => '__placeholder_:',
**'target_element' => array(
'type' => 'Application\Form\CategoryFieldset',
)**,
),
));
However, I need to pass an argument to the specific fieldset's constructor, in my case a translator instance in order to be able to translate within the fieldset.
class CategoryFieldset extends Fieldset
{
public function __construct($translator)
}
- Fieldset's label: as you can see in the example, the collection outputs all the copies of the fieldset with the same specified label "Category". I would need, instead, to have that label numbered, to show "Category 1", "Category 2" etc. based on the collection's count. Is this even possible?
Thanks for your help!
I checked source of the Collection. The Collection just clones target_element. My solution is simple and works:
class CategoryFieldset extends Fieldset implements InputFilterProviderInterface
{
static $lp = 1;// <----------- add this line
public function __clone() //<------------ add this method
{
parent::__clone();
$oldLabel = $this->elements['name']->getLabel();
$this->elements['name']->setLabel($oldLabel . ' ' . self::$lp++);
}
For the first, do not pass translator to the Fieldset, but use translator outside of the Fieldset. Get the values first, from the form, translate them, then set them back into the form. The bonus is that you keep your form and your translator logic separate.
For the second, use $form->prepare()
and then iterate over the Collection
.
$form->prepare(); //clones collection elements
$collection = $form->get('YOUR_COLLECTION_ELEMENT_NAME');
foreach ($collection as $fieldset)
$fieldset->get('INDIVIDUAL_ELEMENT_NAME')->setLabel("WHATEVER YOU WANT");
Example:
/*
* In your model or controller:
*/
$form->prepare();
$collection = $form->get('categories');
foreach ($collection as $fieldset)
{
$label = $fieldset->get('name')->getLabel();
$translatedLabel = $translator->translate($label);
$fieldset->get('name')->setLabel($translatedLabel);
}