Symfony dodanie zdjęć do formularza

0

Mam entity informations i dodałem pole file aby dodawać po kilka zdjęć. Mogę wybierać już pliki ale nie wiem co dalej, jak to zapisywać w bazie i pliki w folderze?

<?php

namespace App\Controller;

use App\Entity\User;
use App\Entity\Informations;
use App\Form\InformationsType;
use App\Repository\InformationsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/artykulyedycja")
 */
class InformationsController extends AbstractController
{
    /**
     * @Route("/", name="informations_index", methods={"GET"})
     */
    public function index(InformationsRepository $informationsRepository): Response
    {
        
        if ($this->container->get('security.authorization_checker')->isGranted('ROLE_ADMIN')){
             return $this->render('informations/index.html.twig', [
                'informations' => $informationsRepository->findAll(),
            ]);
             
         }
        
        else if ($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')) {
             $userId = $this->getUser()->getId();
            return $this->render('informations/index.html.twig', [
                'informations' => $informationsRepository->findBy(
    ['author' => $userId]
),
            ]);
         }
          
         else {
                return $this->render('informations/index.html.twig', [
                'informations' => $informationsRepository->findAll(),
            ]);
             
         }
    }

    /**
     * @Route("/nowy", name="informations_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {$userId = $this->getUser()->getId();
        $information = new Informations();
        $form = $this->createForm(InformationsType::class, $information);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($information);
            $entityManager->flush();

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

        return $this->render('informations/new.html.twig', [
            'information' => $information,
            'userId'=>$userId,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="informations_show", methods={"GET"})
     */
    public function show(Informations $information): Response
    {
        return $this->render('informations/show.html.twig', [
            'information' => $information,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="informations_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Informations $information): Response
    {
        $form = $this->createForm(InformationsType::class, $information);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('informations_index', [
                'id' => $information->getId(),
            ]);
        }

        return $this->render('informations/edit.html.twig', [
            'information' => $information,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="informations_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Informations $information): Response
    {
        if ($this->isCsrfTokenValid('delete'.$information->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($information);
            $entityManager->flush();
        }

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

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

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

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

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

    /**
     * @ORM\Column(type="datetime")
     */
    private $date;

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

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

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

    
    

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

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

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

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

        return $this;
    }

    public function getAuthor(): ?int
    {
        return $this->author;
    }

    public function setAuthor(int $author): self
    {
        $this->author = $author;

        return $this;
    }

    public function getDate(): ?\DateTimeInterface
    {
        return $this->date;
    }

    public function setDate(\DateTimeInterface $date): self
    {
        $this->date = $date;

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

    public function getImages(): ?string
    {
        return $this->images;
    }

    public function setImages(?string $images): self
    {
        $this->images[] = $images;

        return $this;
    }
}

<?php

namespace App\Form;

use App\Entity\Informations;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
class InformationsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('category',ChoiceType::class, [
                'choices' => ['Informacje' => 'Informacje',
                'Kultura i Rozrywka' => 'Rozrywka',
                'Sport' => 'Sport'],])
            ->add('city',ChoiceType::class, [
                'choices' => ['Lublin' => 'Lublin',
                'Warszawa' => 'Warszawa'],])
           
            
            ->add('description', TextareaType::class )
            ->add('author', HiddenType::class,array(                
                'attr' => array('value' => ''),
            ))
            ->add('date')
           
             ->add('images', FileType::class, array(
                'attr' => array(
                    'accept' => 'image/*',
                    'multiple' => 'multiple',
                    
                ),'label'=>'zdjęcia'))
        ;
    }

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

Po wypełnieniu formularza pojawia się błąd SQLSTATE[42S22]: Column not found: 1054 Unknown column 'images' in 'field list'

1

Dlaczego chcesz pliki przechowywać w bazie?

0

Chcę tylko nazwy plików mieć w bazie a same pliki w jakimś folderze

0

Może spróbuj skorzystać z gotowca np. VichUploader

0

Zrobiłem tak jak pod tym linkiem. Po wpisaniu do konsoli

php bin/console cache:clear

pojawiły się błędy

In FileLoader.php line 166:

There is no extension able to load the configuration for "vich_uploader" (in C:\Users\Radek\projekt1\config/packages/vich_uploader.yaml). Looked for namespace "vich_uploader", found "framework", "doctrine
_cache", "sensio_framework_extra", "doctrine", "doctrine_migrations", "security", "swiftmailer", "twig", "web_profiler", "monolog", "debug", "maker", "web_server" in C:\Users\Radek\projekt1\config/package
s/vich_uploader.yaml (which is loaded in resource "C:\Users\Radek\projekt1\config/packages/vich_uploader.yaml").

In YamlFileLoader.php line 666:

There is no extension able to load the configuration for "vich_uploader" (in C:\Users\Radek\projekt1\config/packages/vich_uploader.yaml). Looked for namespace "vich_uploader", found "framework", "doctrine
_cache", "sensio_framework_extra", "doctrine", "doctrine_migrations", "security", "swiftmailer", "twig", "web_profiler", "monolog", "debug", "maker", "web_server"

0

A masz plik plik vich_uploader.yaml w config/packages?

0

Tak utworzyłem wcześniej taki plik

1

Rzuć okiem na to jak ja to kiedyś zrobiłem (bez używania dodatkowych bundli):
https://github.com/ccwrc/ccwrc_small_ads/blob/master/ccwrcSmallAds/src/SmallAdsBundle/Controller/AdController.php
i encja:
https://github.com/ccwrc/ccwrc_small_ads/blob/master/ccwrcSmallAds/src/SmallAdsBundle/Entity/Ad.php

To na co powinieneś zwrócić uwagę to 'photoPath'.

Kod jest jaki jest, było to dawno i nieprawda a poza tym działa zgodnie z założeniami ;)

0

Dzięki, działa dodawanie. Problem mam z wyświetlaniem. W pliku twig.yaml dodałem ścieżkę do katalogu, zdjęcia się zapisują ale nie wyświetlają na stronie. Do wyświetlania mam taki kod:

<img src="{{uploads_img}}/{{ information.photoPath }}">

W źródle strony tworzy się taki adres do zdjęcia :

<img src="C:\Users\Radek\projekt1\src/../web/bundles/SmallAdsBundle/uploads_img/320190505152303644.jpeg">

Po skopiowaniu adresu i otworzeniu w nowej karcie zdjęcie się otwiera. Czy trzeba zmienić jakoś ten adres czy gdzieś indziej jest problem z wyświetlaniem zdjęć?
W konsoli przeglądarki jest komunikat

Not allowed to load local resource:

1 użytkowników online, w tym zalogowanych: 0, gości: 1