Symfony 2.5.6 - исключение UnexpectedTypeException в пользовательском типе формы

0

У меня есть следующий вид формы:

class GalleryImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('thumb', new GalleryThumbnailImage(), array('label' => 'Thumbnail Image'))
            ->add('full', new GalleryFullSizeImage(), array('label' => 'Full Size Image'));
    }

    public function getName()
    {
        return 'galleryImage';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'MajorProductions\SewingDiva\SiteBundle\Entity\GalleryImage'));
    }
}

И следующие лица:

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="GalleryImage", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */
class GalleryImage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="GalleryThumbnailImage", mappedBy="galleryImage")
     */
    private $thumb;

    /**
     * @ORM\OneToOne(targetEntity="GalleryFullSizeImage", mappedBy="galleryImage")
     */
    private $full;

    /**
     * @ORM\Column(name="lastModified", type="datetime", nullable=true)
     */
    private $lastModified;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return GalleryFullSizeImage
     */
    public function getFull()
    {
        return $this->full;
    }

    /**
     * @param GalleryFullSizeImage $full
     */
    public function setFull(Full $full)
    {
        $this->full = $full;
    }

    /**
     * @return GalleryThumbnailImage
     */
    public function getThumb()
    {
        return $this->thumb;
    }

    /**
     * @param GalleryThumbnailImage $thumb
     */
    public function setThumb(Thumb $thumb)
    {
        $this->thumb = $thumb;
    }

    /**
     * @return \DateTime
     */
    public function getLastModified()
    {
        return $this->lastModified;
    }

    /**
     * @param \DateTime $lastModified
     */
    public function setLastModified(\DateTime $lastModified)
    {
        $this->lastModified = $lastModified;
    }
}

// ----

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="GalleryFullSizeImage", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */
class GalleryFullSizeImage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="GalleryImage", inversedBy="full")
     * @ORM\JoinColumn(name="galleryImageId", referencedColumnName="id", onDelete="SET NULL")
     */
    private $galleryImage;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $path;

    /**
     * @Assert\Image(maxSize="6000000")
     */
    private $file;

    private $tmp;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getGalleryImage()
    {
        return $this->galleryImage;
    }

    public function setGalleryImage(GalleryImage $galleryImage)
    {
        $this->galleryImage = $galleryImage;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__ . '/../../../../web/' . $this->getUploadDir() . '/full';
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'uploads/gallery';
    }

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
        // check if we have an old image path
        if (is_file($this->getAbsolutePath())) {
            // store the old name to delete after the update
            $this->tmp = $this->getAbsolutePath();
        } else {
            $this->path = 'initial';
        }
    }

    /**
     * Returns file
     *
     * @return mixed
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) {
            $this->path = $this->getFile()->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->getFile()) {
            return;
        }

        // check if we have an old image
        if (isset($this->tmp)) {
            // delete the old image
            unlink($this->tmp);
            // clear the temp image path
            $this->tmp = null;
        }

        $this->getFile()->move(
            $this->getUploadRootDir(),
            $this->id . '.' . $this->getFile()->guessExtension()
        );

        $this->setFile(null);
        $this->galleryImage->setLastModified(new \DateTime(null));
    }

    /**
     * @ORM\PreRemove()
     */
    public function storeFilenameForRemove()
    {
        $this->tmp = $this->getAbsolutePath();
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if (isset($this->tmp)) {
            unlink($this->tmp);
            $this->galleryImage->setLastModified(new \DateTime(null));
        }
    }

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->id . '.' . $this->path;
    }
}

// ----

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="GalleryThumbnailImage", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */
class GalleryThumbnailImage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="GalleryImage", inversedBy="thumb")
     * @ORM\JoinColumn(name="galleryImageId", referencedColumnName="id", onDelete="SET NULL")
     */
    private $galleryImage;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $path;

    /**
     * @Assert\Image(maxSize="6000000")
     */
    private $file;

    private $tmp;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getGalleryImage()
    {
        return $this->galleryImage;
    }

    public function setGalleryImage(GalleryImage $galleryImage)
    {
        $this->galleryImage = $galleryImage;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__ . '/../../../../web/' . $this->getUploadDir() . '/thumbs';
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'uploads/gallery';
    }

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
        // check if we have an old image path
        if (is_file($this->getAbsolutePath())) {
            // store the old name to delete after the update
            $this->tmp = $this->getAbsolutePath();
        } else {
            $this->path = 'initial';
        }
    }

    /**
     * Returns file
     *
     * @return mixed
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) {
            $this->path = $this->getFile()->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->getFile()) {
            return;
        }

        // check if we have an old image
        if (isset($this->tmp)) {
            // delete the old image
            unlink($this->tmp);
            // clear the temp image path
            $this->tmp = null;
        }

        $this->getFile()->move(
            $this->getUploadRootDir(),
            $this->id . '.' . $this->getFile()->guessExtension()
        );

        $this->setFile(null);
        $this->galleryImage->setLastModified(new \DateTime(null));
    }

    /**
     * @ORM\PreRemove()
     */
    public function storeFilenameForRemove()
    {
        $this->tmp = $this->getAbsolutePath();
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if (isset($this->tmp)) {
            unlink($this->tmp);
            $this->galleryImage->setLastModified(new \DateTime(null));
        }
    }

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->id . '.' . $this->path;
    }
}

И когда я пытаюсь просмотреть форму, я получаю следующее сообщение об ошибке из UnexpectedTypeException:

Ожидаемый аргумент типа "string" или "Symfony\Component\Form\FormTypeInterface", "MajorProductions\SewingDiva\SiteBundle\Entity\GalleryThumbnailImage"

Таким образом, он задыхается от FormBuilder добавляя мое поле GalleryThumbnailImage, думая, что он должен поддерживаться строкой, а не этим объектом. Однако я действительно не знаю, почему это так. Может быть, потому, что я использовал псевдонимы пространства имен в GalleryImage (Thumb вместо GalleryThumbnailImage и Full вместо GalleryFullSizeImage)? Или я пропущу что-то очевидное?


EDIT: проблема остается даже после создания типов форм для GalleryFullSizeImage и GalleryThumbnailImage:

namespace MajorProductions\SewingDiva\SiteBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GalleryFullSizeImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file', 'file');
    }

    public function getName()
    {
        return 'galleryFullSizeImage';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'MajorProductions\SewingDiva\SiteBundle\Entity\GalleryFullSizeImage'));
    }
}

// ----

namespace MajorProductions\SewingDiva\SiteBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GalleryThumbnailImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file', 'file');
    }

    public function getName()
    {
        return 'galleryThumbnailImage';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'MajorProductions\SewingDiva\SiteBundle\Entity\GalleryThumbnailImage'));
    }
}

Обратите внимание, что где / / ---- записано в моем коде, которое представляет конец одного файла и начало другого. Учитывая длину кода моей сущности со всеми аннотациями Doctrine, я решил, что сохраню некоторое вертикальное пространство, поставив здесь код отдельных классов в одни и те же блоки кода.

Теги:

1 ответ

1
Лучший ответ

Ты используешь:

$builder
    ->add('thumb', new GalleryThumbnailImage(), array('label' => 'Thumbnail Image'))
    ->add('full', new GalleryFullSizeImage(), array('label' => 'Full Size Image'));

Напомним, что аргументы FormBuilder#add(): public function add($child, $type = null, array $options = array()). Вместо типа $type вы, похоже, передаете сущность. Классы, которые вы хотите передать здесь, - GalleryThumbnailImageType и GalleryFullSizeImageType. Эти классы реализуют FormTypeInterface, поэтому все в порядке!

Код, который вам нужно использовать:

$builder
    ->add('thumb', new GalleryThumbnailImageType(), array('label' => 'Thumbnail Image'))
    ->add('full', new GalleryFullSizeImageType(), array('label' => 'Full Size Image'));
  • 0
    Что действительно печально, так это то, что я основываю это на другом проекте, который имеет аналогичную настройку parent-> child с обработкой файлов, и он имеет тип формы прямо здесь. Я смотрел на это всю ночь вчера вечером, но не заметил этого. Тьфу. Спасибо за помощь :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню