[英]How to pass an argument to a Zend Form Collection instance & How to set custom Fieldset labels in ZF2?
我試圖理解並解決整個表單收集問題,但是文檔並沒有真正地擴展,我只是無法找到如何做一些我需要的特定事情。
我將參考官方手冊中的示例來解釋我的需求:
創建集合后,您可以將自定義字段集用作目標:
$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', )**, ), ));
但是,我需要將參數傳遞給特定字段集的構造函數(在我的情況下為翻譯器實例),以便能夠在字段集中進行翻譯。
class CategoryFieldset extends Fieldset { public function __construct($translator) }
謝謝你的幫助!
我檢查了集合的來源。 該集合僅克隆target_element。 我的解決方案很簡單,並且可行:
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++);
}
首先,不要將轉換器傳遞給Fieldset,而要在Fieldset之外使用轉換器。 首先從表單獲取值,將其轉換,然后將其重新設置為表單。 好處是您可以將表格和翻譯邏輯分開。
第二,使用$form->prepare()
,然后遍歷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");
例:
/*
* 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.