[英]Symfony2 Entity Form Type gets data
我有2个实体:音频和目的地
在音频中:
/**
* @ORM\OneToOne(targetEntity="HearWeGo\HearWeGoBundle\Entity\Destination", inversedBy="audio")
* @Assert\NotBlank(message="This field must be filled")
*
*/
private $destination;
我创建了一个表单类型名称AddAudioType,用于将音频上传到数据库
<?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 AddAudioType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name','text')
->add('content','file')
->add('destination','entity',array('class'=>'HearWeGoHearWeGoBundle:Destination','property'=>'name'))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('data_class'=>"HearWeGo\\HearWeGoBundle\\Entity\\Audio"));
}
public function getName()
{
return 'add_audio';
}
}
?>
在控制器中
/**
* @Route("/admin/add/audio",name="add_audio")
*/
public function addAudioAction(Request $request)
{
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
return new Response('Please login');
}
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
$audio=new Audio();
$form=$this->createForm(new AddAudioType(),$audio,array(
'method'=>'POST',
'action'=>$this->generateUrl('add_audio')
));
$form->add('submit','submit');
if ($request->getMethod()=='POST')
{
$form->handleRequest($request);
if ($form->isValid())
{
$destination=$this->getDoctrine()->getRepository('HearWeGoHearWeGoBundle:Destination')
->findByName($form->get('destination')->getData()->getName());
$audio->setDestination($destination);
$name=$_FILES['add_audio']['name']['content'];
$tmp_name=$_FILES['add_audio']['tmp_name']['content'];
if (isset($name))
{
if (!empty($name))
{
$location=$_SERVER['DOCUMENT_ROOT']."/bundles/hearwegohearwego/uploads/";
move_uploaded_file($tmp_name,$location.$name);
$audio->setContent($location.$name);
$em=$this->getDoctrine()->getEntityManager();
$em->persist($audio);
$em->flush();
return new Response('Audio '.$audio->getName().' has been created!');
}
}
}
}
return $this->render('@HearWeGoHearWeGo/manage/addAudio.html.twig',array('form'=>$form->createView()));
}
在AddAudioType中,我声明了它以便从Destination实体表中获取所有记录,并允许用户选择其中之一,然后将其持久保存到数据库中
现在,我还需要处理其他事情:由于音频和目标之间的关系是一对一的,因此不允许用户选择已经出现在音频表中的目标。 现在,在AddAudioType中,我不想从Destination表中获取所有记录,而仅获取那些尚未出现在Audio表中的记录。 我该怎么办?
当您在表单生成器中执行操作时
->add('destination', 'entity', array(
'class'=>'HearWeGoHearWeGoBundle:Destination',
'property'=>'name'
));
你是说你想要所有可能的Destination
实体
如果要过滤它们,则有两种可能性
编写您自己的方法,以将已经“关联”的Destinations
排除到DestionationRepository
。 如果您不知道什么是存储库或不知道如何编写存储库,请参阅此文档 。 方法练习留给您作为练习(不,实际上,我不知道所有实体,所以我无法做出任何猜测)
完成此操作后,您必须将DestinationRepository
作为选项传递给表单(我想是必需的,我想[请参见下面的setRequired()
方法]),因此,类似这样的事情(我将省略无趣的代码)
//AddAudioType
<?php
[...]
public function buildForm(FormBuilderInterface $builder, array $options)
{
$destination_repo = $options['dr'];
$builder->[...]
->add('destination','entity',array(
'class'=>'HearWeGoHearWeGoBundle:Destination',
'choices'=> $destination_repo->yourCustomRepoFunctionName(),
'property'=>'name'));
}
$resolver->setRequired(array(
'dr',
));
现在,您已经为表单设置了所有内容,您需要将DestinationRepository
传递给表单。 你怎么样
确实很简单
//In controller you're instatiating your form
[...]
public function addAudioAction()
{
[...]
$destination_repo = $this->getDoctrine()
->getManager()
->getRepository('HearWeGoHearWeGoBundle:Destination');
$form=$this->createForm(new AddAudioType(), $audio, array(
'method' => 'POST',
'action' => $this->generateUrl('add_audio'),
'dr' => $destination_repo,
));
}
只要编写一个好的“过滤器”方法,它就会像魅力一样起作用(即:您用NOT IN
子句排除了将键添加到其他表中的所有Destinations
)
您只需将方法写入表单
//AddAudioType
use Doctrine\ORM\EntityRepository;
<?php
[...]
public function buildForm(FormBuilderInterface $builder, array $options)
{
$destination_repo = $options['dr'];
$builder->[...]
->add('destination','entity',array(
'class'=>'HearWeGoHearWeGoBundle:Destination',
'choices'=> function(EntityRepository $repository) use ($someParametersIfNeeded) {
return $repository->createQueryBuilder('d')
->[...];},
'property'=>'name'));
}
在第二种情况下, createQueryBuilder
也未实现,留给您。 您需要记住的一件事: choices
将需要查询生成器,所以不要调用->getQuery()
和->getResult()
public function findDestinationWithoutAudio() {
$query= "SELECT d
FROM HearWeGoHearWeGoBundle:Destination d
WHERE d NOT IN (SELECT IDENTITY(a.destination)
FROM HearWeGoHearWeGoBundle:Audio a)"
;
return $this->getEntityManager()->createQuery($query)->getResult();
}
如果您想知道为什么应该使用IDENTITY()
函数而不直接使用外键: http : //docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language .html#dql-functions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.