如何从DB中获取所有值parent_id
?
$category = $this->getSubject();
protected function configureFormFields(FormMapper $formMapper)
{
$fieldOptions = array(); //how get all value `parent_id` from DB
$formMapper->add('parent_id', ChoiceType::class, array(
'expanded' => true,
'multiple' => false,
'choices' => $fieldOptions,
'data' => $category->parent_id
));
}
如果"parent"是一个实体(可能是Category
(,您可能需要查看EntityType。否则,您的代码需要更多的上下文。该片段位于哪个类或文件中?
答案:
class CategoryAdmin extends AbstractAdmin
{
$category = $this->getSubject();
protected function configureFormFields(FormMapper $formMapper)
{
$em = $this->modelManager->getEntityManager(Category::class);
$fieldOptions = $em->getRepository(Category::class)->getChoiceParentId();
$formMapper->add('parent_id', ChoiceType::class, array(
'multiple' => false,
'choices' => array_flip($fieldOptions),
'data' => $category->parent_id
));
}
}
class CategoryRepository extends ServiceEntityRepository
{
public function getChoiceParentId()
{
$categories = $this->createQueryBuilder('c')
->select('c.id, c.name')
->getQuery()
->getResult();
$choice_parent_id = [0 => 'Empty'];
foreach ($categories as $category) {
$choice_parent_id[$category['id']] = $category['name'];
}
return $choice_parent_id;
}
}