[英]Symfony2 Upload multiple files
Hello everyone I still learning symfony2 and I want to handle uploading multiple files to server. 大家好,我仍在学习symfony2,我想处理将多个文件上传到服务器。 I try execute 2 entities by one form.
我尝试通过一种形式执行2个实体。 I have Document, Product entity and
我有文件,产品实体和
form CreateProductType: 表格CreateProductType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text') // product name, quantity, description, etc
->add('file','file',array(
'required' => false,
'mapped' => false,
'data_class' => 'AppBundle\Entity\Document',
'attr' => array(
'accept' => 'image/*',
'multiple' => 'multiple',
)
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product'
));
}
what I supposed to do in controller to put files to uploads folder, insert new product 我应该在控制器中执行的操作以将文件放入上载文件夹,插入新产品
name,description,quantity,price, etc
and document (photos) 和文件(照片)
id, path, product_id
to database? 到数据库? Thanks in advance.
提前致谢。
EDIT. 编辑。 my Document entity looks like this Document.php
我的Document实体看起来像这个Document.php
If use form multiple array you should use collection in builder: 如果使用多数组形式,则应在builder中使用collection:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('files', 'collection', array(
'type' => 'file',
'options' => array(
'required' => false,
'mapped' => false,
'attr' => array(
'accept' => 'image/*',
'multiple' => 'multiple',
)
)
))
->add('product', new ProductType())
->add('save', 'submit', array(
'label' => 'Submit',
'attr' => array('class' => 'btn btn-default')
));
}
and then use array collection in entity: 然后在实体中使用数组集合:
/**
* @Assert\File(maxSize="6000000")
*/
public $files;
public function __construct()
{
$this->files = new ArrayCollection();
}
/**
* Add file
*
* @param UploadedFile $file
* @return UploadedFile
*/
public function addFile(UploadedFile $file)
{
$this->files[] = $file;
return $this;
}
/**
* Remove file
*
* @param UploadedFile $file
*/
public function removeFile(UploadedFile $file)
{
$this->files->removeElement($file);
}
Because multiple upload need has an array name name="files[]"
to store file multiple. 因为多个上载需要使用数组名称
name="files[]"
来存储多个文件。
SEE: Multiple file upload with Symfony2 and Symfony 2 Form collection field with type file SEE:使用 文件类型为Symfony2和Symfony 2 Form集合字段的 多个文件上传
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.