Skip to content

Instantly share code, notes, and snippets.

@DenisGorbachev
Created June 9, 2012 10:57
Show Gist options
  • Save DenisGorbachev/2900548 to your computer and use it in GitHub Desktop.
Save DenisGorbachev/2900548 to your computer and use it in GitHub Desktop.
GroupedDocumentChoiceList
<?php
namespace FasterThanWind\Bundle\TaskBundle\Form\ChoiceList;
use Symfony\Bundle\DoctrineMongoDBBundle\Form\ChoiceList\DocumentChoiceList as DocumentChoiceList;
use Symfony\Component\Form\Util\PropertyPath;
use Doctrine\ODM\MongoDB\DocumentManager;
/**
* Allows to choose from a list of documents, optionally grouped by a certain property (triggers the use of <optgroup> in template)
*
* @author Denis Gorbachev <[email protected]>
*/
class GroupedDocumentChoiceList extends DocumentChoiceList
{
/**
* @var PropertyPath
*/
protected $groupByPropertyPath;
public function __construct(DocumentManager $documentManager, $class, $property = null, $queryBuilder = null, $choices = array(), $groupByProperty = null)
{
if ($groupByProperty) {
$this->groupByPropertyPath = new PropertyPath($groupByProperty);
}
parent::__construct($documentManager, $class, $property, $queryBuilder, $choices);
}
protected function load()
{
parent::load();
if ($this->groupByPropertyPath) {
$groupedChoices = array();
foreach ($this->choices as $id => $choice) {
$groupName = $this->groupByPropertyPath->getValue($this->getDocument($id));
if (empty($groupedChoices[$groupName])) {
$groupedChoices[$groupName] = array();
}
$groupedChoices[$groupName][$id] = $choice;
}
$this->choices = $groupedChoices;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment