我有一个ProductType
表单,其中有Collection
个ProductImageType
(用于上传)。通过原型,我定义了一个视图并使用Javascript添加了新元素。
问题是,单击Add
时会找到并渲染原型视图,但是ProductImageType
中的表单小部件根本无法渲染。
这是我代码的相关部分。
发生的是,如果我向表单中添加其他字段(例如,非映射字段仅用于测试目的),则呈现product/prototype.images.html.twig
内的代码,除了FileType的表单字段外此视图不会显示。
其他项目中也一直在使用类似的代码。
class ProductType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('category' , null, ['label' => "Category", 'attr' => ['placeholder' => "Seleccione una categoría"]])
->add('name' , null, ['label' => "Title"])
->add('description', null, ['label' => "Description", 'attr' => ['class' => 'product-description-edit-field']])
->add('images' , CollectionType::class, [
'label' => 'false',
'entry_type' => ProductImageType::class,
'allow_add' => true,
'allow_delete' => true,
// 'delete_empty' => true,
'prototype' => true,
'prototype_data' => New ProductImage
])
;
}/**
class ProductImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('image', FileType::class, ['label' => "Upload a picture",
// 'data_class' => null,
'attr' => ['class' => ''],
]);
}
{# ... #}
{{ form_row(edit_form.images) }}
<ul id="edit-image-list" class="edit-image-list" data-prototype="{% filter escape %}
{{ include('product/prototype.images.html.twig', { 'form': edit_form.images.vars.prototype }) }}
{% endfilter %}">
{# iterate over each existing image and render its only field: name #}
{% for image in edit_form.images %}
<li>{{ form_row(image.image) }}</li>
{% endfor %}
</ul>
<div class="button-wrapper left">
<a href="javascript:void(0)" class="btn btn-sm btn-outline-success" onclick="addImageUploader()">
Add image
</a>
</div>
{# ... #}
<script type="text/javascript">
function addImageUploader()
{
// Get the data-prototype explained earlier
var prototype = $('#edit-image-list').data('prototype');
// get the new index
var index = $('#edit-image-list li').length;
// Replace '__name__' in the prototype's HTML to instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
$('#edit-image-list').append(newForm);
}
</script>
<li>
<div class="row">
<div class="col-md-8">
{{ form_row(form.image, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="col-md-4">
<a href="https://via.placeholder.com/150"><img src="https://via.placeholder.com/150"></a>
</div>
</div>
</li>
/**
* @ORM\Entity
*/
class Product
{
/**
* @ORM\OneToMany(targetEntity="ProductImage", mappedBy="product", cascade={"persist", "remove"})
*/
private $images;
public function __construct()
{
$this->images = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @ORM\Entity
*/
class ProductImage
{
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Assert\Image()
*/
private $image;