Last active
April 11, 2017 18:13
-
-
Save tnqsoft/518c202dd41863921f4029c051d344bf to your computer and use it in GitHub Desktop.
EntityType Tree Display For Symfony 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace CommonBundle\Form\Type; | |
use Doctrine\ORM\EntityRepository; | |
use Symfony\Component\OptionsResolver\Options; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
use Symfony\Component\OptionsResolver\OptionsResolverInterface; | |
use Symfony\Bridge\Doctrine\Form\Type\EntityType; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormView; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\Form\ChoiceList\View\ChoiceView; | |
/** | |
* @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com> | |
* TODO: Can not save with error data invalid | |
* | |
* Usage: | |
* use CommonBundle\Form\Type\TreeChoiceType; | |
* | |
* ->add('categories', TreeChoiceType::class, array( | |
* 'class' => 'CommonBundle:NewsCategory', | |
* 'multiple' => true, | |
* 'required' => true, | |
* 'label' => 'entity.news.categories', | |
* )) | |
*/ | |
class TreeChoiceType extends AbstractType | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildView(FormView $view, FormInterface $form, array $options) | |
{ | |
$choices = []; | |
foreach ($view->vars['choices'] as $choice) { | |
$choices[] = $choice->data; | |
} | |
$choices = $this->buildTreeChoices($choices); | |
$view->vars['choices'] = $choices; | |
} | |
/** | |
* Build Tree Choices | |
* | |
* @param array $choices | |
* @param integer $level | |
* @return array | |
*/ | |
protected function buildTreeChoices($choices, $level = 0) | |
{ | |
$result = array(); | |
foreach ($choices as $choice) { | |
$result[] = new ChoiceView( | |
$choice, | |
(string)$choice->getId(), | |
str_repeat('--', $level) . ' ' . $choice->getName(), | |
[] | |
); | |
if (!$choice->getChildren()->isEmpty()) { | |
$result = array_merge( | |
$result, | |
$this->buildTreeChoices($choice->getChildren(), $level + 1) | |
); | |
} | |
} | |
return $result; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$queryBuilder = function (Options $options) { | |
return function (EntityRepository $repository) use ($options) { | |
$qb = $repository->createQueryBuilder('e'); | |
$qb->where('e.parent IS NULL'); | |
return $qb; | |
}; | |
}; | |
$resolver->setDefaults([ | |
'query_builder' => $queryBuilder, | |
'expanded' => false, | |
]); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getParent() | |
{ | |
return EntityType::class; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment