Adding picture in symfony 2 from symfony form?
- by user2833510
How do I add a picture in symfony2 from form to a database. I want to make a logo as a picture field and store project picture in database from form. How do I do this?
Here is my form:
<?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';
}
}
and here is my controller:
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(),
));
}