I have a collection form called Paragraphe with a text and a file (an Image):
class ParagrapheType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('text')
->add('image', FileType::class, ['mapped'=>false, 'required'=>false])
And it's inside another form called Article. Here, how I add a Paragraphe inside formulaire.html.twig of Article (I just followed How to Embed a Collection of Forms from the official Symfony doc) :
<h3>Paragraphes:</h3>
{# the data-index attribute is required for the JavaScript code below #}
<ul class="paragraphes" data-index="{{ (formArticle.paragraphes|length) > 0 ? formArticle.paragraphes|last.vars.name + 1 : 0 }}" data-prototype="{{ form_widget(formArticle.paragraphes.vars.prototype)|e( 'html_attr' ) }}"></ul>
<button type="button" class="add_item_link" data-collection-holder-class="paragraphes">Add an paragraphe</button>
<script>
//event listener sur le bouton document.querySelectorAll('.add_item_link') ➡️ adds a new Paragraphe form on the Article form when push the button⤵️
const addFormToCollection = (e) => { const collectionHolder =
document.querySelector('.' + e.currentTarget.dataset.collectionHolderClass);
const item = document.createElement('li');
item.innerHTML = collectionHolder .dataset .prototype .replace( /__name__/g, collectionHolder.dataset.index );
collectionHolder.appendChild(item);
collectionHolder.dataset.index++; };
document
.querySelectorAll('.add_item_link')
.forEach(btn => { btn.addEventListener("click", addFormToCollection) });
Here what I try to save my Image in my ArticleControler.php:
foreach ($form->get('paragraphes')->getData() as $paragraphe) {
$imageParagraphe= $paragraphe->get('image')->getData(); //get() method doesn't exist so I don't know how to get the file.
if($imageParagraphe){
$fileNameImageParagraphe = $articleSlug . uniqid() . '.' . $imageParagraphe->guessExtension();
//move the image as parametred in service.yaml
try {
$imageParagraphe->move($this->getParameter('article_images'), $fileNameImageParagraphe);
} catch (FileException $e) {
$this->addFlash('erreur', "Image cannot be uploaded.");
}
$paragraphe->setImage($fileNameImageParagraphe);
} else $paragraphe->setImage($imageParagraphe);
}
As my comment says, I didn't find a way to get the file inside the second form. Did I need to do it from my script inside my twig?