Reputation: 1
Hi I would like to upload a picture associated to a restaurant entity. The image is stocked good in the restaurant entity but impossible to load it in the public folder to use it in my twig file with the assets. Do you have solutions ? May I am uploading bad the image
RestaurantController.php
<?php
namespace App\Controller;
use App\Entity\Image;
use App\Entity\Restaurant;
use App\Form\RestaurantType;
use App\Repository\RestaurantRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/restaurant")
*/
class RestaurantController extends AbstractController
{
/**
* @Route("/index", name="app_restaurant_index", methods={"GET"})
*/
public function index(RestaurantRepository $restaurantRepository): Response
{
return $this->render('restaurant/index.html.twig', [
'restaurants' => $restaurantRepository->findAll(),
]);
}
/**
* @Route("/new", name="app_restaurant_new", methods={"GET", "POST"})
*/
public function new(Request $request, RestaurantRepository $restaurantRepository, EntityManagerInterface $entityManagerInterface): Response
{
$restaurant = new Restaurant();
$form = $this->createForm(RestaurantType::class, $restaurant);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//upload img
if ($form->get('image')->getData() != null) {
$image = $form->get('image')->getData();
$fichier = md5(uniqid()) . '.' . $image->guessExtension();
// On copie le fichier dans le dossier build
$image->move(
$this->getParameter('images_directory'), // Destination folder -> images_directory: '/public/build'
$fichier // File name
);
// On crée l'image dans la base de données
$img = new Image();
$img->setName($fichier);
$restaurant->setImage($img);
}
$restaurant->setUser($this->getUser());
$restaurantRepository->add($restaurant, true);
return $this->redirectToRoute('app_restaurant_show', ['id' => $restaurant->getId()], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('restaurant/new.html.twig', [
'restaurant' => $restaurant,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_restaurant_show", methods={"GET"})
*/
public function show(Restaurant $restaurant): Response
{
// if ($restaurant->getImage() != null) {
// $image= $restaurant->getImage();
// $image->move(
// $this->getParameter('images_directory'),
// $fichier
// );
// }
return $this->render('restaurant/show.html.twig', [
'restaurant' => $restaurant,
]);
}
/**
* @Route("/{id}/edit", name="app_restaurant_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, Restaurant $restaurant, RestaurantRepository $restaurantRepository): Response
{
$form = $this->createForm(RestaurantType::class, $restaurant);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$restaurantRepository->add($restaurant, true);
return $this->redirectToRoute('app_restaurant_show', ['id' => $restaurant->getId()], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('restaurant/edit.html.twig', [
'restaurant' => $restaurant,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_restaurant_delete", methods={"POST"})
*/
public function delete(Request $request, Restaurant $restaurant, RestaurantRepository $restaurantRepository): Response
{
if ($this->isCsrfTokenValid('delete' . $restaurant->getId(), $request->request->get('_token'))) {
$restaurantRepository->remove($restaurant, true);
}
return $this->redirectToRoute('app_restaurant_index', [], Response::HTTP_SEE_OTHER);
}
}
Image.php
<?php
namespace App\Entity;
use App\Repository\ImageRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ImageRepository::class)]
class Image
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\OneToOne(inversedBy: 'image', cascade: ['persist'])]
#[ORM\JoinColumn(name: "restaurant_id", nullable: true)]
private ?Restaurant $restaurant = null;
#[ORM\OneToOne(inversedBy: 'image', cascade: ['persist'])]
#[ORM\JoinColumn(name: "dish_id", nullable: true)]
private ?Dish $dish = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getRestaurant(): ?Restaurant
{
return $this->restaurant;
}
public function setRestaurant(?Restaurant $restaurant): self
{
$this->restaurant = $restaurant;
return $this;
}
public function getDish(): ?Dish
{
return $this->dish;
}
public function setDish(?Dish $dish): self
{
$this->dish = $dish;
return $this;
}
}
Restaurant.php
<?php
namespace App\Entity;
use App\Repository\RestaurantRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RestaurantRepository::class)]
class Restaurant
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $address = null;
#[ORM\Column(type: Types::DECIMAL, precision: 3, scale: 1, nullable: true)]
private ?string $ecoRate = null;
#[ORM\Column(type: Types::DECIMAL, precision: 3, scale: 1, nullable: true)]
private ?string $rate = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $info = null;
#[ORM\ManyToMany(targetEntity: Category::class, inversedBy: 'restaurants')]
private Collection $category;
// #[ORM\OneToMany(mappedBy: 'restaurant', targetEntity: Dish::class)]
// private Collection $dishes;
#[ORM\OneToMany(mappedBy: 'restaurant', targetEntity: Menu::class)]
private Collection $menus;
#[ORM\OneToMany(mappedBy: 'restaurant', targetEntity: Order::class)]
private Collection $orders;
#[ORM\ManyToMany(targetEntity: User::class, mappedBy: 'favorites')]
private Collection $users;
#[ORM\Column(length: 255)]
private ?string $siret = null;
#[ORM\Column(length: 255)]
private ?string $phoneNumber = null;
#[ORM\Column(length: 255)]
private ?string $email = null;
#[ORM\Column]
private ?bool $state = null;
#[ORM\OneToOne(inversedBy: 'restaurant', cascade: ['persist', 'remove'])]
private ?User $user = null;
#[ORM\OneToOne(mappedBy: 'restaurant', cascade: ['persist', 'remove'])]
private ?Image $image = null;
public function __construct()
{
$this->category = new ArrayCollection();
$this->menus = new ArrayCollection();
$this->orders = new ArrayCollection();
$this->users = new ArrayCollection();
}
public function __toString()
{
return (string) $this->getId();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getAddress(): ?string
{
return $this->address;
}
public function setAddress(string $address): self
{
$this->address = $address;
return $this;
}
public function getEcoRate(): ?string
{
return $this->ecoRate;
}
public function setEcoRate(?string $ecoRate): self
{
$this->ecoRate = $ecoRate;
return $this;
}
public function getRate(): ?string
{
return $this->rate;
}
public function setRate(?string $rate): self
{
$this->rate = $rate;
return $this;
}
public function getInfo(): ?string
{
return $this->info;
}
public function setInfo(?string $info): self
{
$this->info = $info;
return $this;
}
/**
* @return Collection<int, Category>
*/
public function getCategory(): Collection
{
return $this->category;
}
public function addCategory(Category $category): self
{
if (!$this->category->contains($category)) {
$this->category->add($category);
}
return $this;
}
public function removeCategory(Category $category): self
{
$this->category->removeElement($category);
return $this;
}
// /**
// * @return Collection<int, Dish>
// */
// public function getDishes(): Collection
// {
// return $this->dishes;
// }
// public function addDish(Dish $dish): self
// {
// if (!$this->dishes->contains($dish)) {
// $this->dishes->add($dish);
// $dish->setRestaurant($this);
// }
// return $this;
// }
// public function removeDish(Dish $dish): self
// {
// if ($this->dishes->removeElement($dish)) {
// // set the owning side to null (unless already changed)
// if ($dish->getRestaurant() === $this) {
// $dish->setRestaurant(null);
// }
// }
// return $this;
// }
/**
* @return Collection<int, Menu>
*/
public function getMenus(): Collection
{
return $this->menus;
}
public function addMenu(Menu $menu): self
{
if (!$this->menus->contains($menu)) {
$this->menus->add($menu);
$menu->setRestaurant($this);
}
return $this;
}
public function removeMenu(Menu $menu): self
{
if ($this->menus->removeElement($menu)) {
// set the owning side to null (unless already changed)
if ($menu->getRestaurant() === $this) {
$menu->setRestaurant(null);
}
}
return $this;
}
/**
* @return Collection<int, Order>
*/
public function getOrders(): Collection
{
return $this->orders;
}
public function addOrder(Order $order): self
{
if (!$this->orders->contains($order)) {
$this->orders->add($order);
$order->setRestaurant($this);
}
return $this;
}
public function removeOrder(Order $order): self
{
if ($this->orders->removeElement($order)) {
// set the owning side to null (unless already changed)
if ($order->getRestaurant() === $this) {
$order->setRestaurant(null);
}
}
return $this;
}
/**
* @return Collection<int, User>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users->add($user);
$user->addFavorite($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
$user->removeFavorite($this);
}
return $this;
}
public function getSiret(): ?string
{
return $this->siret;
}
public function setSiret(string $siret): self
{
$this->siret = $siret;
return $this;
}
public function getPhoneNumber(): ?string
{
return $this->phoneNumber;
}
public function setPhoneNumber(string $phoneNumber): self
{
$this->phoneNumber = $phoneNumber;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function isState(): ?bool
{
return $this->state;
}
public function setState(bool $state): self
{
$this->state = $state;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getImage(): ?Image
{
return $this->image;
}
public function setImage(?Image $image): self
{
// unset the owning side of the relation if necessary
if ($image === null && $this->image !== null) {
$this->image->setRestaurant(null);
}
// set the owning side of the relation if necessary
if ($image !== null && $image->getRestaurant() !== $this) {
$image->setRestaurant($this);
}
$this->image = $image;
return $this;
}
}
twig file
{% extends 'base.html.twig' %}
{% block title %}Restaurant
{% endblock %}
{% block body %}
<h1>Restaurant</h1>
<table class="table">
<tbody>
<tr>
<th>Id</th>
<td>{{ restaurant.id }}</td>
</tr>
<tr>
<th>Address</th>
<td>{{ restaurant.address }}</td>
</tr>
<tr>
<th>Email</th>
<td>{{ restaurant.email }}</td>
</tr>
<tr>
<th>Telephone</th>
<td>{{ restaurant.phoneNumber }}</td>
</tr>
<tr>
<th>Rate</th>
<td>{{ restaurant.rate }}</td>
</tr>
{% if restaurant.ecoRate %}
<tr>
<th>Eco rate</th>
<td>{{ restaurant.ecoRate }}</td>
</tr>
{% endif %}
<tr>
<th>Info</th>
<td>{{ restaurant.info }}</td>
</tr>
<tr>
<th>Siret</th>
<td>{{ restaurant.siret }}</td>
</tr>
{% if restaurant.image %}
<tr>
<th>Image</th>
<td><a href="{{ asset('build/images/' ~ restaurant.image.name) }}"></td>
{# <td><img src="{{ asset('build/images/' ~ restaurant.image.name) }}"></td> #}
</tr>
{% endif %}
<tr>
<th>Categorie</th>
{% for cat in restaurant.category %}
<td>{{ cat.name }}</td>
{% endfor %}
</tr>
</tbody>
</table>
{# <a href="{{ path('app_restaurant_index') }}">back to list</a> #}
<a href="{{ path('app_restaurant_edit', {'id': restaurant.id}) }}">edit</a>
<a href="{{ path('app_restaurant_edit', {'id': restaurant.id}) }}">Menu</a>
{# <a href="{{ path('app_restaurant_dish', {'restaurant_id': restaurant.id}) }}">Produit</a> #}
{# <a href="{{ path('app_restaurant_categorie', {'restaurant_id': restaurant.id}) }}">Catégorie</a> #}
{{ include('restaurant/_delete_form.html.twig') }}
<pre>
{{ dump(restaurant) }}
{{ dump(restaurant.image.name) }}
</pre>
{% endblock %}
Upvotes: 0
Views: 602
Reputation: 86
Did you check if your image is stored correctly? In the good folder? (In your controller, it seems to be in « /public/build », but in the Twig you concatenate with « /public/build/images »
Upvotes: 0