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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用已上传的FileType编辑实体?相关的知识,希望对你有一定的参考价值。

我想用封面图像(图像实体)编辑商店实体。但我无法捕获并使用已上传的文件。

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

/**
 * @ORMEntity(repositoryClass="AppRepositoryShopRepository")
 * @ORMHasLifecycleCallbacks
 * 
 */
class Shop
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

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

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

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

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

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

    /**
     * @ORMColumn(type="string", length=255, nullable=false)
     * @AssertEmail(message="Veuillez renseigner un email valide !")
     */
    private $email;

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

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

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

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

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

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

    /**
     * @ORMColumn(type="integer")
     */
    private $access_level;

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

    /**
     * @ORMColumn(type="text")
     */
    private $description;

    /**
     * @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="shops")
     * @ORMJoinColumn(nullable=false)
     */
    private $owner;

    /**
     * @ORMOneToMany(targetEntity="AppEntityImage", orphanRemoval=true, mappedBy="shop")
     */
    private $images;

    /**
     * @ORMOneToMany(targetEntity="AppEntityProduct", mappedBy="shop", orphanRemoval=true)
     */
    private $products;

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

    /**
     * @ORMOneToMany(targetEntity="AppEntityPromotions", mappedBy="shop", orphanRemoval=true)
     */
    private $promotions;

    /**
     * @ORMManyToOne(targetEntity="AppEntityCategory", inversedBy="shops")
     * @Groups({"shop"})
     */
    private $category;

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

    /**
     * @ORMOneToOne(targetEntity="AppEntityImage", 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
     *
     * @ORMPrePersist
     * @ORMPreUpdate
     * 
     * @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;
    }




}

/**
 * @ORMEntity(repositoryClass="AppRepositoryImageRepository")
 */
class Image
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     * @AssertFile(mimeTypes={ "image/png", "image/jpeg" })
     */
    private $url;

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

    /**
     * @ORMManyToOne(targetEntity="AppEntityShop", inversedBy="images")
     */
    private $shop;

    /**
     * @ORMManyToOne(targetEntity="AppEntityPromotions", inversedBy="images")
     */
    private $promotions;

    /**
     * @ORMManyToOne(targetEntity="AppEntityProduct", inversedBy="images")
     */
    private $product;

    /**
     * @ORMOneToOne(targetEntity="AppEntityShop", 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 ladresse 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 SymfonyComponentHttpFoundationFileUploadedFile $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及其属性显示已上传的文件名。

当我检查我的文件是否已经上传时,Ben是否在表单中包含消息“未选择文件”..

谢谢

答案

我希望以下示例可以帮助您,如果您希望保留较旧的图像而不进行编辑

/**
 * 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('AdminBundleFormPostType', $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(),
    ));
}

以上是关于如何使用已上传的FileType编辑实体?的主要内容,如果未能解决你的问题,请参考以下文章

python接口自动化32-上传文件时自动判断文件类型(filetype)

带有文件类型字段editAction的Symfony 3表单集合实体

简单利用filetype进行文件上传

使用 Retrofit MultiPart 实体上传文件/图像是不是已加密?

保存图表失败!验证 Graphviz 是不是已安装并在您的路径中,或使用 filetype=dot

判断文件上传的类型