EntityChoiceList now supports grouping of entities by property path or closure

This commit is contained in:
Eric Clemmons 2011-10-24 18:45:26 -07:00
parent b171a6a8a3
commit 040e988f0c

View File

@ -81,7 +81,14 @@ class EntityChoiceList extends ArrayChoiceList
private $propertyPath;
public function __construct(EntityManager $em, $class, $property = null, $queryBuilder = null, $choices = array())
/**
* Closure or PropertyPath string on Entity to use for grouping of entities
*
* @var mixed
*/
private $groupBy;
public function __construct(EntityManager $em, $class, $property = null, $queryBuilder = null, $choices = array(), $groupBy = null)
{
// If a query builder was passed, it must be a closure or QueryBuilder
// instance
@ -102,6 +109,7 @@ class EntityChoiceList extends ArrayChoiceList
$this->queryBuilder = $queryBuilder;
$this->unitOfWork = $em->getUnitOfWork();
$this->identifier = $em->getClassMetadata($class)->getIdentifierFieldNames();
$this->groupBy = $groupBy;
// The property option defines, which property (path) is used for
// displaying entities as strings
@ -138,11 +146,43 @@ class EntityChoiceList extends ArrayChoiceList
$this->choices = array();
$this->entities = array();
if ($this->groupBy) {
$entities = $this->groupEntities($entities, $this->groupBy);
}
$this->loadEntities($entities);
return $this->choices;
}
private function groupEntities($entities, $groupBy)
{
$grouped = array();
foreach ($entities as $entity) {
if ($groupBy instanceof \Closure) {
// Get group name from Closure
$group = $groupBy($entity);
} else {
// Get group name from property path
try {
$path = new PropertyPath($groupBy);
$group = (String) $path->getValue($entity);
} catch (UnexpectedTypeException $e) {
// PropertyPath cannot traverse entity
}
}
if (empty($group)) {
$grouped[] = $entity;
} else {
$grouped[$group][] = $entity;
}
}
return $grouped;
}
/**
* Convert entities into choices with support for groups
*