免责声明:我问了一个类似的问题,没有答案。所以我也很想知道“Zend”方式,或者是否有人能够提出替代方案。
下面的方法似乎对我有用。
ListForm.php
将集合添加到您的“列表”表单中。
/** The collection that holds each element **/
$name = $this->getCollectionName();
$collectionElement = new \Zend\Form\Element\Collection($name);
$collectionElement->setOptions(array(
'count' => 0,
'should_create_template' => false,
'allow_add' => true
));
$this->add($collectionElement);
此集合将保存集合元素 ( Zend\Form\Element\Checkbox
)
/** The element that should be added for each item **/
$targetElement = new \Zend\Form\Element\Checkbox('id');
$targetElement->setOptions(array(
'use_hidden_element' => false,
'checked_value' => 1,
));
$collectionElement->setTargetElement($targetElement);
然后我添加了一些方法来允许我将 an 传递ArrayCollecion
给表单。对于我收藏中的每个实体,我将创建一个新的$targetElement
;将其检查值设置为实体的 id。
/**
* addItems
*
* Add multiple items to the collection
*
* @param Doctrine\Common\Collections\Collection $items Items to add to the
* collection
*/
public function addItems(Collection $items)
{
foreach($items as $item) {
$this->addItem($item);
}
return $this;
}
/**
* addItem
*
* Add a sigle collection item
*
* @param EntityInterface $entity The entity to add to the
* element collection
*/
public function addItem(EntityInterface $item)
{
$element = $this->createNewItem($item->getId());
$this->get($this->getCollectionName())->add($element);
}
/**
* createNewItem
*
* Create a new collection item
*
* @param EntityInterface $entity The entity to create
* @return \Zend\Form\ElementInterface
*/
protected function createNewItem($id, array $options = array())
{
$element = clone $this->targetElement;
$element->setOptions(array_merge($element->getOptions(), $options));
$element->setCheckedValue($id);
return $element;
}
然后所需要做的就是将集合从控制器操作中传递给表单。
一些控制器
public function listAction()
{
//....
$users = $objectManager->getRepository('user')->findBy(array('foo' => 'bar'));
$form = $this->getServiceLocator()->get('my_list_form');
$form->addItems($users);
//...
}