我的Symfony 2表单和图片上传存在问题。
我创建了一个表单:
$form = $formFactory->create(new PlaceType($this->_em), $place, array(
'method' => 'POST',
'status' => $place->getStatus()
));
在PlaceType.php
:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('images', 'collection', array(
'type' => new ImageType($this->em),
'allow_add' => true,
'data' => array(new Image())));
}
在ImageType.php
:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('file', 'file', array('required' => false));
}
它工作得非常好,但是当我没有填写场地时,我有一个例外,因为缺少文件信息。
我想将此字段设为可选字段。我尝试了很多解决方案,但都没有。
编辑(我的实体代码image.php
):
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload() {
if (null !== $this->file) {
$this->link = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
$this->name = 'name';
$this->sort = 1;
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload() {
if (null === $this->file) {
return;
}
$this->file->move($this->getUploadRootDir(), $this->link);
unset($this->file);
}
/**
* @ORM\PostRemove()
*/
public function removeUpload() {
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
public function getAbsolutePath() {
return null === $this->link ? null : $this->getUploadRootDir().'/'.$this->link;
}
protected function getUploadRootDir() {
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir() {
return 'uploads/media';
}
编辑2(我的AJAX控制器代码):
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($place);
$em->flush();
}
正如您所看到的,我无法控制持续时间,因此,我无法管理我的图片上传。
编辑3:
我使用ArrayCollection
保留数据库中的旧图像并添加新图像,这是AJAX controller
中的代码:
$originalArray = new ArrayCollection();
foreach ($place->getImages() as $images) {
$originalArray->add($images);
$place->removeImage($images);
}
后来:
foreach ($originalArray as $images) {
$place->addImage($images);
}
感谢。