简体   繁体   中英

Symfony sonata EntityType edit form - select - get other that current

I have simple form generator field like this:

$formMapper->add('project',EntityType::class, [
            'class' => Project::class,
        ]);

It is field for select parent in tree data structure. It works very well in ADD, but in Edit i dont want to project with id X show as possible to select parent for project with id X

在此处输入图片说明

I am trying to use 'query_builder' property, but dont know how to catch id of current editing item from Admin class.

How to catch this id or simplest exclusion id of current editing item in select?

I suppose your FormType is mapped on your edited item. Therefore, you could go with something like (class / fields / entity names to be replaced by yours) :

use Doctrine\ORM\EntityRepository;
class ProjectFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $currentId = $builder->getData()->getId();
        $builder->add('project', EntityType::class, array(
            'class' => Project::class,     
            'query_builder' => function (EntityRepository $er) use ($currentId) {
                return $er->createQueryBuilder('p')
                           ->where('p.id != :idCurrent')
                           ->setParameter('idCurrent', $currentId);
             },  
       ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Project::class,
        ));
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM