Symfony - Как получить изображение, хранящееся в базе данных, в моей форме обновления?

Как получить изображение, хранящееся в базе данных, в моей форме обновления?

Я создал такую ​​сущность Profile:

<?php

namespace Krown\DashboardBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
use Krown\DashboardBundle\Entity\Status;
use Krown\DashboardBundle\Entity\Picture;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Profile
 *
 * @ORM\Table(name="profile")
 * @ORM\Entity(repositoryClass="Krown\DashboardBundle\Repository\ProfileRepository")
 * @Vich\Uploadable
 */
class Profile
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
     *
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $imageName;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
    * @var boolean
    *
    * @ORM\Column(name="avocat", type="boolean")
    */
    private $avocat;


    /**
    * @var string
    *
    * @ORM\Column(name="breve_description", type="string", nullable=true)
    */
    protected $breve_description;

    /**
    * @var array
    *
    * @ORM\Column(name="fields_of_law", type="array", nullable=true)
    */
    protected $fields_of_law;

    /**
    * @var string
    *
    * @ORM\Column(name="registre_ou_bareau", type="string", nullable=true)
    */
    protected $registre_ou_bareau;

    /**
    * @var string
    *
    * @ORM\Column(name="canton_actif", type="string", nullable=true)
    */
    protected $canton_actif;

    /**
    * @var string
    *
    * @ORM\Column(name="annee_obtention_brevet", type="string", nullable=true)
    */
    protected $annee_obtention_brevet;

    /**
    * @var string
    *
    * @ORM\Column(name="titre_supplementaire", type="string", nullable=true)
    */
    protected $titre_supplementaire;

    /**
    * @var string
    *
    * @ORM\Column(name="years_of_experience", type="string", nullable=true)
    */
    protected $years_of_experience;

    /**
    * @var string
    *
    * @ORM\Column(name="langues_de_travail", type="string", nullable=true)
    */
    protected $langues_de_travail;

    /**
    * @var string
    *
    * @ORM\Column(name="email_contact", type="string", nullable=true)
    */
    protected $email_contact;

    /**
    * @var string
    *
    * @ORM\Column(name="numero_telephone", type="string", nullable=true)
    */
    protected $numero_telephone;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="body", type="text")
     */
    private $body;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_date", type="datetime")
     */
    private $createdDate;

    /**
    * @ORM\OneToOne(targetEntity="User")
    * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
    */
    protected $user;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Profile
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set body
     *
     * @param string $body
     *
     * @return Profile
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    /**
     * Get body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Set createdDate
     *
     * @param \DateTime $createdDate
     *
     * @return Profile
     */
    public function setCreatedDate($createdDate)
    {
        $this->createdDate = $createdDate;

        return $this;
    }

    /**
     * Get createdDate
     *
     * @return \DateTime
     */
    public function getCreatedDate()
    {
        return $this->createdDate;
    }

    /**
     * Set user
     *
     * @param \Krown\DashboardBundle\Entity\User $user
     *
     * @return Profile
     */
    public function setUser(\Krown\DashboardBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Krown\DashboardBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Product
     */

    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // 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
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * Set imageName
     *
     * @param string $imageName
     *
     * @return Profile
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * Get imageName
     *
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     * @return Profile
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set avocat
     *
     * @param boolean $avocat
     *
     * @return Profile
     */
    public function setAvocat($avocat)
    {
        $this->avocat = $avocat;

        return $this;
    }

    /**
     * Get avocat
     *
     * @return boolean
     */
    public function getAvocat()
    {
        return $this->avocat;
    }

    /**
     * Set breveDescription
     *
     * @param string $breveDescription
     *
     * @return Profile
     */
    public function setBreveDescription($breveDescription)
    {
        $this->breve_description = $breveDescription;

        return $this;
    }

    /**
     * Get breveDescription
     *
     * @return string
     */
    public function getBreveDescription()
    {
        return $this->breve_description;
    }

    /**
     * Set fieldsOfLaw
     *
     * @param array $fieldsOfLaw
     *
     * @return Profile
     */
    public function setFieldsOfLaw($fieldsOfLaw)
    {
        $this->fields_of_law = $fieldsOfLaw;

        return $this;
    }

    /**
     * Get fieldsOfLaw
     *
     * @return array
     */
    public function getFieldsOfLaw()
    {
        return $this->fields_of_law;
    }

    /**
     * Set registreOuBareau
     *
     * @param string $registreOuBareau
     *
     * @return Profile
     */
    public function setRegistreOuBareau($registreOuBareau)
    {
        $this->registre_ou_bareau = $registreOuBareau;

        return $this;
    }

    /**
     * Get registreOuBareau
     *
     * @return string
     */
    public function getRegistreOuBareau()
    {
        return $this->registre_ou_bareau;
    }

    /**
     * Set cantonActif
     *
     * @param string $cantonActif
     *
     * @return Profile
     */
    public function setCantonActif($cantonActif)
    {
        $this->canton_actif = $cantonActif;

        return $this;
    }

    /**
     * Get cantonActif
     *
     * @return string
     */
    public function getCantonActif()
    {
        return $this->canton_actif;
    }

    /**
     * Set anneeObtentionBrevet
     *
     * @param string $anneeObtentionBrevet
     *
     * @return Profile
     */
    public function setAnneeObtentionBrevet($anneeObtentionBrevet)
    {
        $this->annee_obtention_brevet = $anneeObtentionBrevet;

        return $this;
    }

    /**
     * Get anneeObtentionBrevet
     *
     * @return string
     */
    public function getAnneeObtentionBrevet()
    {
        return $this->annee_obtention_brevet;
    }

    /**
     * Set titreSupplementaire
     *
     * @param string $titreSupplementaire
     *
     * @return Profile
     */
    public function setTitreSupplementaire($titreSupplementaire)
    {
        $this->titre_supplementaire = $titreSupplementaire;

        return $this;
    }

    /**
     * Get titreSupplementaire
     *
     * @return string
     */
    public function getTitreSupplementaire()
    {
        return $this->titre_supplementaire;
    }

    /**
     * Set yearsOfExperience
     *
     * @param string $yearsOfExperience
     *
     * @return Profile
     */
    public function setYearsOfExperience($yearsOfExperience)
    {
        $this->years_of_experience = $yearsOfExperience;

        return $this;
    }

    /**
     * Get yearsOfExperience
     *
     * @return string
     */
    public function getYearsOfExperience()
    {
        return $this->years_of_experience;
    }

    /**
     * Set languesDeTravail
     *
     * @param string $languesDeTravail
     *
     * @return Profile
     */
    public function setLanguesDeTravail($languesDeTravail)
    {
        $this->langues_de_travail = $languesDeTravail;

        return $this;
    }

    /**
     * Get languesDeTravail
     *
     * @return string
     */
    public function getLanguesDeTravail()
    {
        return $this->langues_de_travail;
    }

    /**
     * Set emailContact
     *
     * @param string $emailContact
     *
     * @return Profile
     */
    public function setEmailContact($emailContact)
    {
        $this->email_contact = $emailContact;

        return $this;
    }

    /**
     * Get emailContact
     *
     * @return string
     */
    public function getEmailContact()
    {
        return $this->email_contact;
    }

    /**
     * Set numeroTelephone
     *
     * @param string $numeroTelephone
     *
     * @return Profile
     */
    public function setNumeroTelephone($numeroTelephone)
    {
        $this->numero_telephone = $numeroTelephone;

        return $this;
    }

    /**
     * Get numeroTelephone
     *
     * @return string
     */
    public function getNumeroTelephone()
    {
        return $this->numero_telephone;
    }
}

И такую ​​форму обновления Profile:

public function editAction($id, Request $request)
   {
      $em = $this->getDoctrine()->getManager();
      $profile = $em->getRepository('KrownDashboardBundle:Profile')->find($id);
      if (!$profile) {
        throw $this->createNotFoundException(
                'No news found for id ' . $id
        );
      }

      $form = $this->createFormBuilder($profile)
          ->add('title', 'text')
          ->add('breve_description', TextareaType::class, array(
            'attr' => array('class' => 'tinymce'),
           ))
          ->add('fields_of_law', 'choice', array(
              'choices'  => array(
                  'Droit du travail' => "Droit du travail",
                  'Droit de la famille' => "Droit de la famille",
                  'Contrats commerciaux' => "Contrats commerciaux",
              ),
              'choices_as_values' => true,
              'multiple' => true,
          ))
          ->add('imageFile', FileType::class, array(
              'label' => 'Photo',
              'data' => $profile->getImageFile(),
              'required'      => false,
              )
           )
          ->add('registre_ou_bareau')
          ->add('canton_actif')
          ->add('annee_obtention_brevet')
          ->add('titre_supplementaire')
          ->add('years_of_experience')
          ->add('langues_de_travail')
          ->add('email_contact')
          ->add('numero_telephone')
          ->add('avocat')
          ->getForm();

      $form->handleRequest($request);

      if ($form->isValid()) {
          $em->flush();
          return new Response('Profile updated successfully');
      }

      $build['form'] = $form->createView();

      return $this->render('KrownDashboardBundle:Profile:profiles_edit_add.html.twig', $build);
   }

В этой форме я могу обновлять и извлекать любое поле, кроме FileType поле.

Когда я отправляю форму, файл $ imageFile загружается правильно, а имя файла $ imageName сохраняется в базе данных. Проблема в том, что я не могу прикрепить уже загруженный файл к форме при ее загрузке.

Я могу получить имя файла, хранящегося в базе данных, с помощью $ profile-> getImageName (), но когда я выполняю $ profile-> getImageFile (), я получаю нулевое значение?

Я что-то упускаю?

ИЗМЕНИТЬ

Я также попытался вручную загрузить файл с таким именем.

$profile->setImageFile(
   new File(__DIR__.'/../../../../web/images/products/'.$profile->getImageName())
);

Теперь, когда я выполняю $ profile-> getImageFile (), я вижу файл, но он не прикреплен к форме.


person Kr1    schedule 23.07.2016    source источник


Ответы (2)


Вы не можете прикрепить файл к входному файлу, в целях безопасности это невозможно. Но вместо этого вы можете использовать некоторые библиотеки jquery для отображения / загрузки файлов (может быть тупым) или просто показать тег изображения с вашим путем к файлу, что позволит пользователю изменить файл.

person xurshid29    schedule 23.07.2016
comment
Действительно? Я очень удивлен это слышать! Насчет bluimp, вы имеете в виду загрузку файла jQuery? Собственно, это был следующий шаг, я планировал интегрировать что-то вроде загрузки файлов jQuery или Dropzone.js; но точно, мне нужно будет загрузить файл изображения в мою форму обновления, если я хочу поиграть с ним. Например, если я хочу обрезать изображение с помощью Jcrop (или изменить обрезку при редактировании профиля), мне нужно получить файл изображения, верно? Это так странно, если мы не можем загрузить изображение в форме обновления! Я рассматриваю возможность использования этого стороннего пакета: ComurImageBundle. Что вы думаете об этом? - person Kr1; 23.07.2016

вы должны написать этот код перед отправкой формы

$image = $profile->getImageFile();
if ($image !== null) {
    $profile->setImageFile(new File($this->getParameter('your image dir name') . '/' . $image));
}

$file = $project->getProfilePic();
$project->setProfilePic($file);

и если вы хотите обновить или сохранить старый файл, попробуйте вставить этот код после отправки

// add the new one
if ($profile->getImageFile() !== null) {

    $newImage = $profile->getImageFile();
    $newImageName = md5(uniqid()) . '.' . $file->guessExtension();
    $newImage->move($this->getParameter('your image dir'), $newImageName);
    $project->setImageFile($newImageName);
} else {
    //Restore old file name
    $profile->setProfilePic($image);
}
person Faisal    schedule 28.11.2018