是否可以在不使用javascript的情况下嵌入表单集合五次并在form.twig中显示它们?
产品类型
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('required' => true))
->add('description', 'text', array('required' => true))
->add('price', 'text', array('required' => true))
//embed this formType
->add('image', 'collection', array('type' => new ImageType())
)
;
}
要嵌入的表单 图像类型
class ImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'texet', array('required' => true))
->add('file', 'file', array('required' => true))
;
}
这是表单.twig
<form method="post" action="" {{ form_enctype(form) }}>
{{ form_widget(form.name) }}
{{ form_widget(form.description) }}
{{ form_widget(form.price) }}
<div>
{{ form_widget(form.image) }}
</div>
<input type="submit" class="btn btn-primary" />
</form>
尝试使用五个图像实体填充产品实体。如果需要,创建新的(非持久化)实例。
我不知道
这是不是最好的方法,但如果您想上传确切的 5 张图像,您可以这样做。您还需要手动保存图像。
评论波纹管线:
->add('image', 'collection', array('type' => new ImageType())
在您的图像类型中:
class ImageType extends AbstractType
{
private static $count = 0;
private $index;
public function __construct() {
$this->index = self::$count++;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'texet', array('required' => true))
->add('file', 'file', array('required' => true));
}
public function getName()
{
return 'yourbundle_images_'.$this->index;
}
在控制器中这样写:
for($i=1;$i<=5; $i++)
{
$image = new 'YourBundle'Entity'Image();
$img = $this->createForm(new 'YourBundle'Entity'ImageType(), $image);
$images[$i] = $img->createView();
}
使用$images数组渲染树枝。
在你的树枝中编写如下代码:
{% for i in 1..5 %}
{{ form_widget(images[i].name) }}
{{ form_widget(images[i].file) }}
{% endfor %}
这很奇怪,但您必须保存文件/图像,例如:
for($i=1 ; $i<=5; $i++)
{
$img = new 'YourBundle'Entity'Image();
$filename = $request->get('acme_productbundle_image_'.$i); // Your generated field id will be here
$file = $request->files->get('acme_productbundle_image_'.$i);
$img->setName($filename['name']);
$img->setFile($file['file']);
$img->setProduct($product); // your related product
$this->getDoctrine()->getManager()->persist($img);
}
$this->getDoctrine()->getManager()->flush();
我有一个问题,为什么你不想使用javascript。这是最好的选择。在这里看到 http://symfony.com/doc/current/cookbook/form/form_collections.html#allowing-new-tags-with-the-prototype
我也徘徊着从别人那里得到更好的答案。 :)