Symfony 2形成可选图像

时间:2015-04-13 13:43:21

标签: php forms symfony image-uploading symfony-forms

我的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);
}

感谢。

0 个答案:

没有答案