免責事項:同様の質問をしましたが、回答がありません。したがって、「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);
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);
//...
}