Reputation: 250
I want to display my Categories tree sort by names. I have a CategoryType to create new Category entity and assignate it a parent Category with a select box. Here's my form type :
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', TextType::class, array("required" => false));
$builder->add('parent', EntityType::class, array(
'class' => 'CAPShopAdminBundle:Category',
'choice_label' => 'selectBoxName',
'placeholder' => '-- Aucune --',
'required' => false,
'query_builder' => function(NestedTreeRepository $r) {
return $r->createQueryBuilder('c')
->orderBy('c.root, c.lvl, c.name', 'ASC');
}
));
$builder->add('save', SubmitType::class);
}
Here's the result :
I search this result :
Is it possible without PHP treatment, just with the good SQL query?
Upvotes: 0
Views: 1991
Reputation: 250
I think I've find a solution. I've rebuild my tree with a start from one and only root node. This structure is better, and then, when I insert a node in the tree, I execute the reorder() function from Gedmo tree Bundle.
/**
* @param Category $category
*/
public function saveCategory(Category $category)
{
if(!$category->getId()){ //insert
$this->objectManager->persist($category);
$this->objectManager->flush();
$root = $this->categoryRepository->findOneBySlug('pieces-automobile'); //The root node
$this->categoryRepository->reorder($root, 'name', 'ASC'); //Reoder by name
}
$category->setSlug($category->getId().'-'.$this->miscellaneous->slugify($category->getName(),'-'));
$this->objectManager->flush();
}
My tree will be pretty small, maybe 30 nodes maximum. So I can reoder the tree each time I insert a node. But be careful, because reorder() is a heavy function who can takes some times with big tree.
I get my tree without the root with :
/**
* @return bool
*/
public function getAllCategories(){
$root = $this->categoryRepository->findOneBySlug('pieces-automobile');
$htmlTree = $this->categoryRepository->childrenHierarchy(
$root, /* starting from root nodes */
false, /* true to take only direct children */
array(
'decorate' => true,
'representationField' => 'name',
'html' => true,
)
);
return $htmlTree;
}
And the result :
Upvotes: 1