如何将 symfony2 中的图片从表单添加到数据库。我想将徽标制作为图片字段并将项目图片从表单存储在数据库中。我该怎么做呢?
这是我的表格:
<?php
namespace Projects\ProjectsBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProjectsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('priority','choice', array(
'choices' => array('high' => 'high', 'low' => 'low', 'medium' => 'medium')))
->add('logo')
->add('startedAt','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
->add('completedOn','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
->add('createdDatetime','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
->add('updatedDatetime','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;')))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Projects\ProjectsBundle\Entity\Projects'
));
}
public function getName()
{
return 'projects_projectsbundle_projectstype';
}
}
这是我的控制器:
public function createAction(Request $request)
{
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
$entity = new Projects();
$form = $this->createForm(new ProjectsType(), $entity);
$form->bind($request);
$entity->setCreatedBy($userId);
$entity->setUpdatedBy($userId);
$entity->setCompletedBy($userId);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$_SESSION['projectid'] =$entity->getId();
if($request->isXmlHttpRequest()) {
$response = new Response();
$output = array('success' => true, 'description' => $entity->getdescription(), 'id' => $entity->getId(), 'name' => $entity->getname(), 'priority' => $entity->getpriority(), 'logo' => $entity->getlogo(), 'startedat' => $entity->getstartedat(),'completedon' => $entity->getcompletedon(),'completedby' => $entity->getCompletedBy(), 'createdby' => $entity->getcreatedby(), 'updatedby' => $entity->getupdatedby(), 'createddatetime' => $entity->getcreateddatetime(), 'updateddatetime' => $entity->getupdateddatetime());
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect($this->generateUrl('projects_show', array('id' => $entity->getId())));
}
return $this->render('ProjectsProjectsBundle:Projects:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}