Answer the question
In order to leave comments, you need to log in
Symfony, How to correctly update an entity that has a field of type "File"?
I welcome everyone! I'm learning Symfony
The problem is this, there is a Task entity that has properties
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Task
*
* @ORM\Table(name="task")
* @ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository")
*/
class Task
{
/**
* @ORM\Column(type="string", nullable=true)
*/
private $originalFileName;
/**
* @ORM\Column(type="string", nullable=true)
*/
private $fileName;
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class TaskType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('taskName',TextType::class)
->add('fileName', FileType::class, array('label' => 'Документ'))
;
}/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Task'
));
}
Answer the question
In order to leave comments, you need to log in
In the presented code, the fileName property should be overwritten, because you have it specified in the TaskType form. Generally speaking, an UploadedFile instance should be stored in it (or null if the field was not filled when the form was submitted), and your annotation indicates that this is a string field.
You don't need to "map" the file field into an entity (specify 'mapped' => false):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('taskName',TextType::class)
->add('file', FileType::class, [ 'mapped' => false, 'label' => 'Документ'])
;
}
$uploadedFile = $form['file']->getData();
$fileName = 'myfile.txt';
$uploadedFile->move('public/uploads', $fileName);
$task->setFileName('public/uploads/'.$fileName);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question