I am using EntityType
field to create a multiple select dropdown. Also I want to query the available options based on user input (eg. standard
), and then display the options. For this, I am trying to inject EntityRepository into my TagType form itself, so that I can use it's CreateQueryBuilder
. But I get this error -
Here is my code, TagType.php
:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class TagType extends AbstractType {
protected $er;
public function __construct(EntityRepository $er)
{
$this->er = $er;
}
private function getTagsByCategoryName($categoryname, $er) {
return $er->createQueryBuilder('t')
->innerJoin('t.categories', 'c', 'WITH', 'c.categoryname = :categoryname')
->setParameter('categoryname', $categoryname)
->orderBy('t.id', 'ASC');
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('tagname', EntityType::class, array(
'class' => 'AppBundle:Tag',
'choices' => $this->getTagsByCategoryName('standard'),
'choice_label' => 'tagname',
'expanded' => false,
'multiple' => true,
'label' => 'Choose Tags',
));
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Tag',
'tags' => null,
));
}
}
Any ideas?
2 answers:
You don't need to inject EntityRepository
into your Form to use query_builder
option of EntityType
. EntityType
will inject the EntityRepository
on your behalf, you just need to define a method taking EntityRepository
as parameter. Knowing this:
class TagType extends AbstractType { private function getTagsByCategoryName($categoryname) { return function(EntityRepository $er) { return $er->createQueryBuilder('t') ->innerJoin('t.categories', 'c', 'WITH', 'c.categoryname = :categoryname') ->setParameter('categoryname', $categoryname) ->orderBy('t.id', 'ASC'); } } public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('tagname', EntityType::class, array( 'class' => 'AppBundle:Tag', 'choices' => $this->getTagsByCategoryName('standard'), 'choice_label' => 'tagname', 'expanded' => false, 'multiple' => true, 'label' => 'Choose Tags', )); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\\Entity\\Tag', 'tags' => null, )); } }
should be enough.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.