ivodvb
ivodvb

Reputation: 1164

Symfony 2.8 form entity type custom property

I'm working on a form in a Symfony 2.8 application.

I have an entity Object and that entity can have one or more SubObjects. Those SubObjects are identified by the property id, but also by the property key.

By default the value from the id property is used in the HTML (subObject.__toString()). I want to use the property key in the .

I can't seem to find how to do this...

PS: I can't use the __toString() method of the SubObject, because that's already in use for some other purposes...

Ideas would be greatly appreciated.

<?php

namespace My\Bundle\ObjectBundle\Form\Type\Object;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class ObjectType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('code', TextType::class, [
                'required' => true,
            ])
            ->add('subObjects', EntityType::class, [
                'class'    => 'My\Bundle\ObjectBundle\Entity\SubObject',
                'multiple' => true,
            ])
    }
}

Upvotes: 0

Views: 629

Answers (1)

Richard
Richard

Reputation: 4119

I chucked up a quick pseudocode of how I'd do this in a listener, hopefully I understood what you're after. It's a general approach anyway.

class ResolveSubObjectSubscriber implements EventSubscriberInterface {

    /** @var  EntityManager */
    private $entityManager;

    public function __construct(FormFactoryInterface $factory, EntityManager $entityManager) {

        $this->factory = $factory;
        $this->entityManager = $entityManager;
    }

    public static function getSubscribedEvents() {
        return array(FormEvents::POST_SET_DATA => 'resolveSubObject');
    }

    /**
     *  Resolve sub objects based on key
     *
     * @param FormEvent $event
     */
    public function resolveSubObject(FormEvent $event) {

        $data = $event->getData();
        $form = $event->getForm();

        // don't care if it's not a sub object
        if (!$data instanceof SubObject) {
            return;
        }

        /** @var SubObject $subObject */
        $subObject = $data;

        // here you do whatever you need to do to populate the object into the sub object based on key

        $subObjectByKey = $this->entityManager->getRepository('SomeRepository')->findMySubObject($subObject->getKey());
        $subObject->setObject($subObjectByKey);
   }
}

Upvotes: 1

Related Questions