问题
I am encountering an issue with my form and I need help...
I want to create a form which can persist an advert. My issue come from my ManyToMany item 'images'. The new div i get by the 'images' form look like this:
<div><label class="required">Images</label><div id="annonce_rent_images" data-prototype="<div><label class="required">__name__label__</label><div id="annonce_rent_images___name__"><div><label for="annonce_rent_images___name___url" class="required">Url</label><input type="url" id="annonce_rent_images___name___url" name="annonce_rent[images][__name__][url]" required="required" /></div><div><label for="annonce_rent_images___name___alt" class="required">Alt</label><input type="text" id="annonce_rent_images___name___alt" name="annonce_rent[images][__name__][alt]" required="required" /></div></div></div>"></div></div>
The fields "url" & "alt" are stuck into the data-prototype attribute of the sub-div How am I supposed to fix that?
Here is few samples of my code, if you need complete files i can post them.
FORMBUILDER :
$builder
->add('name', TextType::class)
->add('description', TextType::class)
->add('price', TextType::class)
->add('location', TextType::class)
->add('zipcode', TextType::class)
->add('images', CollectionType::class, array(
'entry_type' => 'LAMainBundle\Form\ImageType',
'allow_add' => true,
'allow_delete' => true
))
->add('save', SubmitType::class, array('label' => 'Save'))
;
IMAGEBUILDER :
$builder
->add('url', UrlType::class)
->add('alt', TextType::class)
;
CONTROLLER addRentAction :
$annonce = new AnnonceRent();
$form = $this->createForm('LAMainBundle\Form\AnnonceRentType');
return $this->render('LAMainBundle:Admin:addrent.html.twig', array(
'form' => $form->createView(),
));
回答1:
You need some javascript to add the fields, here's a way to easily do it with jQuery:
<div>
<label class="required">Images</label>
<div id="annonce_rent_images" data-prototype="<div><label class="required">__name__label__</label><div id="annonce_rent_images___name__"><div><label for="annonce_rent_images___name___url" class="required">Url</label><input type="url" id="annonce_rent_images___name___url" name="annonce_rent[images][__name__][url]" required="required" /></div><div><label for="annonce_rent_images___name___alt" class="required">Alt</label><input type="text" id="annonce_rent_images___name___alt" name="annonce_rent[images][__name__][alt]" required="required" /></div></div></div>">
</div>
</div>
<!-- ... -->
<button id="add_image">Add image</button>
<script src="/js/jquery-2.2.1.min.js"></script>
<script>
function addEntry() {
var $container = $('#annonce_rent_images'),
$prototype = $container.data('prototype');
$prototype.replace(/__name__/g, $container.children('div').length);
$container.append($prototype);
}
addEntry(); // add a first field by default
$('#add_image').click(addEntry);
</script>
来源:https://stackoverflow.com/questions/36045743/how-to-add-an-entry-field-dynamically-in-an-empty-collection-form