How to pass an argument to a Zend Form Collection instance & How to set custom Fieldset labels in ZF2?

和自甴很熟 提交于 2019-12-13 04:25:54

问题


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:

  1. 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) }

  1. 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!


回答1:


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++);
    }



回答2:


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);
}


来源:https://stackoverflow.com/questions/35100826/how-to-pass-an-argument-to-a-zend-form-collection-instance-how-to-set-custom-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!