Я пытаюсь редактировать запись в Symfony. Я могу редактировать текстовую запись, но я не могу редактировать новый файл в записи. ((Файл сохранен в хранилище, но не сохраняется в базе данных))
Как я могу это сделать в Symfony 3.4 с VichUploaderBundle 1.4 ... для вставки у меня нет проблем, я загружаю изображение в хранилище и сохраняю в базе данных .....
это мое действие редактирования
/**
* @Route("/Article/editArticle/{id}",name = "editArticle")
*/
public function editArticleAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$articleRepo=$em->getRepository('AdminBundle:Article');
$articleata = $articleRepo->find($id);
// $satelliteImage=new satelliteImage;
$article = new Article();
$form = $this->createForm(ArticleType::class,$article,array(
'action' => $this->generateUrl('editArticle',array('id' => $articleata->getId())),
'attr' => array(
'class' => 'dropzone',
'id' => "my-awesome-dropzone"
),
'method' => 'POST',
[
'name' => $articleata->getName(),
'title' => $articleata->getTitle(),
'subject' => $articleata->getSubject(),
'description' => $articleata->getDescription(),
'smallPic' => $articleata->getSmallPic(),
'largPic' => $articleata->getLargPic(),
'displayStatus' => $articleata->getDisplayStatus()]
));
//
if ($request->getMethod() == Request::METHOD_POST){
$form->handleRequest($request);
$article->setName($form->get('name')->getData());
$article->setTitle($form->get('title')->getData());
$article->setSubject($form->get('subject')->getData());
$article->setDescription($form->get('description')->getData());
$article->setDisplayStatus($form->get('displayStatus')->getData());
$article->setSmallPic($form->get('imageFile')->getData());
$article->setLargPic($form->get('imageFile2')->getData());
$em = $this->getDoctrine()->getManager();
$em->flush();
}
return $this->render('AdminBundle:Article:edit_article.html.twig', array(
'form' => $form->createView(),
'Articles' => $articleata
));
}
моя сущность
private $smallPic;
/**
* @Vich\UploadableField(mapping = "articles_images", fileNameProperty = "smallPic")
* @var File
*/
private $imageFile;
/**
* @ORM\Column(type = "datetime")
* @var \DateTime
*/
private $updatedAt;
/**
* @var string
*
* @ORM\Column(name = "largPic", type = "string", length=255)
*/
private $largPic;
/**
* @Vich\UploadableField(mapping = "articles_images", fileNameProperty = "largPic")
* @var File
*/
private $imageFile2;
public function setImageFile(File $smallPic = null)
{
$this->imageFile = $smallPic;
// VERY IMPORTANT:
// It is required that at least one field changes if you are using Doctrine,
// otherwise the event listeners won't be called and the file is lost
if ($smallPic) {
// if 'updatedAt' is not defined in your entity, use another property
$this->updatedAt = new \DateTime('now');
}
}
public function getImageFile()
{
return $this->imageFile;
}
public function setSmallPic($smallPic)
{
$this->smallPic = $smallPic;
}
public function getSmallPic()
{
return $this->smallPic;
}
public function setImageFile2(File $largPic = null)
{
$this->imageFile2 = $largPic;
// VERY IMPORTANT:
// It is required that at least one field changes if you are using Doctrine,
// otherwise the event listeners won't be called and the file is lost
if ($largPic) {
// if 'updatedAt' is not defined in your entity, use another property
$this->updatedAt = new \DateTime('now');
}
}
public function getImageFile2()
{
return $this->imageFile2;
}
/**
* Set largPic
*
* @param string $largPic
*
* @return Article
*/
public function setLargPic($largPic)
{
$this->largPic = $largPic;
}
/**
* Get largPic
*
* @return string
*/
public function getLargPic()
{
return $this->largPic;
}
.
.
.
FromType
->add('imageFile', VichFileType::class, array(
'label' => "smallpic",
'required' => false,
'allow_delete' => true, // not mandatory, default is true
'download_link' => true, // not mandatory, default is true
))
->add('imageFile2', VichFileType::class, array(
'label' => "largPic",
'required' => false,
'allow_delete' => true, // not mandatory, default is true
'download_link' => true, // not mandatory, default is true
))
config.yml
vich_uploader:
db_driver: orm
mappings:
articles_images:
uri_prefix: '%app.path.articles_images%'
upload_destination: '%kernel.root_dir%/../web/uploads/images/articles'
inject_on_load: true
delete_on_update: true
delete_on_remove: true






Перед смывом необходимо:
$em->persist($article);
ОБНОВЛЕНО:
В общем, VichUploader Bundle больше не считается лучшей практикой для загрузки изображений. Хранение данных изображений в БД действительно увеличивает их размер, и это не рекомендуется. У вас есть еще один объект, называемый media, с некоторыми полями, такими как hash, path, size и т.д ... и вы должны использовать файловую систему с абстракцией, если вы хотите перейти, например, на Amazon S3 или Google Storage в будущем.
Взгляните на потрясающий комплект flysystem, который использует библиотека flysystem.
Спасибо, Матиас. У меня нет времени менять собственную стратегию, поэтому сейчас я предпочитаю использовать VichUploaderBundle. Обязательно воспользуйтесь вашим предложением в следующем проекте.