我正在使用Symfony 2.8应用程序中的表单。
我有一个实体Object,该实体可以有一个或多个SubObjects。 这些子对象由属性 id 标识,但也由属性键标识。
默认情况下, id 属性中的值用于HTML(subObject .__ toString())。我想在。
中使用键属性我似乎无法找到如何做到这一点......
PS:我不能使用SubObject的__toString()方法,因为它已经用于其他目的......
我们将非常感谢您的想法。
<?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,
])
}
}
答案 0 :(得分:1)
我放弃了一个关于我如何在听众中做到这一点的快速伪代码,希望我理解你所追求的是什么。无论如何,这是一种普遍的方法。
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);
}
}