Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Doctrine2 form EntityType

I'm looking for a way to extend Symfony 2 EntityType

Symfony\Bridge\Doctrine\Form\Type\EntityType

as in a new type extending this one, not creating a FormTypeExtension - and I can't figure it out. Does anyone know any proper way to do that?

I've tried simply extending it that way:

class NestedEntityType extends EntityType {

    public function getName() {
        return $this->getBlockPrefix();
    }

    public function getBlockPrefix() {
        return 'nested_entity';
    }
}

and then in sonata admin class I have:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('types', NestedEntityType::class, [
        'label' => false,
        'multiple' => true,
        'expanded' => true,
        'by_reference' => false
    ]);
}

but unfortunately it causes Fatal Error:

Catchable Fatal Error: Argument 1 passed to Symfony\Bridge\Doctrine\Form\Type\DoctrineType::__construct() must implement interface Doctrine\Common\Persistence\ManagerRegistry, none given, called in

I need to keep the whole functionality of EntityType, with one exception - the way it's presented. That's why I need to extend this type (I use it in other fields, so I can't just modify the template for it!).

I'm using Symfony 2.8 (just for the record).

like image 504
pzaj Avatar asked Apr 17 '26 12:04

pzaj


1 Answers

You should not extend it directly but use parent option

/**
 * {@inheritdoc}
 */
public function getParent()
{
    return EntityType::class;
}

So something like

class NestedEntityType extends AbstractType 
{

    public function getName() 
    {
        return $this->getBlockPrefix();
    }

    public function getBlockPrefix() 
    {
        return 'nested_entity';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return EntityType::class;
    }
}

That way if FormType you're extending from has something in injected (or setted) into constructor, you don't need to care as symfony will do it for you.

like image 197
DonCallisto Avatar answered Apr 20 '26 03:04

DonCallisto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!