更新 在我的Symfony项目中,我可以上传单个图像.现在我正在尝试上传多个图像.
class ImageFile extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('images', FileType::class, array( 'attr' => array( 'accept' => 'image/*', 'multiple' => 'multiple' ) )) ->add('save',SubmitType::class,array('label'=>'Insert Image','attr'=>array('class'=>'btn btn-primary','style'=>'margin-bottom:15px'))) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => images::class )); } }
在我的Images实体中,我保留了一个像这样的SatellieImage对象数组.
class images { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * @var satelliteImage[] * @ORM\Column(name="images", type="string") * */ private $images; /** * Set images * * @param string $images * * @return satelliteImage[] */ public function setImages($images) { $this->images = $images; return $this->images; } /** * Get images * * @return satelliteImage[] */ public function getImages() { return $this->images; } public function addImage($image) { $this->images[] = $image; return $this; } }
在我的控制器中,我将satelliteImage []存储为$ files并运行foreach循环以上传()每个文件(upload()函数完美地用于单个文件)
public function uploadImages(Request $request) { $satelliteImage=new satelliteImage; $images=new images(); $form = $this->createForm(ImageFile::class, $images); $form->handleRequest($request); $files=$images->getImages(); foreach ($files as $file){ $em=$this->getDoctrine()->getManager(); $file->upload(); $em->persist($satelliteImage); $em->flush(); } $this->addFlash( 'notice', 'Images inserted successfully' ); return $this->redirectToRoute('satellite_images'); }
问题:我收到错误提示"警告:为foreach提供的参数无效()"如何解决这个问题?
我认为你在这里要做的就是为你的ImageFile
班级添加'multiple'属性;
请参阅Symfony文档.
use Symfony\Component\Form\Extension\Core\Type\FileType; class ImageFile extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('images', FileType::class, [ 'multiple' => true, 'attr' => [ 'accept' => 'image/*', 'multiple' => 'multiple' ] ]) ; } }
另外,将"图片"属性更改为"图片"属性:
/** * Set images * * @param string $images * * @return satelliteImage[] */ public function setImages($images) { $this->images = $images; return $this; } /** * Get images * * @return string */ public function getImages() { return $this->image; } public function addImage($image) { $this->images[] = $image; return $this; }
对此进行排序后,可以修改upload
方法以处理FormType中的多个文件.