如何使用已上传的FileType编辑实体?

时间:2019-04-13 11:59:48

标签: php symfony

我要编辑带有封面图像的商店实体(Image Entity)。 但是我无法捕获和使用已经上传的文件。

我已经尝试了Internet上找到的所有方法,所以不要判断代码的状态:)。

/**
 * @ORM\Entity(repositoryClass="App\Repository\ShopRepository")
 * @ORM\HasLifecycleCallbacks
 * 
 */
class Shop
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

    /**
     * @ORM\Column(type="float", nullable=true)
     */
    private $lat;

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

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

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     * @Assert\Email(message="Veuillez renseigner un email valide !")
     */
    private $email;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $phone;

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

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

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

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

    /**
     * @ORM\Column(type="array", nullable=true)
     */
    private $hours = [];

    /**
     * @ORM\Column(type="integer")
     */
    private $access_level;

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

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="shops")
     * @ORM\JoinColumn(nullable=false)
     */
    private $owner;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Image", orphanRemoval=true, mappedBy="shop")
     */
    private $images;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="shop", orphanRemoval=true)
     */
    private $products;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    private $enable;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Promotions", mappedBy="shop", orphanRemoval=true)
     */
    private $promotions;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="shops")
     * @Groups({"shop"})
     */
    private $category;

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

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Image", inversedBy="coverShop", cascade={"persist", "remove"})
     */
    private $cover;




    public function __construct()
    {
        $this->owner = new ArrayCollection();
        $this->images = new ArrayCollection();
        $this->bookings = new ArrayCollection();
        $this->products = new ArrayCollection();
        $this->promotions = new ArrayCollection();
    }

    /**
     * Undocumented function
     *
     * @ORM\PrePersist
     * @ORM\PreUpdate
     * 
     * @return void
     */
    public function initializeSlug() 
    {
        if(empty($this->slug))
        {
            $slugify = new Slugify();
            $this->slug = $slugify->slugify($this->name);
        }
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getGoogleId(): ?string
    {
        return $this->google_id;
    }

    public function setGoogleId(?string $google_id): self
    {
        $this->google_id = $google_id;

        return $this;
    }

    public function getLat(): ?float
    {
        return $this->lat;
    }

    public function setLat(?float $lat): self
    {
        $this->lat = $lat;

        return $this;
    }

    public function getLongi(): ?string
    {
        return $this->longi;
    }

    public function setLongi(?string $longi): self
    {
        $this->longi = $longi;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(string $address): self
    {
        $this->address = $address;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getPhone(): ?int
    {
        return $this->phone;
    }

    public function setPhone(?int $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getMobile(): ?int
    {
        return $this->mobile;
    }

    public function setMobile(int $mobile): self
    {
        $this->mobile = $mobile;

        return $this;
    }

    public function getFax(): ?int
    {
        return $this->fax;
    }

    public function setFax(?int $fax): self
    {
        $this->fax = $fax;

        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getCity(): ?string
    {
        return $this->city;
    }

    public function setCity(string $city): self
    {
        $this->city = $city;

        return $this;
    }

    public function getHours(): ?array
    {
        return $this->hours;
    }

    public function setHours(array $hours): self
    {
        $this->hours = $hours;

        return $this;
    }

    public function getAccessLevel(): ?int
    {
        return $this->access_level;
    }

    public function setAccessLevel(int $access_level): self
    {
        $this->access_level = $access_level;

        return $this;
    }

    public function getIntroduction(): ?string
    {
        return $this->introduction;
    }

    public function setIntroduction(string $introduction): self
    {
        $this->introduction = $introduction;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getCoverImage(): ?string
    {
        return $this->coverImage;
    }

    public function setCoverImage(string $coverImage): self
    {
        $this->coverImage = $coverImage;

        return $this;
    }



    public function getOwner(): ?User
    {
        return $this->owner;
    }

    public function setOwner(?User $owner): self
    {
        $this->owner = $owner;

        return $this;
    }

    /**
     * @return Collection|Image[]
     */
    public function getImages(): Collection
    {
        return $this->images;
    }

    public function addImage(Image $image): self
    {
        if (!$this->images->contains($image)) {
            $this->images[] = $image;
            $image->setShop($this);
        }

        return $this;
    }

    public function removeImage(Image $image): self
    {
        if ($this->images->contains($image)) {
            $this->images->removeElement($image);
            // set the owning side to null (unless already changed)
            if ($image->getShop() === $this) {
                $image->setShop(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Product[]
     */
    public function getProducts(): Collection
    {
        return $this->products;
    }

    public function addProduct(Product $product): self
    {
        if (!$this->products->contains($product)) {
            $this->products[] = $product;
            $product->setShop($this);
        }

        return $this;
    }

    public function removeProduct(Product $product): self
    {
        if ($this->products->contains($product)) {
            $this->products->removeElement($product);
            // set the owning side to null (unless already changed)
            if ($product->getShop() === $this) {
                $product->setShop(null);
            }
        }

        return $this;
    }

    public function getEnable(): ?bool
    {
        return $this->enable;
    }

    public function setEnable(?bool $enable): self
    {
        $this->enable = $enable;

        return $this;
    }

    /**
     * @return Collection|Promotions[]
     */
    public function getPromotions(): Collection
    {
        return $this->promotions;
    }

    public function addPromotion(Promotions $promotion): self
    {
        if (!$this->promotions->contains($promotion)) {
            $this->promotions[] = $promotion;
            $promotion->setShop($this);
        }

        return $this;
    }

    public function removePromotion(Promotions $promotion): self
    {
        if ($this->promotions->contains($promotion)) {
            $this->promotions->removeElement($promotion);
            // set the owning side to null (unless already changed)
            if ($promotion->getShop() === $this) {
                $promotion->setShop(null);
            }
        }

        return $this;
    }

    public function getCategory(): ?Category
    {
        return $this->category;
    }

    public function setCategory(?Category $category): self
    {
        $this->category = $category;

        return $this;
    }

    public function getWebsite(): ?string
    {
        return $this->website;
    }

    public function setWebsite(?string $website): self
    {
        $this->website = $website;

        return $this;
    }

    public function getCover(): ?Image
    {
        return $this->cover;
    }

    public function setCover(?Image $cover): self
    {
        $this->cover = $cover;

        return $this;
    }




}

/**
 * @ORM\Entity(repositoryClass="App\Repository\ImageRepository")
 */
class Image
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\File(mimeTypes={ "image/png", "image/jpeg" })
     */
    private $url;

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

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Shop", inversedBy="images")
     */
    private $shop;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Promotions", inversedBy="images")
     */
    private $promotions;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Product", inversedBy="images")
     */
    private $product;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Shop", mappedBy="cover", cascade={"persist", "remove"})
     */
    private $coverShop;


    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUrl(): ?string
    {
        return $this->url;
    }

    public function setUrl(string $url): self
    {
        $this->url = $url;

        return $this;
    }

    public function getFile(): ?string
    {
        return $this->file;
    }

    public function setFile(string $file): self
    {
        $this->file = $file;

        return $this;
    }

    public function getCaption(): ?string
    {
        return $this->caption;
    }

    public function setCaption(string $caption): self
    {
        $this->caption = $caption;

        return $this;
    }

    public function getShop(): ?Shop
    {
        return $this->shop;
    }

    public function setShop(?Shop $shop): self
    {
        $this->shop = $shop;

        return $this;
    }

    public function getPromotions(): ?Promotions
    {
        return $this->promotions;
    }

    public function setPromotions(?Promotions $promotions): self
    {
        $this->promotions = $promotions;

        return $this;
    }

    public function getProduct(): ?Product
    {
        return $this->product;
    }

    public function setProduct(?Product $product): self
    {
        $this->product = $product;

        return $this;
    }

    public function getCoverShop(): ?Shop
    {
        return $this->coverShop;
    }

    public function setCoverShop(?Shop $coverShop): self
    {
        $this->coverShop = $coverShop;

        // set (or unset) the owning side of the relation if necessary
        $newCover = $coverShop === null ? null : $this;
        if ($newCover !== $coverShop->getCover()) {
            $coverShop->setCover($newCover);
        }

        return $this;
    }

}


class ShopType extends ApplicationType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 
                TextType::class, 
                $this->getConfiguration("Nom","Tapez le nom de votre magasin"))
            ->add('category', 
                EntityType::class, 
                $this->getConfiguration("Catégorie","Indiquer la categorie dans laquelle se situ votre magasin", [
                'required' => true,
                'class'    => Category::class,
                'choice_label' => 'name'
            ]))
            ->add('slug', 
                TextType::class, 
                $this->getConfiguration("Slug","Taper l\adresse web ( automatique )", [
                    'required' => false
                ]))
            ->add('introduction', 
                TextType::class, 
                $this->getConfiguration("Introduction","Donnez une courte description de l'annonce"))
            ->add('description', 
                TextareaType::class, 
                $this->getConfiguration("Descritpion détaillée","Indiquez la description complete de votre logement"))
            ->add('cover', 
                ImageType::class)
            ->add('address', 
                TextType::class, 
                $this->getConfiguration("Adresse","Indiquez l'adresse du magasin"))
            ->add('email', 
                EmailType::class, 
                $this->getConfiguration("Adresse mail","Indiquez votre adresse mail", [
                    'required' => true
                ]))
            ->add('phone', 
                TextType::class, 
                $this->getConfiguration("Téléphone fixe","Indiquez votre numéro de téléphone", [
                    'required' => false
                ]))
            ->add('mobile', 
                TextType::class, 
                $this->getConfiguration("Téléphone mobile","Indiquez votre numéro de téléphone portable"))
            ->add('website', 
                TextType::class, 
                $this->getConfiguration("Site Internet","Indiquez l'adresse de votre site internet professionnel", [
                    'required' => false
                ]))
            ->add('images', CollectionType::class, 
            [
                'entry_type' => ImageType::class,
                'allow_add' => true,
                'allow_delete' => true
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([

        ]);
    }
}


class ImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('url', FileType::class, array(
            'label' => 'Photo de couverture (png, jpeg)',
            'data_class' => null,
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Image::class,
        ]);
    }
}



{% extends '/manage/base.html.twig' %}

{% block title %}Modification d'une annonce{% endblock %}

{# Indique que l'on utilise un theme dans le fichier #}
{% form_theme form '/manage/shop/_collection.html.twig' %}

{% block bodybody %}
<div class="container">


    <h1>Modifier l'annonce : {{ shop.name }}</h1>
    {{ form_start(form) }}

    {{ form_widget(form) }}

    <input type="hidden" id="widget-counter" value="0"/>
    <button type="submit" class="btn btn-primary"> Enreigstrer </button>

    {{ form_end(form) }}
</div>

{% endblock %}



{% block javascripts %}

<script src="/js/shop.js">

</script>
{% endblock %}


{% block _shop_cover_widget %}
{{ dump(form.vars)}}
{{ form_widget(form.url, {'attr': {'value': form.vars.value.url , 'placeholder' : form.vars.value.url }}) }}   
{%- endblock _shop_cover_widget %}


/**
     * Edit an announce
     *
     * @Route ("/shops/{slug}/edit", name="shop_edit")
     * 
     * @Security("is_granted('ROLE_USER') and user === shop.getOwner()", message="Ce magasin ne vous appartient pas, vous ne pouvez pas le modifier" )
     * 
     * @return Response
     */
    public function edit(Shop $shop, Request $request, ObjectManager $manager) 
    {
        $cover = $shop->getCover();
        $cover->setUrl(
            new File($this->getParameter('coverImages_directory').'/'.$shop->getCover()->getUrl())
        );

        $shop->setCover($cover);

        $form = $this->createForm(ShopType::class, $shop);

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid())
        {
            if(null === $form->get('cover')->get('url')->getData())
            {
                $cover->setUrl(
                    new UploadedFile($this->getParameter('coverImages_directory').'/'.$shop->getCover()->getUrl())
                );

                $shop->setCover($cover);
            }
            else
            {
                // $file stores the uploaded PDF file
                /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */

                $file = $form->get('cover')->get('url')->getData();
                $realName = $file->getClientOriginalName();
                $cover->setCaption($realName);
                $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

                // Move the file to the directory where brochures are stored
                try {
                    $file->move(
                        $this->getParameter('coverImages_directory'),
                        $fileName
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }
                $cover->setUrl($fileName);
                $shop->setCover($cover);

            }


            $manager->persist($shop);
            $manager->flush();

            $this->addFlash(
                'success',
                "Les modifications de  <strong>{$shop->getName()}</strong> ont été ajouté avec succes!"
            ); 

            return $this->redirectToRoute('manage_home', [
                'slug' => $shop->getSlug()
            ]);
        }

        return $this->render('/manage/shop/edit.html.twig', [
            'form' => $form->createView(),
            'shop' => $shop,

        ]);
    }

今天,我可以使用_shop_cover_widget及其属性来显示已经上传的文件的名称。

当我检查是否已上传文件时,出现提示“未选择文件”的提示。

谢谢

1 个答案:

答案 0 :(得分:0)

我希望以下示例可以为您提供帮助,如果您希望在不编辑的情况下上传较旧的图片

/**
 * Displays a form to edit an existing post entity.
 *
 * @Route("/{id}/edit", name="admin_post_edit")
 * @Method({"GET", "POST"})
 */
public function editAction(Request $request, Post $post)
{
    $oldPost = $post->getImage();
    $editForm = $this->createForm('AdminBundle\Form\PostType', $post);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {

        if($post->getImage() == null){
            $post->setImage($oldPost);
        }else{

            $file = $post->getImage();
            $fileName = md5(uniqid()).'.'.$file->guessExtension();
            $file->move($this->getParameter('uploads_posts_directory') , $fileName); 
            $post->setImage($fileName);
        }

        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('admin_post_index');
    }

    return $this->render('post/edit.html.twig', array(
        'post' => $post,
        'edit_form' => $editForm->createView(),
    ));
}