Добрый день!
Изучаю этот прекрасный фрейм и наткнулся на такую проблему при разработке, не хотят сохранятся фотографии из формы.
Для этого реализовал класс формы через бандл Maker:
namespace App\Form;
use App\Entity\Note;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Image;
class NoteFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('content')
->add('image', FileType::class, [
'required' => false,
'mapped' => false,
'constraints' => [
new Image(['maxSize' => '2048k'])
],
])
->add('submit', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Note::class,
]);
}
}
Далее добавил его в контроллер:
namespace App\Controller;
use App\Entity\Author;
use App\Entity\Note;
use App\Form\NoteFormType;
use App\Repository\AuthorRepository;
use App\Repository\NoteRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;
class NoteController extends AbstractController
{
private $twig;
private $entityManager;
public function __construct(Environment $twig, EntityManagerInterface $entityManager)
{
$this->twig = $twig;
$this->entityManager = $entityManager;
}
// some code
/**
* @Route("/{slug}/notes", name="author")
*/
public function show(Request $request, Author $author, NoteRepository $noterepository): Response
{
$note = new Note();
$form = $this->createForm(NoteFormType::class, $note);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$note->setAuthor($author);
if ($image = $form['image']->getData()) {
$filename = bin2hex(random_bytes(6)).'.'.$image->guessExtension();
try {
$image->move(
$this->getParameter('image_directory'),
$filename
);
} catch (FileException $e) {
// unable to upload the image, give up
}
$note->setImageFilename($filename);
}
$this->entityManager->persist($note);
$this->entityManager->flush();
return $this->redirectToRoute('author', ['slug' => $author->getSlug()]);
}
$offset = max(0, $request->query->getInt('offset', 0));
$paginator = $noterepository->getNotePaginator($author, $offset);
return new Response($this->twig->render('note/show.html.twig', [
// some code
'notes' => $paginator,
'note_form' => $form->createView(),
]));
}
}
В нем так же сохряняется новое имя фото в БД, для этого создал миграцию в доктрине, но это не суть вопроса.
Переменную
image_directory
засунул в
/config/services.yaml
parameters:
$image_directory: "%kernel.project_dir%/public/uploads/photos"
Ну и на последок отрисовал вывод фото в твиге:
{% for note in notes %}
<div>
...
<img src="{{ asset('uploads/images/' ~ note.imageFilename) }}" alt="{{ note.imageFilename }}">
...
</div>
{% endfor %}
В итоге форма свое дело делает, но не сохраняются фотографии при этом, какие могут быть причины?