I'm following this tutorial http://symfony.com/doc/current/controller/upload_file.html but the $file isn't being converted to an UploadedFile, it stays as a string:
var_dump($file);
/home/owner/Desktop/Workspace/Documentary/src/DW/DocumentaryBundle/Controller/Admin/DocumentaryController.php:103:string '/tmp/phpmmv1LP' (length=14)
Type error: Argument 1 passed to DW\DocumentaryBundle\Uploader\PosterUploader::upload() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, called in /home/owner/Desktop/Workspace/DocumentaryWIRE/src/DW/DocumentaryBundle/Controller/Admin/DocumentaryController.php on line 106
Create Action:
/**
* #param Request $request
* #return Response
*/
public function createAction(Request $request)
{
$documentary = new Documentary();
$form = $this->createForm(DocumentaryType::class, $documentary);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $documentary->getPoster();
$posterUploader = $this->getPosterUploader();
$fileName = $posterUploader->upload($file);
$documentary->setPoster($fileName);
$documentaryService = $this->getDocumentaryService();
$documentaryService->save($documentary);
}
return $this->render('DocumentaryBundle:Admin:create.html.twig', array(
'form' => $form->createView(),
));
}
View
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Form:
<?php
namespace DW\DocumentaryBundle\Form;
use DW\DocumentaryBundle\Entity\Documentary;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DocumentaryType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class)
->add('storyline', TextareaType::class)
->add('summary', TextareaType::class)
->add('year', IntegerType::class)
->add('length', IntegerType::class)
->add('status', TextType::class)
->add('views', IntegerType::class)
->add('shortUrl', TextType::class)
->add('videoId', TextType::class)
->add('videoSource', TextType::class)
->add('poster', FileType::class, [
'label' => 'Poster'])
->add('category', EntityType::class, [
'class' => 'CategoryBundle:Category',
'choice_label' => 'name',
])
->add('submit', SubmitType::class);
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Documentary::class,
));
}
/**
* #return string
*/
public function getName()
{
return "documentary";
}
}
Controller:
<?php
namespace DW\DocumentaryBundle\Uploader;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class PosterUploader
{
/**
* #var string
*/
private $targetDir;
/**
* #param string $targetDir
*/
public function __construct(string $targetDir)
{
$this->targetDir = $targetDir;
}
/**
* #param UploadedFile $file
* #return string
*/
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->targetDir, $fileName);
return $fileName;
}
}
The documentation is NOT wrong! They don't use type hinting in their example:
// src/AppBundle/Entity/Product.php
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
When you use string type hinting then UploadedFile::__toString() will be invoked!
So check your entity. It should be something like this:
public function setPoster($poster)
{
// ...
}
To get a file from request, in Symfony, you need to get $request->files. For example $request->files->get('file_name');.
The documentation is wrong, it should be: $file = $form->get('poster')->getData();
/**
* #param Request $request
* #return Response
*/
public function createAction(Request $request)
{
$documentary = new Documentary();
$form = $this->createForm(DocumentaryType::class, $documentary);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('poster')->getData();
$posterUploader = $this->getPosterUploader();
$fileName = $posterUploader->upload($file);
$documentary->setPoster($fileName);
$documentaryService = $this->getDocumentaryService();
$documentaryService->save($documentary);
}
return $this->render('DocumentaryBundle:Admin:create.html.twig', [
'form' => $form->createView(),
]);
}
Related
Hello i can't find the error when i try to delete something out of my database.
It says that my namespace is wrong but i really cant find any issues.
Here is the action im calling
/**
* #Route("/delete/{id}", name="delete")
* #param $id
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function deleteById($id)
{
$em = $this->getDoctrine()->getManager();
$entries = $em->getRepository(Database_InteractionType::class)->find($id);
$em->remove($entries);
$em->flush();
return $this->redirectToRoute('show');
}
Here is Entitiy and my Form.
I have been looking at it for 2 hours straight and i cant seem to find the Iusse..
Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\Database_InteractionRepository")
*/
class Database_Interaction
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $question;
/**
* #ORM\Column(type="string", length=255)
*/
private $answer;
public function getId(): ?int
{
return $this->id;
}
public function getQuestion(): ?string
{
return $this->question;
}
public function setQuestion(string $question): self
{
$this->question = $question;
return $this;
}
public function getAnswer(): ?string
{
return $this->answer;
}
public function setAnswer(string $answer): self
{
$this->answer = $answer;
return $this;
}
}
My Form:
<?php
namespace App\Form;
use App\Entity\Database_Interaction;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class Database_InteractionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'question',
TextType::class,
[
'attr' => [
'placeholder' => 'Enter your Question',
'class' => 'form-control'
],
'required' => true
]
)
->add(
'answer',
TextType::class,
[
'required' => true,
'attr' => [
'class' => 'form-control',
'placeholder' => 'Enter your Answer',
]
]
)
->add(
'save',
SubmitType::class,
[
'attr' => [
'class' => 'btn btn-primary'
]
]
)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Database_Interaction::class,
]);
}
}
And my Repository if this is to any help..
<?php
namespace App\Repository;
use App\Entity\Database_Interaction;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* #method Database_Interaction|null find($id, $lockMode = null, $lockVersion = null)
* #method Database_Interaction|null findOneBy(array $criteria, array $orderBy = null)
* #method Database_Interaction[] findAll()
* #method Database_Interaction[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class Database_InteractionRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Database_Interaction::class);
}
/**
* #param string $id
* #return Database_Interaction|null
*/
public function findById(string $id)
{
return $this->findOneBy(
['id' => $id]
);
}
// /**
// * #return SubmitNew[] Returns an array of SubmitNew objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('s')
->andWhere('s.exampleField = :val')
->setParameter('val', $value)
->orderBy('s.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?SubmitNew
{
return $this->createQueryBuilder('s')
->andWhere('s.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
If anyone could help me out I don't know where to look anymore...
Thank you
Look closely at this line:
$entries = $em->getRepository(Database_InteractionType::class)->find($id);
This refers to the form type class(App\Form\Database_InteractionType) not your persisted entity class, which lives in App\Entity namespace (the namespace it is looking in), this is why the error is produced. Forms do not have a repository, the related entity does.
Try this:
$entries = $em->getRepository(Database_Interaction::class)->find($id);
I'm saving a date with Symfony 3 and the bootstrap-datepicker.
If I fill out my form I expect it to save a date, 04/25/2017 in this case.
What I want in my datatabse is this: 04/25/2017.
Instead I get this in my dump:
2017-01-25 00:04.000000
and in my database:
2017-01-25
Dump result:
Database value:
PlayLogController:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\PlayLog;
use AppBundle\Entity\Game;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
/**
* Playlog controller.
*
* #Route("playlog")
*/
class PlayLogController extends Controller
{
/**
* Lists all playLog entities.
*
* #Route("/", name="playlog_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$playLogs = $em->getRepository('AppBundle:PlayLog')->findAll();
return $this->render('playlog/index.html.twig', array(
'playLogs' => $playLogs,
));
}
/**
* Creates a new playLog entity.
*
* #Route("/{gameId}/new", name="playlog_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request, $gameId)
{
$playlog = new PlayLog();
$em = $this->getDoctrine()->getManager();
$game = $em ->getRepository(Game::class)->find($gameId);
$playlog->setGame($game);
$form = $this->createForm('AppBundle\Form\PlayLogType', $playlog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/* #var $playLog PlayLog */
$playlog = $form->getData();
// echo $playlog->getGame()->getId() .'!';
$em->persist($playlog);
$em->flush();
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playlog,
'form' => $form->createView(),
));
}
/**
* Finds and displays a playLog entity.
*
* #Route("/{id}", name="playlog_show")
* #Method("GET")
*/
public function showAction(PlayLog $playLog)
{
$deleteForm = $this->createDeleteForm($playLog);
return $this->render('playlog/show.html.twig', array(
'playLog' => $playLog,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing playLog entity.
*
* #Route("/{id}/edit", name="playlog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, PlayLog $playLog)
{
$deleteForm = $this->createDeleteForm($playLog);
$editForm = $this->createForm('AppBundle\Form\PlayLogType', $playLog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('playlog_edit', array('id' => $playLog->getId()));
}
return $this->render('playlog/edit.html.twig', array(
'playLog' => $playLog,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a playLog entity.
*
* #Route("/{id}", name="playlog_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, PlayLog $playLog)
{
$form = $this->createDeleteForm($playLog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($playLog);
$em->flush();
}
return $this->redirectToRoute('playlog_index');
}
/**
* Creates a form to delete a playLog entity.
*
* #param PlayLog $playLog The playLog entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(PlayLog $playLog)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('playlog_delete', array('id' => $playLog->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
PlayLogType:
<?php
namespace AppBundle\Form;
use AppBundle\Entity\PlayLog;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PlayLogType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('date', DateType::class, array(
'widget' => 'single_text',
'html5' => false,
'attr' => ['class' => 'js-datepicker'],
'format' => 'mm/dd/yyyy'
)
);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => PlayLog::class
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_playlog';
}
}
The script I use for the datepicker:
<script type="text/javascript">
$(document).ready(function () {
$('.js-datepicker').datepicker({
format: 'mm/dd/yyyy'
});
});
</script>
Format must be 'MM/dd/yyyy'. mm are minutes, which is why the time is 00:04 in your record.
The date/time format that you send to the server is going to depend on the locale that the server is in. Since I see Europe/Berlin in your screenshot above that means it's expecting the date/time to come in as d/m/Y (php format).
Alternatively the best way to eliminate all the date/time formats is to send it in either YYYY-MM-DD H:i:s format (H:i:s can be omitted if you don't care about time), or as a unix timestamp which is guaranteed to be in UTC time..
I am trying to create a form using Symfony and Doctrine.
I created a Job class, and a table in mysql which relates to it, using Doctrine. It also made the JobType and JobController, and Routing facility.
I can access the index page, where the jobs are listed, but can't access the new entry page.
Here are the files used for creating the forms.
JobController.php
<?php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\Job;
use AppBundle\Form\JobType;
/**
* Job controller.
*
* #Route("/job")
*/
class JobController extends Controller
{
/**
* Lists all Job entities.
*
* #Route("/", name="job_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$jobs = $em->getRepository('AppBundle:Job')->findAll();
return $this->render('job/index.html.twig', array(
'jobs' => $jobs,
));
}
/**
* Creates a new Job entity.
*
* #Route("/new", name="job_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$job = new Job();
$jobType = new JobType();
$form = $this->createForm($jobType, $job);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($job);
$em->flush();
return $this->redirectToRoute('job_show', array('id' => $job->getId()));
}
return $this->render('job/new.html.twig', array(
'job' => $job,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Job entity.
*
* #Route("/{id}", name="job_show")
* #Method("GET")
*/
public function showAction(Job $job)
{
$deleteForm = $this->createDeleteForm($job);
return $this->render('job/show.html.twig', array(
'job' => $job,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Job entity.
*
* #Route("/{id}/edit", name="job_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Job $job)
{
$deleteForm = $this->createDeleteForm($job);
$editForm = $this->createForm(new JobType(), $job);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($job);
$em->flush();
return $this->redirectToRoute('job_edit', array('id' => $job->getId()));
}
return $this->render('job/edit.html.twig', array(
'job' => $job,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Job entity.
*
* #Route("/{id}", name="job_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Job $job)
{
$form = $this->createDeleteForm($job);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($job);
$em->flush();
}
return $this->redirectToRoute('job_index');
}
/**
* Creates a form to delete a Job entity.
*
* #param Job $job The Job entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Job $job)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('job_delete', array('id' => $job->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
JobType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class JobType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', 'string')
->add('type', 'string')
->add('company', 'string')
->add('logo', 'string')
->add('url', 'string')
->add('position', 'string')
->add('location', 'string')
->add('desciption', 'text')
->add('how_to_apply', 'text')
->add('token', 'string')
->add('is_public', 'boolean')
->add('is_activated', 'boolean')
->add('email', 'string')
->add('expires_at', 'datetime')
->add('created_at', 'datetime')
->add('updated_at', 'datetime')
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Job'
));
}
/**
* Mandatory in Symfony2
* Gets the unique name of this form.
* #return string
*/
public function getName()
{
return 'add_job';
}
}
This is the error I receive
Thanks!
EDIT:
The content of app/config/services.yml
parameters:
# parameter_name: value
services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["#another_service_name", "plain_value", "%parameter_name%"]
$editForm = $this->createForm(new JobType(), $job);
This is no longer possible in Symfony 3. In Symfony 3, you always have to pass the fully-qualified class name for form types:
$editForm = $this->createForm(JobType::class, $job);
Also, in your form type you're passing the type name instead of the FQCN of the type classes.
Symfony 3 has just released its first BETA, which means it's very bleeding edge. Also, there are almost zero tutorials for Symfony 3 yet (as it's so extremely bleeding edge). You're reading a Symfony 2 tutorial, so I recommend you to install Symfony 2 instead of 3.
I am trying to validate a form in Symfony 2.3. I need to get the current User id and submit in my database.
My controller :
public function giftcardAction(Request $request)
{
$giftcard = new Giftcard();
$giftcard->setDate(new \DateTime());
$user = $this->container->get('security.context')->getToken()->getUser();
$userId = $user->getId();
var_dump($userId);
$form = $this->createFormBuilder($giftcard)
->add('amount', 'integer')
->add('onBehalfOf')
->add('towards')
->add('message', 'text')
// ->add($userId)
->add('submit', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($giftcard);
$em->flush();
}else{
throw new NotFoundHttpException("Page not found");
}
}
return $this->render('FrontBundle:Forms:giftcard.html.twig', array(
'form' => $form->createView(),
));
}
My FormType
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class GiftCardType extends AbstractType
{
private $userId;
public function __construct(array $userId)
{
$this->userId = $userId;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date')
->add('onBehalfOf')
->add('towards')
->add('message')
// ->add('UserId')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Front\Bundle\Entity\GiftCard',
));
}
/**
* #return string
*/
public function getName()
{
return 'front_bundle_giftcard';
}
}
At the moment i can get the user id in var_dump in the controller. But how I can pass the variable in the form. Has anyone may help me. Thank you.
I'm using Symfony2.
I have an entity Post that has a title and a picture field.
My problem : Everything is fine when I create a post, I have my picture etc. But when I want to modify it, I have a problem with the "picture" field which is an uploaded file, Symfony wants a file type and it has a string (the path of the uploaded file) :
The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.
I'm really stuck with this problem and really don't know how to solve it, any help would be greatly appreciated! Thanks a lot!
Here is my PostType.php (which is used in newAction() and modifiyAction()) and which may cause the problem (Form/PostType.php) :
<?php
namespace MyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use MyBundle\Entity\Post;
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('picture', 'file');//there is a problem here when I call the modifyAction() that calls the PostType file.
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'MyBundle\Entity\Post',
);
}
public static function processImage(UploadedFile $uploaded_file, Post $post)
{
$path = 'pictures/blog/';
//getClientOriginalName() => Returns the original file name.
$uploaded_file_info = pathinfo($uploaded_file->getClientOriginalName());
$file_name =
"post_" .
$post->getTitle() .
"." .
$uploaded_file_info['extension']
;
$uploaded_file->move($path, $file_name);
return $file_name;
}
public function getName()
{
return 'form_post';
}
}
Here is my Post entity (Entity/Post.php) :
<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* MyBundle\Entity\Post
*
* #ORM\Table()
* #ORM\Entity
*/
class Post
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Image(
* mimeTypesMessage = "Not valid.",
* maxSize = "5M",
* maxSizeMessage = "Too big."
* )
*/
private $picture;
/**
* #var string $title
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
//getters and setters
}
Here is my newAction() (Controller/PostController.php) Every works fine with this function:
public function newAction()
{
$em = $this->getDoctrine()->getEntityManager();
$post = new Post();
$form = $this->createForm(new PostType, $post);
$post->setPicture("");
$form->setData($post);
if ($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest(), $post);
if ($form->isValid())
{
$uploaded_file = $form['picture']->getData();
if ($uploaded_file)
{
$picture = PostType::processImage($uploaded_file, $post);
$post->setPicture('pictures/blog/' . $picture);
}
$em->persist($post);
$em->flush();
$this->get('session')->setFlash('succes', 'Post added.');
return $this->redirect($this->generateUrl('MyBundle_post_show', array('id' => $post->getId())));
}
}
return $this->render('MyBundle:Post:new.html.twig', array('form' => $form->createView()));
}
Here is my modifyAction() (Controller/PostController.php) :There is a problem with this function
public function modifyAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$post = $em->getRepository('MyBundle:Post')->find($id);
$form = $this->createForm(new PostType, $post);//THIS LINE CAUSES THE EXCEPTION
if ($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest(), $post);
if ($form->isValid())
{
$uploaded_file = $form['picture']->getData();
if ($uploaded_file)
{
$picture = PostType::processImage($uploaded_file, $post);
$post->setPicture('pictures/blog/' . $picture);
}
$em->persist($post);
$em->flush();
$this->get('session')->setFlash('succes', 'Modifications saved.');
return $this->redirect($this->generateUrl('MyBundle_post_show', array('id' => $post->getId())));
}
}
return $this->render('MyBundle:Post:modify.html.twig', array('form' => $form->createView(), 'post' => $post));
}
I solved the problem setting data_class to null as follows:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('picture', 'file', array('data_class' => null)
);
}
I would recommend you to read the documentation of file upload with Symfony and Doctrine How to handle File Uploads with Doctrine and a strong recommendation to the part Lifecycle callbacks
In a brief you usually in the form use the 'file' variable (see documentation), you can put a different label through the options, then in your 'picture' field, you just store the name of the file, because when you need the src file you can just call getWebpath() method.
->add('file', 'file', array('label' => 'Post Picture' )
);
to call in your twig template
<img src="{{ asset(entity.webPath) }}" />
Please make below change in your PostType.php.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('picture', 'file', array(
'data_class' => 'Symfony\Component\HttpFoundation\File\File',
'property_path' => 'picture'
)
);
}