我有2个实体:音频和目的地
在音频中:
/**
* @ORM\OneToOne(targetEntity="HearWeGo\HearWeGoBundle\Entity\Destination", inversedBy="audio")
* @Assert\NotBlank(message="This field must be filled")
*
*/
private $destination;
我创建了一个表单类型名称EditAudioType,用于编辑上传链接存储在数据库中的音频
<?php
namespace HearWeGo\HearWeGoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use HearWeGo\HearWeGoBundle\Entity\Audio;
class AudioAudioType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$destination_repo=$options['dr'];
$builder
->add('name','text')
->add('audio','file')
->add('destination','entity',array(
'class'=>'HearWeGoHearWeGoBundle:Destination',
'choices'=>$destination_repo->findToReplaceAudio('id'),
'property'=>'name'
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('data_class'=>"HearWeGo\\HearWeGoBundle\\Entity\\Audio"));
$resolver->setRequired(array('dr'));
}
public function getName()
{
return 'edit_audio';
}
}
我在旧帖子中做了类似的答案: Symfony2 Entity Form Type gets data
但是现在我不知道我将在choices
形式的属性中放什么,因为这个自定义repo函数有参数,而不是旧的答案。在DestinationRepository
:
public function findByAudioId($id)
{
return $this->getEntityManager()->createQuery('SELECT d FROM HearWeGoHearWeGoBundle:Destination d,HearWeGoHearWeGoBundle:Audio a WHERE d.id=IDENTITY (a.destination)')->getResult();
}
public function findToReplaceAudio($id)
{
$result=$this->findDestinationWithoutAudio();
$result[]=$this->findByAudioId($id);
return $result;
}
答案 0 :(得分:1)
我会做类似的事情:
<?php
namespace HearWeGo\HearWeGoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use HearWeGo\HearWeGoBundle\Entity\Audio;
use HearWeGo\HearWeGoBundle\Entity\Repository\AudioRepository;
class AudioAudioType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name','text')
->add('audio','file')
->add('destination','entity',array(
'class'=>'HearWeGoHearWeGoBundle:Destination',
'query_builder'=>function (AudioRepository $repository) {
return $repository->findToReplaceAudioQueryBuilder('id');
},
'property' => 'name'
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('data_class'=>"HearWeGo\\HearWeGoBundle\\Entity\\Audio"));
}
public function getName()
{
return 'edit_audio';
}
}