我想在表單中使用實體類型的選擇列表,但如果向表單中添加數據,它不起作用。它給了我一個「無法將對象轉換爲int」的錯誤。使用ChoiceList實體類型
我buildForm方法
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('department', 'entity', array(
'label' => 'Form.department',
'class' => 'HotfloSystemCoreBundle:Department',
'choice_list' => $this->departmentChoiceList,
'multiple' => true,
'required' => false,
'attr' => array(
'class' => 'selectpicker',
'data-actions-box' => true,
'data-live-search' => true,
'data-selected-text-format' => 'count'
),
'horizontal' => false,
));
}
我的選擇列表
class DepartmentChoiceList extends LazyChoiceList
{
/**
* @var EntityManager
*/
protected $em;
public function __construct($em)
{
$this->em = $em;
}
/**
* Loads the choice list
* Should be implemented by child classes.
*
* @return ChoiceListInterface The loaded choice list
*/
protected function loadChoiceList()
{
$departments = $this->getDepartments();
$departmentChoices = [];
foreach ($departments as $department) {
$departmentChoices[$department->getId()] = $department;
}
// Return the choice list
return new SimpleChoiceList($departmentChoices);
}
/**
* Get the departments available in the poli appointment data
*
* @return Department[]
*/
protected function getDepartments()
{
// Get the used department out of the appointment table by using a group by SQL statement
/** @var $qb QueryBuilder */
$qb = $this->em->getRepository('MyBundle:PoliAnalyzeAppointment')
->createQueryBuilder('appointment');
$qb->select('DISTINCT IDENTITY(appointment.department)');
// Get the actual departments
/** @var $qb2 QueryBuilder */
$qb2 = $this->em->getRepository('MyBundle:Department')
->createQueryBuilder('department');
$qb2->where($qb2->expr()->in('department.id', $qb->getDQL()));
$qb2->orderBy('department.name', 'ASC');
return $qb2->getQuery()->getResult();
}
}
我使用的實體類型,因爲它應該被轉換爲一個實體和背部。如果我使用選擇類型,我必須自己做(我不想)。
我該如何做到這一點?
該解決方案解決了我的問題!我沒有使用innerJoin,因爲它很慢,所以我在表單中插入了實體管理器,因此我可以做一些額外的查詢。 – 2014-10-09 08:09:54